1 /*
   2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 
  30 import com.sun.tools.javac.code.*;
  31 import com.sun.tools.javac.jvm.*;
  32 import com.sun.tools.javac.main.RecognizedOptions.PkgInfo;
  33 import com.sun.tools.javac.tree.*;
  34 import com.sun.tools.javac.util.*;
  35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  36 import com.sun.tools.javac.util.List;
  37 
  38 import com.sun.tools.javac.code.Symbol.*;
  39 import com.sun.tools.javac.tree.JCTree.*;
  40 import com.sun.tools.javac.code.Type.*;
  41 
  42 import com.sun.tools.javac.jvm.Target;
  43 
  44 import static com.sun.tools.javac.code.Flags.*;
  45 import static com.sun.tools.javac.code.Kinds.*;
  46 import static com.sun.tools.javac.code.TypeTags.*;
  47 import static com.sun.tools.javac.jvm.ByteCodes.*;
  48 
  49 /** This pass translates away some syntactic sugar: inner classes,
  50  *  class literals, assertions, foreach loops, etc.
  51  *
  52  *  <p><b>This is NOT part of any supported API.
  53  *  If you write code that depends on this, you do so at your own risk.
  54  *  This code and its internal interfaces are subject to change or
  55  *  deletion without notice.</b>
  56  */
  57 public class Lower extends TreeTranslator {
  58     protected static final Context.Key<Lower> lowerKey =
  59         new Context.Key<Lower>();
  60 
  61     public static Lower instance(Context context) {
  62         Lower instance = context.get(lowerKey);
  63         if (instance == null)
  64             instance = new Lower(context);
  65         return instance;
  66     }
  67 
  68     private Names names;
  69     private Log log;
  70     private Symtab syms;
  71     private Resolve rs;
  72     private Check chk;
  73     private Attr attr;
  74     private TreeMaker make;
  75     private DiagnosticPosition make_pos;
  76     private ClassWriter writer;
  77     private ClassReader reader;
  78     private ConstFold cfolder;
  79     private Target target;
  80     private Source source;
  81     private boolean allowEnums;
  82     private final Name dollarAssertionsDisabled;
  83     private final Name classDollar;
  84     private Types types;
  85     private boolean debugLower;
  86     private PkgInfo pkginfoOpt;
  87 
  88     protected Lower(Context context) {
  89         context.put(lowerKey, this);
  90         names = Names.instance(context);
  91         log = Log.instance(context);
  92         syms = Symtab.instance(context);
  93         rs = Resolve.instance(context);
  94         chk = Check.instance(context);
  95         attr = Attr.instance(context);
  96         make = TreeMaker.instance(context);
  97         writer = ClassWriter.instance(context);
  98         reader = ClassReader.instance(context);
  99         cfolder = ConstFold.instance(context);
 100         target = Target.instance(context);
 101         source = Source.instance(context);
 102         allowEnums = source.allowEnums();
 103         dollarAssertionsDisabled = names.
 104             fromString(target.syntheticNameChar() + "assertionsDisabled");
 105         classDollar = names.
 106             fromString("class" + target.syntheticNameChar());
 107 
 108         types = Types.instance(context);
 109         Options options = Options.instance(context);
 110         debugLower = options.isSet("debuglower");
 111         pkginfoOpt = PkgInfo.get(options);
 112     }
 113 
 114     /** The currently enclosing class.
 115      */
 116     ClassSymbol currentClass;
 117 
 118     /** A queue of all translated classes.
 119      */
 120     ListBuffer<JCTree> translated;
 121 
 122     /** Environment for symbol lookup, set by translateTopLevelClass.
 123      */
 124     Env<AttrContext> attrEnv;
 125 
 126     /** A hash table mapping syntax trees to their ending source positions.
 127      */
 128     Map<JCTree, Integer> endPositions;
 129 
 130 /**************************************************************************
 131  * Global mappings
 132  *************************************************************************/
 133 
 134     /** A hash table mapping local classes to their definitions.
 135      */
 136     Map<ClassSymbol, JCClassDecl> classdefs;
 137 
 138     /** A hash table mapping virtual accessed symbols in outer subclasses
 139      *  to the actually referred symbol in superclasses.
 140      */
 141     Map<Symbol,Symbol> actualSymbols;
 142 
 143     /** The current method definition.
 144      */
 145     JCMethodDecl currentMethodDef;
 146 
 147     /** The current method symbol.
 148      */
 149     MethodSymbol currentMethodSym;
 150 
 151     /** The currently enclosing outermost class definition.
 152      */
 153     JCClassDecl outermostClassDef;
 154 
 155     /** The currently enclosing outermost member definition.
 156      */
 157     JCTree outermostMemberDef;
 158 
 159     /** A navigator class for assembling a mapping from local class symbols
 160      *  to class definition trees.
 161      *  There is only one case; all other cases simply traverse down the tree.
 162      */
 163     class ClassMap extends TreeScanner {
 164 
 165         /** All encountered class defs are entered into classdefs table.
 166          */
 167         public void visitClassDef(JCClassDecl tree) {
 168             classdefs.put(tree.sym, tree);
 169             super.visitClassDef(tree);
 170         }
 171     }
 172     ClassMap classMap = new ClassMap();
 173 
 174     /** Map a class symbol to its definition.
 175      *  @param c    The class symbol of which we want to determine the definition.
 176      */
 177     JCClassDecl classDef(ClassSymbol c) {
 178         // First lookup the class in the classdefs table.
 179         JCClassDecl def = classdefs.get(c);
 180         if (def == null && outermostMemberDef != null) {
 181             // If this fails, traverse outermost member definition, entering all
 182             // local classes into classdefs, and try again.
 183             classMap.scan(outermostMemberDef);
 184             def = classdefs.get(c);
 185         }
 186         if (def == null) {
 187             // If this fails, traverse outermost class definition, entering all
 188             // local classes into classdefs, and try again.
 189             classMap.scan(outermostClassDef);
 190             def = classdefs.get(c);
 191         }
 192         return def;
 193     }
 194 
 195     /** A hash table mapping class symbols to lists of free variables.
 196      *  accessed by them. Only free variables of the method immediately containing
 197      *  a class are associated with that class.
 198      */
 199     Map<ClassSymbol,List<VarSymbol>> freevarCache;
 200 
 201     /** A navigator class for collecting the free variables accessed
 202      *  from a local class.
 203      *  There is only one case; all other cases simply traverse down the tree.
 204      */
 205     class FreeVarCollector extends TreeScanner {
 206 
 207         /** The owner of the local class.
 208          */
 209         Symbol owner;
 210 
 211         /** The local class.
 212          */
 213         ClassSymbol clazz;
 214 
 215         /** The list of owner's variables accessed from within the local class,
 216          *  without any duplicates.
 217          */
 218         List<VarSymbol> fvs;
 219 
 220         FreeVarCollector(ClassSymbol clazz) {
 221             this.clazz = clazz;
 222             this.owner = clazz.owner;
 223             this.fvs = List.nil();
 224         }
 225 
 226         /** Add free variable to fvs list unless it is already there.
 227          */
 228         private void addFreeVar(VarSymbol v) {
 229             for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
 230                 if (l.head == v) return;
 231             fvs = fvs.prepend(v);
 232         }
 233 
 234         /** Add all free variables of class c to fvs list
 235          *  unless they are already there.
 236          */
 237         private void addFreeVars(ClassSymbol c) {
 238             List<VarSymbol> fvs = freevarCache.get(c);
 239             if (fvs != null) {
 240                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
 241                     addFreeVar(l.head);
 242                 }
 243             }
 244         }
 245 
 246         /** If tree refers to a variable in owner of local class, add it to
 247          *  free variables list.
 248          */
 249         public void visitIdent(JCIdent tree) {
 250             result = tree;
 251             visitSymbol(tree.sym);
 252         }
 253         // where
 254         private void visitSymbol(Symbol _sym) {
 255             Symbol sym = _sym;
 256             if (sym.kind == VAR || sym.kind == MTH) {
 257                 while (sym != null && sym.owner != owner)
 258                     sym = proxies.lookup(proxyName(sym.name)).sym;
 259                 if (sym != null && sym.owner == owner) {
 260                     VarSymbol v = (VarSymbol)sym;
 261                     if (v.getConstValue() == null) {
 262                         addFreeVar(v);
 263                     }
 264                 } else {
 265                     if (outerThisStack.head != null &&
 266                         outerThisStack.head != _sym)
 267                         visitSymbol(outerThisStack.head);
 268                 }
 269             }
 270         }
 271 
 272         /** If tree refers to a class instance creation expression
 273          *  add all free variables of the freshly created class.
 274          */
 275         public void visitNewClass(JCNewClass tree) {
 276             ClassSymbol c = (ClassSymbol)tree.constructor.owner;
 277             addFreeVars(c);
 278             if (tree.encl == null &&
 279                 c.hasOuterInstance() &&
 280                 outerThisStack.head != null)
 281                 visitSymbol(outerThisStack.head);
 282             super.visitNewClass(tree);
 283         }
 284 
 285         /** If tree refers to a qualified this or super expression
 286          *  for anything but the current class, add the outer this
 287          *  stack as a free variable.
 288          */
 289         public void visitSelect(JCFieldAccess tree) {
 290             if ((tree.name == names._this || tree.name == names._super) &&
 291                 tree.selected.type.tsym != clazz &&
 292                 outerThisStack.head != null)
 293                 visitSymbol(outerThisStack.head);
 294             super.visitSelect(tree);
 295         }
 296 
 297         /** If tree refers to a superclass constructor call,
 298          *  add all free variables of the superclass.
 299          */
 300         public void visitApply(JCMethodInvocation tree) {
 301             if (TreeInfo.name(tree.meth) == names._super) {
 302                 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
 303                 Symbol constructor = TreeInfo.symbol(tree.meth);
 304                 ClassSymbol c = (ClassSymbol)constructor.owner;
 305                 if (c.hasOuterInstance() &&
 306                     tree.meth.getTag() != JCTree.SELECT &&
 307                     outerThisStack.head != null)
 308                     visitSymbol(outerThisStack.head);
 309             }
 310             super.visitApply(tree);
 311         }
 312     }
 313 
 314     /** Return the variables accessed from within a local class, which
 315      *  are declared in the local class' owner.
 316      *  (in reverse order of first access).
 317      */
 318     List<VarSymbol> freevars(ClassSymbol c)  {
 319         if ((c.owner.kind & (VAR | MTH)) != 0) {
 320             List<VarSymbol> fvs = freevarCache.get(c);
 321             if (fvs == null) {
 322                 FreeVarCollector collector = new FreeVarCollector(c);
 323                 collector.scan(classDef(c));
 324                 fvs = collector.fvs;
 325                 freevarCache.put(c, fvs);
 326             }
 327             return fvs;
 328         } else {
 329             return List.nil();
 330         }
 331     }
 332 
 333     Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<TypeSymbol,EnumMapping>();
 334 
 335     EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
 336         EnumMapping map = enumSwitchMap.get(enumClass);
 337         if (map == null)
 338             enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
 339         return map;
 340     }
 341 
 342     /** This map gives a translation table to be used for enum
 343      *  switches.
 344      *
 345      *  <p>For each enum that appears as the type of a switch
 346      *  expression, we maintain an EnumMapping to assist in the
 347      *  translation, as exemplified by the following example:
 348      *
 349      *  <p>we translate
 350      *  <pre>
 351      *          switch(colorExpression) {
 352      *          case red: stmt1;
 353      *          case green: stmt2;
 354      *          }
 355      *  </pre>
 356      *  into
 357      *  <pre>
 358      *          switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
 359      *          case 1: stmt1;
 360      *          case 2: stmt2
 361      *          }
 362      *  </pre>
 363      *  with the auxiliary table initialized as follows:
 364      *  <pre>
 365      *          class Outer$0 {
 366      *              synthetic final int[] $EnumMap$Color = new int[Color.values().length];
 367      *              static {
 368      *                  try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
 369      *                  try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
 370      *              }
 371      *          }
 372      *  </pre>
 373      *  class EnumMapping provides mapping data and support methods for this translation.
 374      */
 375     class EnumMapping {
 376         EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
 377             this.forEnum = forEnum;
 378             this.values = new LinkedHashMap<VarSymbol,Integer>();
 379             this.pos = pos;
 380             Name varName = names
 381                 .fromString(target.syntheticNameChar() +
 382                             "SwitchMap" +
 383                             target.syntheticNameChar() +
 384                             writer.xClassName(forEnum.type).toString()
 385                             .replace('/', '.')
 386                             .replace('.', target.syntheticNameChar()));
 387             ClassSymbol outerCacheClass = outerCacheClass();
 388             this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
 389                                         varName,
 390                                         new ArrayType(syms.intType, syms.arrayClass),
 391                                         outerCacheClass);
 392             enterSynthetic(pos, mapVar, outerCacheClass.members());
 393         }
 394 
 395         DiagnosticPosition pos = null;
 396 
 397         // the next value to use
 398         int next = 1; // 0 (unused map elements) go to the default label
 399 
 400         // the enum for which this is a map
 401         final TypeSymbol forEnum;
 402 
 403         // the field containing the map
 404         final VarSymbol mapVar;
 405 
 406         // the mapped values
 407         final Map<VarSymbol,Integer> values;
 408 
 409         JCLiteral forConstant(VarSymbol v) {
 410             Integer result = values.get(v);
 411             if (result == null)
 412                 values.put(v, result = next++);
 413             return make.Literal(result);
 414         }
 415 
 416         // generate the field initializer for the map
 417         void translate() {
 418             make.at(pos.getStartPosition());
 419             JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
 420 
 421             // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
 422             MethodSymbol valuesMethod = lookupMethod(pos,
 423                                                      names.values,
 424                                                      forEnum.type,
 425                                                      List.<Type>nil());
 426             JCExpression size = make // Color.values().length
 427                 .Select(make.App(make.QualIdent(valuesMethod)),
 428                         syms.lengthVar);
 429             JCExpression mapVarInit = make
 430                 .NewArray(make.Type(syms.intType), List.of(size), null)
 431                 .setType(new ArrayType(syms.intType, syms.arrayClass));
 432 
 433             // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
 434             ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
 435             Symbol ordinalMethod = lookupMethod(pos,
 436                                                 names.ordinal,
 437                                                 forEnum.type,
 438                                                 List.<Type>nil());
 439             List<JCCatch> catcher = List.<JCCatch>nil()
 440                 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
 441                                                               syms.noSuchFieldErrorType,
 442                                                               syms.noSymbol),
 443                                                 null),
 444                                     make.Block(0, List.<JCStatement>nil())));
 445             for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
 446                 VarSymbol enumerator = e.getKey();
 447                 Integer mappedValue = e.getValue();
 448                 JCExpression assign = make
 449                     .Assign(make.Indexed(mapVar,
 450                                          make.App(make.Select(make.QualIdent(enumerator),
 451                                                               ordinalMethod))),
 452                             make.Literal(mappedValue))
 453                     .setType(syms.intType);
 454                 JCStatement exec = make.Exec(assign);
 455                 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
 456                 stmts.append(_try);
 457             }
 458 
 459             owner.defs = owner.defs
 460                 .prepend(make.Block(STATIC, stmts.toList()))
 461                 .prepend(make.VarDef(mapVar, mapVarInit));
 462         }
 463     }
 464 
 465 
 466 /**************************************************************************
 467  * Tree building blocks
 468  *************************************************************************/
 469 
 470     /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
 471      *  pos as make_pos, for use in diagnostics.
 472      **/
 473     TreeMaker make_at(DiagnosticPosition pos) {
 474         make_pos = pos;
 475         return make.at(pos);
 476     }
 477 
 478     /** Make an attributed tree representing a literal. This will be an
 479      *  Ident node in the case of boolean literals, a Literal node in all
 480      *  other cases.
 481      *  @param type       The literal's type.
 482      *  @param value      The literal's value.
 483      */
 484     JCExpression makeLit(Type type, Object value) {
 485         return make.Literal(type.tag, value).setType(type.constType(value));
 486     }
 487 
 488     /** Make an attributed tree representing null.
 489      */
 490     JCExpression makeNull() {
 491         return makeLit(syms.botType, null);
 492     }
 493 
 494     /** Make an attributed class instance creation expression.
 495      *  @param ctype    The class type.
 496      *  @param args     The constructor arguments.
 497      */
 498     JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
 499         JCNewClass tree = make.NewClass(null,
 500             null, make.QualIdent(ctype.tsym), args, null);
 501         tree.constructor = rs.resolveConstructor(
 502             make_pos, attrEnv, ctype, TreeInfo.types(args), null, false, false);
 503         tree.type = ctype;
 504         return tree;
 505     }
 506 
 507     /** Make an attributed unary expression.
 508      *  @param optag    The operators tree tag.
 509      *  @param arg      The operator's argument.
 510      */
 511     JCUnary makeUnary(int optag, JCExpression arg) {
 512         JCUnary tree = make.Unary(optag, arg);
 513         tree.operator = rs.resolveUnaryOperator(
 514             make_pos, optag, attrEnv, arg.type);
 515         tree.type = tree.operator.type.getReturnType();
 516         return tree;
 517     }
 518 
 519     /** Make an attributed binary expression.
 520      *  @param optag    The operators tree tag.
 521      *  @param lhs      The operator's left argument.
 522      *  @param rhs      The operator's right argument.
 523      */
 524     JCBinary makeBinary(int optag, JCExpression lhs, JCExpression rhs) {
 525         JCBinary tree = make.Binary(optag, lhs, rhs);
 526         tree.operator = rs.resolveBinaryOperator(
 527             make_pos, optag, attrEnv, lhs.type, rhs.type);
 528         tree.type = tree.operator.type.getReturnType();
 529         return tree;
 530     }
 531 
 532     /** Make an attributed assignop expression.
 533      *  @param optag    The operators tree tag.
 534      *  @param lhs      The operator's left argument.
 535      *  @param rhs      The operator's right argument.
 536      */
 537     JCAssignOp makeAssignop(int optag, JCTree lhs, JCTree rhs) {
 538         JCAssignOp tree = make.Assignop(optag, lhs, rhs);
 539         tree.operator = rs.resolveBinaryOperator(
 540             make_pos, tree.getTag() - JCTree.ASGOffset, attrEnv, lhs.type, rhs.type);
 541         tree.type = lhs.type;
 542         return tree;
 543     }
 544 
 545     /** Convert tree into string object, unless it has already a
 546      *  reference type..
 547      */
 548     JCExpression makeString(JCExpression tree) {
 549         if (tree.type.tag >= CLASS) {
 550             return tree;
 551         } else {
 552             Symbol valueOfSym = lookupMethod(tree.pos(),
 553                                              names.valueOf,
 554                                              syms.stringType,
 555                                              List.of(tree.type));
 556             return make.App(make.QualIdent(valueOfSym), List.of(tree));
 557         }
 558     }
 559 
 560     /** Create an empty anonymous class definition and enter and complete
 561      *  its symbol. Return the class definition's symbol.
 562      *  and create
 563      *  @param flags    The class symbol's flags
 564      *  @param owner    The class symbol's owner
 565      */
 566     ClassSymbol makeEmptyClass(long flags, ClassSymbol owner) {
 567         // Create class symbol.
 568         ClassSymbol c = reader.defineClass(names.empty, owner);
 569         c.flatname = chk.localClassName(c);
 570         c.sourcefile = owner.sourcefile;
 571         c.completer = null;
 572         c.members_field = new Scope(c);
 573         c.flags_field = flags;
 574         ClassType ctype = (ClassType) c.type;
 575         ctype.supertype_field = syms.objectType;
 576         ctype.interfaces_field = List.nil();
 577 
 578         JCClassDecl odef = classDef(owner);
 579 
 580         // Enter class symbol in owner scope and compiled table.
 581         enterSynthetic(odef.pos(), c, owner.members());
 582         chk.compiled.put(c.flatname, c);
 583 
 584         // Create class definition tree.
 585         JCClassDecl cdef = make.ClassDef(
 586             make.Modifiers(flags), names.empty,
 587             List.<JCTypeParameter>nil(),
 588             null, List.<JCExpression>nil(), List.<JCTree>nil());
 589         cdef.sym = c;
 590         cdef.type = c.type;
 591 
 592         // Append class definition tree to owner's definitions.
 593         odef.defs = odef.defs.prepend(cdef);
 594 
 595         return c;
 596     }
 597 
 598 /**************************************************************************
 599  * Symbol manipulation utilities
 600  *************************************************************************/
 601 
 602     /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
 603      *  @param pos           Position for error reporting.
 604      *  @param sym           The symbol.
 605      *  @param s             The scope.
 606      */
 607     private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
 608         s.enter(sym);
 609     }
 610 
 611     /** Create a fresh synthetic name within a given scope - the unique name is
 612      *  obtained by appending '$' chars at the end of the name until no match
 613      *  is found.
 614      *
 615      * @param name base name
 616      * @param s scope in which the name has to be unique
 617      * @return fresh synthetic name
 618      */
 619     private Name makeSyntheticName(Name name, Scope s) {
 620         do {
 621             name = name.append(
 622                     target.syntheticNameChar(),
 623                     names.empty);
 624         } while (lookupSynthetic(name, s) != null);
 625         return name;
 626     }
 627 
 628     /** Check whether synthetic symbols generated during lowering conflict
 629      *  with user-defined symbols.
 630      *
 631      *  @param translatedTrees lowered class trees
 632      */
 633     void checkConflicts(List<JCTree> translatedTrees) {
 634         for (JCTree t : translatedTrees) {
 635             t.accept(conflictsChecker);
 636         }
 637     }
 638 
 639     JCTree.Visitor conflictsChecker = new TreeScanner() {
 640 
 641         TypeSymbol currentClass;
 642 
 643         @Override
 644         public void visitMethodDef(JCMethodDecl that) {
 645             chk.checkConflicts(that.pos(), that.sym, currentClass);
 646             super.visitMethodDef(that);
 647         }
 648 
 649         @Override
 650         public void visitVarDef(JCVariableDecl that) {
 651             if (that.sym.owner.kind == TYP) {
 652                 chk.checkConflicts(that.pos(), that.sym, currentClass);
 653             }
 654             super.visitVarDef(that);
 655         }
 656 
 657         @Override
 658         public void visitClassDef(JCClassDecl that) {
 659             TypeSymbol prevCurrentClass = currentClass;
 660             currentClass = that.sym;
 661             try {
 662                 super.visitClassDef(that);
 663             }
 664             finally {
 665                 currentClass = prevCurrentClass;
 666             }
 667         }
 668     };
 669 
 670     /** Look up a synthetic name in a given scope.
 671      *  @param scope        The scope.
 672      *  @param name         The name.
 673      */
 674     private Symbol lookupSynthetic(Name name, Scope s) {
 675         Symbol sym = s.lookup(name).sym;
 676         return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
 677     }
 678 
 679     /** Look up a method in a given scope.
 680      */
 681     private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
 682         return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, null);
 683     }
 684 
 685     /** Look up a constructor.
 686      */
 687     private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
 688         return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
 689     }
 690 
 691     /** Look up a field.
 692      */
 693     private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
 694         return rs.resolveInternalField(pos, attrEnv, qual, name);
 695     }
 696 
 697     /** Anon inner classes are used as access constructor tags.
 698      * accessConstructorTag will use an existing anon class if one is available,
 699      * and synthethise a class (with makeEmptyClass) if one is not available.
 700      * However, there is a small possibility that an existing class will not
 701      * be generated as expected if it is inside a conditional with a constant
 702      * expression. If that is found to be the case, create an empty class here.
 703      */
 704     private void checkAccessConstructorTags() {
 705         for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
 706             ClassSymbol c = l.head;
 707             if (isTranslatedClassAvailable(c))
 708                 continue;
 709             // Create class definition tree.
 710             JCClassDecl cdef = make.ClassDef(
 711                 make.Modifiers(STATIC | SYNTHETIC), names.empty,
 712                 List.<JCTypeParameter>nil(),
 713                 null, List.<JCExpression>nil(), List.<JCTree>nil());
 714             cdef.sym = c;
 715             cdef.type = c.type;
 716             // add it to the list of classes to be generated
 717             translated.append(cdef);
 718         }
 719     }
 720     // where
 721     private boolean isTranslatedClassAvailable(ClassSymbol c) {
 722         for (JCTree tree: translated) {
 723             if (tree.getTag() == JCTree.CLASSDEF
 724                     && ((JCClassDecl) tree).sym == c) {
 725                 return true;
 726             }
 727         }
 728         return false;
 729     }
 730 
 731 /**************************************************************************
 732  * Access methods
 733  *************************************************************************/
 734 
 735     /** Access codes for dereferencing, assignment,
 736      *  and pre/post increment/decrement.
 737      *  Access codes for assignment operations are determined by method accessCode
 738      *  below.
 739      *
 740      *  All access codes for accesses to the current class are even.
 741      *  If a member of the superclass should be accessed instead (because
 742      *  access was via a qualified super), add one to the corresponding code
 743      *  for the current class, making the number odd.
 744      *  This numbering scheme is used by the backend to decide whether
 745      *  to issue an invokevirtual or invokespecial call.
 746      *
 747      *  @see Gen.visitSelect(Select tree)
 748      */
 749     private static final int
 750         DEREFcode = 0,
 751         ASSIGNcode = 2,
 752         PREINCcode = 4,
 753         PREDECcode = 6,
 754         POSTINCcode = 8,
 755         POSTDECcode = 10,
 756         FIRSTASGOPcode = 12;
 757 
 758     /** Number of access codes
 759      */
 760     private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
 761 
 762     /** A mapping from symbols to their access numbers.
 763      */
 764     private Map<Symbol,Integer> accessNums;
 765 
 766     /** A mapping from symbols to an array of access symbols, indexed by
 767      *  access code.
 768      */
 769     private Map<Symbol,MethodSymbol[]> accessSyms;
 770 
 771     /** A mapping from (constructor) symbols to access constructor symbols.
 772      */
 773     private Map<Symbol,MethodSymbol> accessConstrs;
 774 
 775     /** A list of all class symbols used for access constructor tags.
 776      */
 777     private List<ClassSymbol> accessConstrTags;
 778 
 779     /** A queue for all accessed symbols.
 780      */
 781     private ListBuffer<Symbol> accessed;
 782 
 783     /** Map bytecode of binary operation to access code of corresponding
 784      *  assignment operation. This is always an even number.
 785      */
 786     private static int accessCode(int bytecode) {
 787         if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
 788             return (bytecode - iadd) * 2 + FIRSTASGOPcode;
 789         else if (bytecode == ByteCodes.string_add)
 790             return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
 791         else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
 792             return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
 793         else
 794             return -1;
 795     }
 796 
 797     /** return access code for identifier,
 798      *  @param tree     The tree representing the identifier use.
 799      *  @param enclOp   The closest enclosing operation node of tree,
 800      *                  null if tree is not a subtree of an operation.
 801      */
 802     private static int accessCode(JCTree tree, JCTree enclOp) {
 803         if (enclOp == null)
 804             return DEREFcode;
 805         else if (enclOp.getTag() == JCTree.ASSIGN &&
 806                  tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
 807             return ASSIGNcode;
 808         else if (JCTree.PREINC <= enclOp.getTag() && enclOp.getTag() <= JCTree.POSTDEC &&
 809                  tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
 810             return (enclOp.getTag() - JCTree.PREINC) * 2 + PREINCcode;
 811         else if (JCTree.BITOR_ASG <= enclOp.getTag() && enclOp.getTag() <= JCTree.MOD_ASG &&
 812                  tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
 813             return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
 814         else
 815             return DEREFcode;
 816     }
 817 
 818     /** Return binary operator that corresponds to given access code.
 819      */
 820     private OperatorSymbol binaryAccessOperator(int acode) {
 821         for (Scope.Entry e = syms.predefClass.members().elems;
 822              e != null;
 823              e = e.sibling) {
 824             if (e.sym instanceof OperatorSymbol) {
 825                 OperatorSymbol op = (OperatorSymbol)e.sym;
 826                 if (accessCode(op.opcode) == acode) return op;
 827             }
 828         }
 829         return null;
 830     }
 831 
 832     /** Return tree tag for assignment operation corresponding
 833      *  to given binary operator.
 834      */
 835     private static int treeTag(OperatorSymbol operator) {
 836         switch (operator.opcode) {
 837         case ByteCodes.ior: case ByteCodes.lor:
 838             return JCTree.BITOR_ASG;
 839         case ByteCodes.ixor: case ByteCodes.lxor:
 840             return JCTree.BITXOR_ASG;
 841         case ByteCodes.iand: case ByteCodes.land:
 842             return JCTree.BITAND_ASG;
 843         case ByteCodes.ishl: case ByteCodes.lshl:
 844         case ByteCodes.ishll: case ByteCodes.lshll:
 845             return JCTree.SL_ASG;
 846         case ByteCodes.ishr: case ByteCodes.lshr:
 847         case ByteCodes.ishrl: case ByteCodes.lshrl:
 848             return JCTree.SR_ASG;
 849         case ByteCodes.iushr: case ByteCodes.lushr:
 850         case ByteCodes.iushrl: case ByteCodes.lushrl:
 851             return JCTree.USR_ASG;
 852         case ByteCodes.iadd: case ByteCodes.ladd:
 853         case ByteCodes.fadd: case ByteCodes.dadd:
 854         case ByteCodes.string_add:
 855             return JCTree.PLUS_ASG;
 856         case ByteCodes.isub: case ByteCodes.lsub:
 857         case ByteCodes.fsub: case ByteCodes.dsub:
 858             return JCTree.MINUS_ASG;
 859         case ByteCodes.imul: case ByteCodes.lmul:
 860         case ByteCodes.fmul: case ByteCodes.dmul:
 861             return JCTree.MUL_ASG;
 862         case ByteCodes.idiv: case ByteCodes.ldiv:
 863         case ByteCodes.fdiv: case ByteCodes.ddiv:
 864             return JCTree.DIV_ASG;
 865         case ByteCodes.imod: case ByteCodes.lmod:
 866         case ByteCodes.fmod: case ByteCodes.dmod:
 867             return JCTree.MOD_ASG;
 868         default:
 869             throw new AssertionError();
 870         }
 871     }
 872 
 873     /** The name of the access method with number `anum' and access code `acode'.
 874      */
 875     Name accessName(int anum, int acode) {
 876         return names.fromString(
 877             "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
 878     }
 879 
 880     /** Return access symbol for a private or protected symbol from an inner class.
 881      *  @param sym        The accessed private symbol.
 882      *  @param tree       The accessing tree.
 883      *  @param enclOp     The closest enclosing operation node of tree,
 884      *                    null if tree is not a subtree of an operation.
 885      *  @param protAccess Is access to a protected symbol in another
 886      *                    package?
 887      *  @param refSuper   Is access via a (qualified) C.super?
 888      */
 889     MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
 890                               boolean protAccess, boolean refSuper) {
 891         ClassSymbol accOwner = refSuper && protAccess
 892             // For access via qualified super (T.super.x), place the
 893             // access symbol on T.
 894             ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
 895             // Otherwise pretend that the owner of an accessed
 896             // protected symbol is the enclosing class of the current
 897             // class which is a subclass of the symbol's owner.
 898             : accessClass(sym, protAccess, tree);
 899 
 900         Symbol vsym = sym;
 901         if (sym.owner != accOwner) {
 902             vsym = sym.clone(accOwner);
 903             actualSymbols.put(vsym, sym);
 904         }
 905 
 906         Integer anum              // The access number of the access method.
 907             = accessNums.get(vsym);
 908         if (anum == null) {
 909             anum = accessed.length();
 910             accessNums.put(vsym, anum);
 911             accessSyms.put(vsym, new MethodSymbol[NCODES]);
 912             accessed.append(vsym);
 913             // System.out.println("accessing " + vsym + " in " + vsym.location());
 914         }
 915 
 916         int acode;                // The access code of the access method.
 917         List<Type> argtypes;      // The argument types of the access method.
 918         Type restype;             // The result type of the access method.
 919         List<Type> thrown;        // The thrown exceptions of the access method.
 920         switch (vsym.kind) {
 921         case VAR:
 922             acode = accessCode(tree, enclOp);
 923             if (acode >= FIRSTASGOPcode) {
 924                 OperatorSymbol operator = binaryAccessOperator(acode);
 925                 if (operator.opcode == string_add)
 926                     argtypes = List.of(syms.objectType);
 927                 else
 928                     argtypes = operator.type.getParameterTypes().tail;
 929             } else if (acode == ASSIGNcode)
 930                 argtypes = List.of(vsym.erasure(types));
 931             else
 932                 argtypes = List.nil();
 933             restype = vsym.erasure(types);
 934             thrown = List.nil();
 935             break;
 936         case MTH:
 937             acode = DEREFcode;
 938             argtypes = vsym.erasure(types).getParameterTypes();
 939             restype = vsym.erasure(types).getReturnType();
 940             thrown = vsym.type.getThrownTypes();
 941             break;
 942         default:
 943             throw new AssertionError();
 944         }
 945 
 946         // For references via qualified super, increment acode by one,
 947         // making it odd.
 948         if (protAccess && refSuper) acode++;
 949 
 950         // Instance access methods get instance as first parameter.
 951         // For protected symbols this needs to be the instance as a member
 952         // of the type containing the accessed symbol, not the class
 953         // containing the access method.
 954         if ((vsym.flags() & STATIC) == 0) {
 955             argtypes = argtypes.prepend(vsym.owner.erasure(types));
 956         }
 957         MethodSymbol[] accessors = accessSyms.get(vsym);
 958         MethodSymbol accessor = accessors[acode];
 959         if (accessor == null) {
 960             accessor = new MethodSymbol(
 961                 STATIC | SYNTHETIC,
 962                 accessName(anum.intValue(), acode),
 963                 new MethodType(argtypes, restype, thrown, syms.methodClass),
 964                 accOwner);
 965             enterSynthetic(tree.pos(), accessor, accOwner.members());
 966             accessors[acode] = accessor;
 967         }
 968         return accessor;
 969     }
 970 
 971     /** The qualifier to be used for accessing a symbol in an outer class.
 972      *  This is either C.sym or C.this.sym, depending on whether or not
 973      *  sym is static.
 974      *  @param sym   The accessed symbol.
 975      */
 976     JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
 977         return (sym.flags() & STATIC) != 0
 978             ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
 979             : makeOwnerThis(pos, sym, true);
 980     }
 981 
 982     /** Do we need an access method to reference private symbol?
 983      */
 984     boolean needsPrivateAccess(Symbol sym) {
 985         if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
 986             return false;
 987         } else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
 988             // private constructor in local class: relax protection
 989             sym.flags_field &= ~PRIVATE;
 990             return false;
 991         } else {
 992             return true;
 993         }
 994     }
 995 
 996     /** Do we need an access method to reference symbol in other package?
 997      */
 998     boolean needsProtectedAccess(Symbol sym, JCTree tree) {
 999         if ((sym.flags() & PROTECTED) == 0 ||
1000             sym.owner.owner == currentClass.owner || // fast special case
1001             sym.packge() == currentClass.packge())
1002             return false;
1003         if (!currentClass.isSubClass(sym.owner, types))
1004             return true;
1005         if ((sym.flags() & STATIC) != 0 ||
1006             tree.getTag() != JCTree.SELECT ||
1007             TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
1008             return false;
1009         return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
1010     }
1011 
1012     /** The class in which an access method for given symbol goes.
1013      *  @param sym        The access symbol
1014      *  @param protAccess Is access to a protected symbol in another
1015      *                    package?
1016      */
1017     ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
1018         if (protAccess) {
1019             Symbol qualifier = null;
1020             ClassSymbol c = currentClass;
1021             if (tree.getTag() == JCTree.SELECT && (sym.flags() & STATIC) == 0) {
1022                 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
1023                 while (!qualifier.isSubClass(c, types)) {
1024                     c = c.owner.enclClass();
1025                 }
1026                 return c;
1027             } else {
1028                 while (!c.isSubClass(sym.owner, types)) {
1029                     c = c.owner.enclClass();
1030                 }
1031             }
1032             return c;
1033         } else {
1034             // the symbol is private
1035             return sym.owner.enclClass();
1036         }
1037     }
1038 
1039     /** Ensure that identifier is accessible, return tree accessing the identifier.
1040      *  @param sym      The accessed symbol.
1041      *  @param tree     The tree referring to the symbol.
1042      *  @param enclOp   The closest enclosing operation node of tree,
1043      *                  null if tree is not a subtree of an operation.
1044      *  @param refSuper Is access via a (qualified) C.super?
1045      */
1046     JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
1047         // Access a free variable via its proxy, or its proxy's proxy
1048         while (sym.kind == VAR && sym.owner.kind == MTH &&
1049             sym.owner.enclClass() != currentClass) {
1050             // A constant is replaced by its constant value.
1051             Object cv = ((VarSymbol)sym).getConstValue();
1052             if (cv != null) {
1053                 make.at(tree.pos);
1054                 return makeLit(sym.type, cv);
1055             }
1056             // Otherwise replace the variable by its proxy.
1057             sym = proxies.lookup(proxyName(sym.name)).sym;
1058             Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
1059             tree = make.at(tree.pos).Ident(sym);
1060         }
1061         JCExpression base = (tree.getTag() == JCTree.SELECT) ? ((JCFieldAccess) tree).selected : null;
1062         switch (sym.kind) {
1063         case TYP:
1064             if (sym.owner.kind != PCK) {
1065                 // Convert type idents to
1066                 // <flat name> or <package name> . <flat name>
1067                 Name flatname = Convert.shortName(sym.flatName());
1068                 while (base != null &&
1069                        TreeInfo.symbol(base) != null &&
1070                        TreeInfo.symbol(base).kind != PCK) {
1071                     base = (base.getTag() == JCTree.SELECT)
1072                         ? ((JCFieldAccess) base).selected
1073                         : null;
1074                 }
1075                 if (tree.getTag() == JCTree.IDENT) {
1076                     ((JCIdent) tree).name = flatname;
1077                 } else if (base == null) {
1078                     tree = make.at(tree.pos).Ident(sym);
1079                     ((JCIdent) tree).name = flatname;
1080                 } else {
1081                     ((JCFieldAccess) tree).selected = base;
1082                     ((JCFieldAccess) tree).name = flatname;
1083                 }
1084             }
1085             break;
1086         case MTH: case VAR:
1087             if (sym.owner.kind == TYP) {
1088 
1089                 // Access methods are required for
1090                 //  - private members,
1091                 //  - protected members in a superclass of an
1092                 //    enclosing class contained in another package.
1093                 //  - all non-private members accessed via a qualified super.
1094                 boolean protAccess = refSuper && !needsPrivateAccess(sym)
1095                     || needsProtectedAccess(sym, tree);
1096                 boolean accReq = protAccess || needsPrivateAccess(sym);
1097 
1098                 // A base has to be supplied for
1099                 //  - simple identifiers accessing variables in outer classes.
1100                 boolean baseReq =
1101                     base == null &&
1102                     sym.owner != syms.predefClass &&
1103                     !sym.isMemberOf(currentClass, types);
1104 
1105                 if (accReq || baseReq) {
1106                     make.at(tree.pos);
1107 
1108                     // Constants are replaced by their constant value.
1109                     if (sym.kind == VAR) {
1110                         Object cv = ((VarSymbol)sym).getConstValue();
1111                         if (cv != null) return makeLit(sym.type, cv);
1112                     }
1113 
1114                     // Private variables and methods are replaced by calls
1115                     // to their access methods.
1116                     if (accReq) {
1117                         List<JCExpression> args = List.nil();
1118                         if ((sym.flags() & STATIC) == 0) {
1119                             // Instance access methods get instance
1120                             // as first parameter.
1121                             if (base == null)
1122                                 base = makeOwnerThis(tree.pos(), sym, true);
1123                             args = args.prepend(base);
1124                             base = null;   // so we don't duplicate code
1125                         }
1126                         Symbol access = accessSymbol(sym, tree,
1127                                                      enclOp, protAccess,
1128                                                      refSuper);
1129                         JCExpression receiver = make.Select(
1130                             base != null ? base : make.QualIdent(access.owner),
1131                             access);
1132                         return make.App(receiver, args);
1133 
1134                     // Other accesses to members of outer classes get a
1135                     // qualifier.
1136                     } else if (baseReq) {
1137                         return make.at(tree.pos).Select(
1138                             accessBase(tree.pos(), sym), sym).setType(tree.type);
1139                     }
1140                 }
1141             }
1142         }
1143         return tree;
1144     }
1145 
1146     /** Ensure that identifier is accessible, return tree accessing the identifier.
1147      *  @param tree     The identifier tree.
1148      */
1149     JCExpression access(JCExpression tree) {
1150         Symbol sym = TreeInfo.symbol(tree);
1151         return sym == null ? tree : access(sym, tree, null, false);
1152     }
1153 
1154     /** Return access constructor for a private constructor,
1155      *  or the constructor itself, if no access constructor is needed.
1156      *  @param pos       The position to report diagnostics, if any.
1157      *  @param constr    The private constructor.
1158      */
1159     Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1160         if (needsPrivateAccess(constr)) {
1161             ClassSymbol accOwner = constr.owner.enclClass();
1162             MethodSymbol aconstr = accessConstrs.get(constr);
1163             if (aconstr == null) {
1164                 List<Type> argtypes = constr.type.getParameterTypes();
1165                 if ((accOwner.flags_field & ENUM) != 0)
1166                     argtypes = argtypes
1167                         .prepend(syms.intType)
1168                         .prepend(syms.stringType);
1169                 aconstr = new MethodSymbol(
1170                     SYNTHETIC,
1171                     names.init,
1172                     new MethodType(
1173                         argtypes.append(
1174                             accessConstructorTag().erasure(types)),
1175                         constr.type.getReturnType(),
1176                         constr.type.getThrownTypes(),
1177                         syms.methodClass),
1178                     accOwner);
1179                 enterSynthetic(pos, aconstr, accOwner.members());
1180                 accessConstrs.put(constr, aconstr);
1181                 accessed.append(constr);
1182             }
1183             return aconstr;
1184         } else {
1185             return constr;
1186         }
1187     }
1188 
1189     /** Return an anonymous class nested in this toplevel class.
1190      */
1191     ClassSymbol accessConstructorTag() {
1192         ClassSymbol topClass = currentClass.outermostClass();
1193         Name flatname = names.fromString("" + topClass.getQualifiedName() +
1194                                          target.syntheticNameChar() +
1195                                          "1");
1196         ClassSymbol ctag = chk.compiled.get(flatname);
1197         if (ctag == null)
1198             ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass);
1199         // keep a record of all tags, to verify that all are generated as required
1200         accessConstrTags = accessConstrTags.prepend(ctag);
1201         return ctag;
1202     }
1203 
1204     /** Add all required access methods for a private symbol to enclosing class.
1205      *  @param sym       The symbol.
1206      */
1207     void makeAccessible(Symbol sym) {
1208         JCClassDecl cdef = classDef(sym.owner.enclClass());
1209         if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
1210         if (sym.name == names.init) {
1211             cdef.defs = cdef.defs.prepend(
1212                 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
1213         } else {
1214             MethodSymbol[] accessors = accessSyms.get(sym);
1215             for (int i = 0; i < NCODES; i++) {
1216                 if (accessors[i] != null)
1217                     cdef.defs = cdef.defs.prepend(
1218                         accessDef(cdef.pos, sym, accessors[i], i));
1219             }
1220         }
1221     }
1222 
1223     /** Construct definition of an access method.
1224      *  @param pos        The source code position of the definition.
1225      *  @param vsym       The private or protected symbol.
1226      *  @param accessor   The access method for the symbol.
1227      *  @param acode      The access code.
1228      */
1229     JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
1230 //      System.err.println("access " + vsym + " with " + accessor);//DEBUG
1231         currentClass = vsym.owner.enclClass();
1232         make.at(pos);
1233         JCMethodDecl md = make.MethodDef(accessor, null);
1234 
1235         // Find actual symbol
1236         Symbol sym = actualSymbols.get(vsym);
1237         if (sym == null) sym = vsym;
1238 
1239         JCExpression ref;           // The tree referencing the private symbol.
1240         List<JCExpression> args;    // Any additional arguments to be passed along.
1241         if ((sym.flags() & STATIC) != 0) {
1242             ref = make.Ident(sym);
1243             args = make.Idents(md.params);
1244         } else {
1245             ref = make.Select(make.Ident(md.params.head), sym);
1246             args = make.Idents(md.params.tail);
1247         }
1248         JCStatement stat;          // The statement accessing the private symbol.
1249         if (sym.kind == VAR) {
1250             // Normalize out all odd access codes by taking floor modulo 2:
1251             int acode1 = acode - (acode & 1);
1252 
1253             JCExpression expr;      // The access method's return value.
1254             switch (acode1) {
1255             case DEREFcode:
1256                 expr = ref;
1257                 break;
1258             case ASSIGNcode:
1259                 expr = make.Assign(ref, args.head);
1260                 break;
1261             case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
1262                 expr = makeUnary(
1263                     ((acode1 - PREINCcode) >> 1) + JCTree.PREINC, ref);
1264                 break;
1265             default:
1266                 expr = make.Assignop(
1267                     treeTag(binaryAccessOperator(acode1)), ref, args.head);
1268                 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
1269             }
1270             stat = make.Return(expr.setType(sym.type));
1271         } else {
1272             stat = make.Call(make.App(ref, args));
1273         }
1274         md.body = make.Block(0, List.of(stat));
1275 
1276         // Make sure all parameters, result types and thrown exceptions
1277         // are accessible.
1278         for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
1279             l.head.vartype = access(l.head.vartype);
1280         md.restype = access(md.restype);
1281         for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
1282             l.head = access(l.head);
1283 
1284         return md;
1285     }
1286 
1287     /** Construct definition of an access constructor.
1288      *  @param pos        The source code position of the definition.
1289      *  @param constr     The private constructor.
1290      *  @param accessor   The access method for the constructor.
1291      */
1292     JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
1293         make.at(pos);
1294         JCMethodDecl md = make.MethodDef(accessor,
1295                                       accessor.externalType(types),
1296                                       null);
1297         JCIdent callee = make.Ident(names._this);
1298         callee.sym = constr;
1299         callee.type = constr.type;
1300         md.body =
1301             make.Block(0, List.<JCStatement>of(
1302                 make.Call(
1303                     make.App(
1304                         callee,
1305                         make.Idents(md.params.reverse().tail.reverse())))));
1306         return md;
1307     }
1308 
1309 /**************************************************************************
1310  * Free variables proxies and this$n
1311  *************************************************************************/
1312 
1313     /** A scope containing all free variable proxies for currently translated
1314      *  class, as well as its this$n symbol (if needed).
1315      *  Proxy scopes are nested in the same way classes are.
1316      *  Inside a constructor, proxies and any this$n symbol are duplicated
1317      *  in an additional innermost scope, where they represent the constructor
1318      *  parameters.
1319      */
1320     Scope proxies;
1321 
1322     /** A scope containing all unnamed resource variables/saved
1323      *  exception variables for translated TWR blocks
1324      */
1325     Scope twrVars;
1326 
1327     /** A stack containing the this$n field of the currently translated
1328      *  classes (if needed) in innermost first order.
1329      *  Inside a constructor, proxies and any this$n symbol are duplicated
1330      *  in an additional innermost scope, where they represent the constructor
1331      *  parameters.
1332      */
1333     List<VarSymbol> outerThisStack;
1334 
1335     /** The name of a free variable proxy.
1336      */
1337     Name proxyName(Name name) {
1338         return names.fromString("val" + target.syntheticNameChar() + name);
1339     }
1340 
1341     /** Proxy definitions for all free variables in given list, in reverse order.
1342      *  @param pos        The source code position of the definition.
1343      *  @param freevars   The free variables.
1344      *  @param owner      The class in which the definitions go.
1345      */
1346     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
1347         long flags = FINAL | SYNTHETIC;
1348         if (owner.kind == TYP &&
1349             target.usePrivateSyntheticFields())
1350             flags |= PRIVATE;
1351         List<JCVariableDecl> defs = List.nil();
1352         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
1353             VarSymbol v = l.head;
1354             VarSymbol proxy = new VarSymbol(
1355                 flags, proxyName(v.name), v.erasure(types), owner);
1356             proxies.enter(proxy);
1357             JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
1358             vd.vartype = access(vd.vartype);
1359             defs = defs.prepend(vd);
1360         }
1361         return defs;
1362     }
1363 
1364     /** The name of a this$n field
1365      *  @param type   The class referenced by the this$n field
1366      */
1367     Name outerThisName(Type type, Symbol owner) {
1368         Type t = type.getEnclosingType();
1369         int nestingLevel = 0;
1370         while (t.tag == CLASS) {
1371             t = t.getEnclosingType();
1372             nestingLevel++;
1373         }
1374         Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
1375         while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
1376             result = names.fromString(result.toString() + target.syntheticNameChar());
1377         return result;
1378     }
1379 
1380     /** Definition for this$n field.
1381      *  @param pos        The source code position of the definition.
1382      *  @param owner      The class in which the definition goes.
1383      */
1384     JCVariableDecl outerThisDef(int pos, Symbol owner) {
1385         long flags = FINAL | SYNTHETIC;
1386         if (owner.kind == TYP &&
1387             target.usePrivateSyntheticFields())
1388             flags |= PRIVATE;
1389         Type target = types.erasure(owner.enclClass().type.getEnclosingType());
1390         VarSymbol outerThis = new VarSymbol(
1391             flags, outerThisName(target, owner), target, owner);
1392         outerThisStack = outerThisStack.prepend(outerThis);
1393         JCVariableDecl vd = make.at(pos).VarDef(outerThis, null);
1394         vd.vartype = access(vd.vartype);
1395         return vd;
1396     }
1397 
1398     /** Return a list of trees that load the free variables in given list,
1399      *  in reverse order.
1400      *  @param pos          The source code position to be used for the trees.
1401      *  @param freevars     The list of free variables.
1402      */
1403     List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
1404         List<JCExpression> args = List.nil();
1405         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
1406             args = args.prepend(loadFreevar(pos, l.head));
1407         return args;
1408     }
1409 //where
1410         JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
1411             return access(v, make.at(pos).Ident(v), null, false);
1412         }
1413 
1414     /** Construct a tree simulating the expression <C.this>.
1415      *  @param pos           The source code position to be used for the tree.
1416      *  @param c             The qualifier class.
1417      */
1418     JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
1419         if (currentClass == c) {
1420             // in this case, `this' works fine
1421             return make.at(pos).This(c.erasure(types));
1422         } else {
1423             // need to go via this$n
1424             return makeOuterThis(pos, c);
1425         }
1426     }
1427 
1428     /** Optionally replace a try statement with an automatic resource
1429      *  management (ARM) block.
1430      * @param tree  The try statement to inspect.
1431      * @return      An ARM block, or the original try block if there are no
1432      *              resources to manage.
1433      */
1434     JCTree makeArmTry(JCTry tree) {
1435         make_at(tree.pos());
1436         twrVars = twrVars.dup();
1437         JCBlock armBlock = makeArmBlock(tree.resources, tree.body, 0);
1438         if (tree.catchers.isEmpty() && tree.finalizer == null)
1439             result = translate(armBlock);
1440         else
1441             result = translate(make.Try(armBlock, tree.catchers, tree.finalizer));
1442         twrVars = twrVars.leave();
1443         return result;
1444     }
1445 
1446     private JCBlock makeArmBlock(List<JCTree> resources, JCBlock block, int depth) {
1447         if (resources.isEmpty())
1448             return block;
1449 
1450         // Add resource declaration or expression to block statements
1451         ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
1452         JCTree resource = resources.head;
1453         JCExpression expr = null;
1454         if (resource instanceof JCVariableDecl) {
1455             JCVariableDecl var = (JCVariableDecl) resource;
1456             expr = make.Ident(var.sym).setType(resource.type);
1457             stats.add(var);
1458         } else {
1459             Assert.check(resource instanceof JCExpression);
1460             VarSymbol syntheticTwrVar =
1461             new VarSymbol(SYNTHETIC | FINAL,
1462                           makeSyntheticName(names.fromString("twrVar" +
1463                                            depth), twrVars),
1464                           (resource.type.tag == TypeTags.BOT) ?
1465                           syms.autoCloseableType : resource.type,
1466                           currentMethodSym);
1467             twrVars.enter(syntheticTwrVar);
1468             JCVariableDecl syntheticTwrVarDecl =
1469                 make.VarDef(syntheticTwrVar, (JCExpression)resource);
1470             expr = (JCExpression)make.Ident(syntheticTwrVar);
1471             stats.add(syntheticTwrVarDecl);
1472         }
1473 
1474         // Add primaryException declaration
1475         VarSymbol primaryException =
1476             new VarSymbol(SYNTHETIC,
1477                           makeSyntheticName(names.fromString("primaryException" +
1478                           depth), twrVars),
1479                           syms.throwableType,
1480                           currentMethodSym);
1481         twrVars.enter(primaryException);
1482         JCVariableDecl primaryExceptionTreeDecl = make.VarDef(primaryException, makeNull());
1483         stats.add(primaryExceptionTreeDecl);
1484 
1485         // Create catch clause that saves exception and then rethrows it
1486         VarSymbol param =
1487             new VarSymbol(FINAL|SYNTHETIC,
1488                           names.fromString("t" +
1489                                            target.syntheticNameChar()),
1490                           syms.throwableType,
1491                           currentMethodSym);
1492         JCVariableDecl paramTree = make.VarDef(param, null);
1493         JCStatement assign = make.Assignment(primaryException, make.Ident(param));
1494         JCStatement rethrowStat = make.Throw(make.Ident(param));
1495         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(assign, rethrowStat));
1496         JCCatch catchClause = make.Catch(paramTree, catchBlock);
1497 
1498         int oldPos = make.pos;
1499         make.at(TreeInfo.endPos(block));
1500         JCBlock finallyClause = makeArmFinallyClause(primaryException, expr);
1501         make.at(oldPos);
1502         JCTry outerTry = make.Try(makeArmBlock(resources.tail, block, depth + 1),
1503                                   List.<JCCatch>of(catchClause),
1504                                   finallyClause);
1505         stats.add(outerTry);
1506         return make.Block(0L, stats.toList());
1507     }
1508 
1509     private JCBlock makeArmFinallyClause(Symbol primaryException, JCExpression resource) {
1510         // primaryException.addSuppressed(catchException);
1511         VarSymbol catchException =
1512             new VarSymbol(0, make.paramName(2),
1513                           syms.throwableType,
1514                           currentMethodSym);
1515         JCStatement addSuppressionStatement =
1516             make.Exec(makeCall(make.Ident(primaryException),
1517                                names.addSuppressed,
1518                                List.<JCExpression>of(make.Ident(catchException))));
1519 
1520         // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
1521         JCBlock tryBlock =
1522             make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
1523         JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
1524         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
1525         List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
1526         JCTry tryTree = make.Try(tryBlock, catchClauses, null);
1527 
1528         // if (resource != null) resourceClose;
1529         JCExpression nullCheck = makeBinary(JCTree.NE,
1530                                             make.Ident(primaryException),
1531                                             makeNull());
1532         JCIf closeIfStatement = make.If(nullCheck,
1533                                         tryTree,
1534                                         makeResourceCloseInvocation(resource));
1535         return make.Block(0L, List.<JCStatement>of(closeIfStatement));
1536     }
1537 
1538     private JCStatement makeResourceCloseInvocation(JCExpression resource) {
1539         // create resource.close() method invocation
1540         JCExpression resourceClose = makeCall(resource, names.close, List.<JCExpression>nil());
1541         return make.Exec(resourceClose);
1542     }
1543 
1544     /** Construct a tree that represents the outer instance
1545      *  <C.this>. Never pick the current `this'.
1546      *  @param pos           The source code position to be used for the tree.
1547      *  @param c             The qualifier class.
1548      */
1549     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1550         List<VarSymbol> ots = outerThisStack;
1551         if (ots.isEmpty()) {
1552             log.error(pos, "no.encl.instance.of.type.in.scope", c);
1553             Assert.error();
1554             return makeNull();
1555         }
1556         VarSymbol ot = ots.head;
1557         JCExpression tree = access(make.at(pos).Ident(ot));
1558         TypeSymbol otc = ot.type.tsym;
1559         while (otc != c) {
1560             do {
1561                 ots = ots.tail;
1562                 if (ots.isEmpty()) {
1563                     log.error(pos,
1564                               "no.encl.instance.of.type.in.scope",
1565                               c);
1566                     Assert.error(); // should have been caught in Attr
1567                     return tree;
1568                 }
1569                 ot = ots.head;
1570             } while (ot.owner != otc);
1571             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1572                 chk.earlyRefError(pos, c);
1573                 Assert.error(); // should have been caught in Attr
1574                 return makeNull();
1575             }
1576             tree = access(make.at(pos).Select(tree, ot));
1577             otc = ot.type.tsym;
1578         }
1579         return tree;
1580     }
1581 
1582     /** Construct a tree that represents the closest outer instance
1583      *  <C.this> such that the given symbol is a member of C.
1584      *  @param pos           The source code position to be used for the tree.
1585      *  @param sym           The accessed symbol.
1586      *  @param preciseMatch  should we accept a type that is a subtype of
1587      *                       sym's owner, even if it doesn't contain sym
1588      *                       due to hiding, overriding, or non-inheritance
1589      *                       due to protection?
1590      */
1591     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1592         Symbol c = sym.owner;
1593         if (preciseMatch ? sym.isMemberOf(currentClass, types)
1594                          : currentClass.isSubClass(sym.owner, types)) {
1595             // in this case, `this' works fine
1596             return make.at(pos).This(c.erasure(types));
1597         } else {
1598             // need to go via this$n
1599             return makeOwnerThisN(pos, sym, preciseMatch);
1600         }
1601     }
1602 
1603     /**
1604      * Similar to makeOwnerThis but will never pick "this".
1605      */
1606     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1607         Symbol c = sym.owner;
1608         List<VarSymbol> ots = outerThisStack;
1609         if (ots.isEmpty()) {
1610             log.error(pos, "no.encl.instance.of.type.in.scope", c);
1611             Assert.error();
1612             return makeNull();
1613         }
1614         VarSymbol ot = ots.head;
1615         JCExpression tree = access(make.at(pos).Ident(ot));
1616         TypeSymbol otc = ot.type.tsym;
1617         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1618             do {
1619                 ots = ots.tail;
1620                 if (ots.isEmpty()) {
1621                     log.error(pos,
1622                         "no.encl.instance.of.type.in.scope",
1623                         c);
1624                     Assert.error();
1625                     return tree;
1626                 }
1627                 ot = ots.head;
1628             } while (ot.owner != otc);
1629             tree = access(make.at(pos).Select(tree, ot));
1630             otc = ot.type.tsym;
1631         }
1632         return tree;
1633     }
1634 
1635     /** Return tree simulating the assignment <this.name = name>, where
1636      *  name is the name of a free variable.
1637      */
1638     JCStatement initField(int pos, Name name) {
1639         Scope.Entry e = proxies.lookup(name);
1640         Symbol rhs = e.sym;
1641         Assert.check(rhs.owner.kind == MTH);
1642         Symbol lhs = e.next().sym;
1643         Assert.check(rhs.owner.owner == lhs.owner);
1644         make.at(pos);
1645         return
1646             make.Exec(
1647                 make.Assign(
1648                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
1649                     make.Ident(rhs)).setType(lhs.erasure(types)));
1650     }
1651 
1652     /** Return tree simulating the assignment <this.this$n = this$n>.
1653      */
1654     JCStatement initOuterThis(int pos) {
1655         VarSymbol rhs = outerThisStack.head;
1656         Assert.check(rhs.owner.kind == MTH);
1657         VarSymbol lhs = outerThisStack.tail.head;
1658         Assert.check(rhs.owner.owner == lhs.owner);
1659         make.at(pos);
1660         return
1661             make.Exec(
1662                 make.Assign(
1663                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
1664                     make.Ident(rhs)).setType(lhs.erasure(types)));
1665     }
1666 
1667 /**************************************************************************
1668  * Code for .class
1669  *************************************************************************/
1670 
1671     /** Return the symbol of a class to contain a cache of
1672      *  compiler-generated statics such as class$ and the
1673      *  $assertionsDisabled flag.  We create an anonymous nested class
1674      *  (unless one already exists) and return its symbol.  However,
1675      *  for backward compatibility in 1.4 and earlier we use the
1676      *  top-level class itself.
1677      */
1678     private ClassSymbol outerCacheClass() {
1679         ClassSymbol clazz = outermostClassDef.sym;
1680         if ((clazz.flags() & INTERFACE) == 0 &&
1681             !target.useInnerCacheClass()) return clazz;
1682         Scope s = clazz.members();
1683         for (Scope.Entry e = s.elems; e != null; e = e.sibling)
1684             if (e.sym.kind == TYP &&
1685                 e.sym.name == names.empty &&
1686                 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
1687         return makeEmptyClass(STATIC | SYNTHETIC, clazz);
1688     }
1689 
1690     /** Return symbol for "class$" method. If there is no method definition
1691      *  for class$, construct one as follows:
1692      *
1693      *    class class$(String x0) {
1694      *      try {
1695      *        return Class.forName(x0);
1696      *      } catch (ClassNotFoundException x1) {
1697      *        throw new NoClassDefFoundError(x1.getMessage());
1698      *      }
1699      *    }
1700      */
1701     private MethodSymbol classDollarSym(DiagnosticPosition pos) {
1702         ClassSymbol outerCacheClass = outerCacheClass();
1703         MethodSymbol classDollarSym =
1704             (MethodSymbol)lookupSynthetic(classDollar,
1705                                           outerCacheClass.members());
1706         if (classDollarSym == null) {
1707             classDollarSym = new MethodSymbol(
1708                 STATIC | SYNTHETIC,
1709                 classDollar,
1710                 new MethodType(
1711                     List.of(syms.stringType),
1712                     types.erasure(syms.classType),
1713                     List.<Type>nil(),
1714                     syms.methodClass),
1715                 outerCacheClass);
1716             enterSynthetic(pos, classDollarSym, outerCacheClass.members());
1717 
1718             JCMethodDecl md = make.MethodDef(classDollarSym, null);
1719             try {
1720                 md.body = classDollarSymBody(pos, md);
1721             } catch (CompletionFailure ex) {
1722                 md.body = make.Block(0, List.<JCStatement>nil());
1723                 chk.completionError(pos, ex);
1724             }
1725             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1726             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
1727         }
1728         return classDollarSym;
1729     }
1730 
1731     /** Generate code for class$(String name). */
1732     JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
1733         MethodSymbol classDollarSym = md.sym;
1734         ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
1735 
1736         JCBlock returnResult;
1737 
1738         // in 1.4.2 and above, we use
1739         // Class.forName(String name, boolean init, ClassLoader loader);
1740         // which requires we cache the current loader in cl$
1741         if (target.classLiteralsNoInit()) {
1742             // clsym = "private static ClassLoader cl$"
1743             VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
1744                                             names.fromString("cl" + target.syntheticNameChar()),
1745                                             syms.classLoaderType,
1746                                             outerCacheClass);
1747             enterSynthetic(pos, clsym, outerCacheClass.members());
1748 
1749             // emit "private static ClassLoader cl$;"
1750             JCVariableDecl cldef = make.VarDef(clsym, null);
1751             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1752             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
1753 
1754             // newcache := "new cache$1[0]"
1755             JCNewArray newcache = make.
1756                 NewArray(make.Type(outerCacheClass.type),
1757                          List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
1758                          null);
1759             newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
1760                                           syms.arrayClass);
1761 
1762             // forNameSym := java.lang.Class.forName(
1763             //     String s,boolean init,ClassLoader loader)
1764             Symbol forNameSym = lookupMethod(make_pos, names.forName,
1765                                              types.erasure(syms.classType),
1766                                              List.of(syms.stringType,
1767                                                      syms.booleanType,
1768                                                      syms.classLoaderType));
1769             // clvalue := "(cl$ == null) ?
1770             // $newcache.getClass().getComponentType().getClassLoader() : cl$"
1771             JCExpression clvalue =
1772                 make.Conditional(
1773                     makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()),
1774                     make.Assign(
1775                         make.Ident(clsym),
1776                         makeCall(
1777                             makeCall(makeCall(newcache,
1778                                               names.getClass,
1779                                               List.<JCExpression>nil()),
1780                                      names.getComponentType,
1781                                      List.<JCExpression>nil()),
1782                             names.getClassLoader,
1783                             List.<JCExpression>nil())).setType(syms.classLoaderType),
1784                     make.Ident(clsym)).setType(syms.classLoaderType);
1785 
1786             // returnResult := "{ return Class.forName(param1, false, cl$); }"
1787             List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
1788                                               makeLit(syms.booleanType, 0),
1789                                               clvalue);
1790             returnResult = make.
1791                 Block(0, List.<JCStatement>of(make.
1792                               Call(make. // return
1793                                    App(make.
1794                                        Ident(forNameSym), args))));
1795         } else {
1796             // forNameSym := java.lang.Class.forName(String s)
1797             Symbol forNameSym = lookupMethod(make_pos,
1798                                              names.forName,
1799                                              types.erasure(syms.classType),
1800                                              List.of(syms.stringType));
1801             // returnResult := "{ return Class.forName(param1); }"
1802             returnResult = make.
1803                 Block(0, List.of(make.
1804                           Call(make. // return
1805                               App(make.
1806                                   QualIdent(forNameSym),
1807                                   List.<JCExpression>of(make.
1808                                                         Ident(md.params.
1809                                                               head.sym))))));
1810         }
1811 
1812         // catchParam := ClassNotFoundException e1
1813         VarSymbol catchParam =
1814             new VarSymbol(0, make.paramName(1),
1815                           syms.classNotFoundExceptionType,
1816                           classDollarSym);
1817 
1818         JCStatement rethrow;
1819         if (target.hasInitCause()) {
1820             // rethrow = "throw new NoClassDefFoundError().initCause(e);
1821             JCTree throwExpr =
1822                 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
1823                                       List.<JCExpression>nil()),
1824                          names.initCause,
1825                          List.<JCExpression>of(make.Ident(catchParam)));
1826             rethrow = make.Throw(throwExpr);
1827         } else {
1828             // getMessageSym := ClassNotFoundException.getMessage()
1829             Symbol getMessageSym = lookupMethod(make_pos,
1830                                                 names.getMessage,
1831                                                 syms.classNotFoundExceptionType,
1832                                                 List.<Type>nil());
1833             // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
1834             rethrow = make.
1835                 Throw(makeNewClass(syms.noClassDefFoundErrorType,
1836                           List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
1837                                                                      getMessageSym),
1838                                                          List.<JCExpression>nil()))));
1839         }
1840 
1841         // rethrowStmt := "( $rethrow )"
1842         JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
1843 
1844         // catchBlock := "catch ($catchParam) $rethrowStmt"
1845         JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
1846                                       rethrowStmt);
1847 
1848         // tryCatch := "try $returnResult $catchBlock"
1849         JCStatement tryCatch = make.Try(returnResult,
1850                                         List.of(catchBlock), null);
1851 
1852         return make.Block(0, List.of(tryCatch));
1853     }
1854     // where
1855         /** Create an attributed tree of the form left.name(). */
1856         private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1857             Assert.checkNonNull(left.type);
1858             Symbol funcsym = lookupMethod(make_pos, name, left.type,
1859                                           TreeInfo.types(args));
1860             return make.App(make.Select(left, funcsym), args);
1861         }
1862 
1863     /** The Name Of The variable to cache T.class values.
1864      *  @param sig      The signature of type T.
1865      */
1866     private Name cacheName(String sig) {
1867         StringBuffer buf = new StringBuffer();
1868         if (sig.startsWith("[")) {
1869             buf = buf.append("array");
1870             while (sig.startsWith("[")) {
1871                 buf = buf.append(target.syntheticNameChar());
1872                 sig = sig.substring(1);
1873             }
1874             if (sig.startsWith("L")) {
1875                 sig = sig.substring(0, sig.length() - 1);
1876             }
1877         } else {
1878             buf = buf.append("class" + target.syntheticNameChar());
1879         }
1880         buf = buf.append(sig.replace('.', target.syntheticNameChar()));
1881         return names.fromString(buf.toString());
1882     }
1883 
1884     /** The variable symbol that caches T.class values.
1885      *  If none exists yet, create a definition.
1886      *  @param sig      The signature of type T.
1887      *  @param pos      The position to report diagnostics, if any.
1888      */
1889     private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
1890         ClassSymbol outerCacheClass = outerCacheClass();
1891         Name cname = cacheName(sig);
1892         VarSymbol cacheSym =
1893             (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
1894         if (cacheSym == null) {
1895             cacheSym = new VarSymbol(
1896                 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
1897             enterSynthetic(pos, cacheSym, outerCacheClass.members());
1898 
1899             JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
1900             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1901             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
1902         }
1903         return cacheSym;
1904     }
1905 
1906     /** The tree simulating a T.class expression.
1907      *  @param clazz      The tree identifying type T.
1908      */
1909     private JCExpression classOf(JCTree clazz) {
1910         return classOfType(clazz.type, clazz.pos());
1911     }
1912 
1913     private JCExpression classOfType(Type type, DiagnosticPosition pos) {
1914         switch (type.tag) {
1915         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1916         case DOUBLE: case BOOLEAN: case VOID:
1917             // replace with <BoxedClass>.TYPE
1918             ClassSymbol c = types.boxedClass(type);
1919             Symbol typeSym =
1920                 rs.access(
1921                     rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
1922                     pos, c.type, names.TYPE, true);
1923             if (typeSym.kind == VAR)
1924                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
1925             return make.QualIdent(typeSym);
1926         case CLASS: case ARRAY:
1927             if (target.hasClassLiterals()) {
1928                 VarSymbol sym = new VarSymbol(
1929                         STATIC | PUBLIC | FINAL, names._class,
1930                         syms.classType, type.tsym);
1931                 return make_at(pos).Select(make.Type(type), sym);
1932             }
1933             // replace with <cache == null ? cache = class$(tsig) : cache>
1934             // where
1935             //  - <tsig>  is the type signature of T,
1936             //  - <cache> is the cache variable for tsig.
1937             String sig =
1938                 writer.xClassName(type).toString().replace('/', '.');
1939             Symbol cs = cacheSym(pos, sig);
1940             return make_at(pos).Conditional(
1941                 makeBinary(JCTree.EQ, make.Ident(cs), makeNull()),
1942                 make.Assign(
1943                     make.Ident(cs),
1944                     make.App(
1945                         make.Ident(classDollarSym(pos)),
1946                         List.<JCExpression>of(make.Literal(CLASS, sig)
1947                                               .setType(syms.stringType))))
1948                 .setType(types.erasure(syms.classType)),
1949                 make.Ident(cs)).setType(types.erasure(syms.classType));
1950         default:
1951             throw new AssertionError();
1952         }
1953     }
1954 
1955 /**************************************************************************
1956  * Code for enabling/disabling assertions.
1957  *************************************************************************/
1958 
1959     // This code is not particularly robust if the user has
1960     // previously declared a member named '$assertionsDisabled'.
1961     // The same faulty idiom also appears in the translation of
1962     // class literals above.  We should report an error if a
1963     // previous declaration is not synthetic.
1964 
1965     private JCExpression assertFlagTest(DiagnosticPosition pos) {
1966         // Outermost class may be either true class or an interface.
1967         ClassSymbol outermostClass = outermostClassDef.sym;
1968 
1969         // note that this is a class, as an interface can't contain a statement.
1970         ClassSymbol container = currentClass;
1971 
1972         VarSymbol assertDisabledSym =
1973             (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
1974                                        container.members());
1975         if (assertDisabledSym == null) {
1976             assertDisabledSym =
1977                 new VarSymbol(STATIC | FINAL | SYNTHETIC,
1978                               dollarAssertionsDisabled,
1979                               syms.booleanType,
1980                               container);
1981             enterSynthetic(pos, assertDisabledSym, container.members());
1982             Symbol desiredAssertionStatusSym = lookupMethod(pos,
1983                                                             names.desiredAssertionStatus,
1984                                                             types.erasure(syms.classType),
1985                                                             List.<Type>nil());
1986             JCClassDecl containerDef = classDef(container);
1987             make_at(containerDef.pos());
1988             JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select(
1989                     classOfType(types.erasure(outermostClass.type),
1990                                 containerDef.pos()),
1991                     desiredAssertionStatusSym)));
1992             JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
1993                                                    notStatus);
1994             containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
1995         }
1996         make_at(pos);
1997         return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym));
1998     }
1999 
2000 
2001 /**************************************************************************
2002  * Building blocks for let expressions
2003  *************************************************************************/
2004 
2005     interface TreeBuilder {
2006         JCTree build(JCTree arg);
2007     }
2008 
2009     /** Construct an expression using the builder, with the given rval
2010      *  expression as an argument to the builder.  However, the rval
2011      *  expression must be computed only once, even if used multiple
2012      *  times in the result of the builder.  We do that by
2013      *  constructing a "let" expression that saves the rvalue into a
2014      *  temporary variable and then uses the temporary variable in
2015      *  place of the expression built by the builder.  The complete
2016      *  resulting expression is of the form
2017      *  <pre>
2018      *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
2019      *     in (<b>BUILDER</b>(<b>TEMP</b>)))
2020      *  </pre>
2021      *  where <code><b>TEMP</b></code> is a newly declared variable
2022      *  in the let expression.
2023      */
2024     JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
2025         rval = TreeInfo.skipParens(rval);
2026         switch (rval.getTag()) {
2027         case JCTree.LITERAL:
2028             return builder.build(rval);
2029         case JCTree.IDENT:
2030             JCIdent id = (JCIdent) rval;
2031             if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
2032                 return builder.build(rval);
2033         }
2034         VarSymbol var =
2035             new VarSymbol(FINAL|SYNTHETIC,
2036                           names.fromString(
2037                                           target.syntheticNameChar()
2038                                           + "" + rval.hashCode()),
2039                                       type,
2040                                       currentMethodSym);
2041         rval = convert(rval,type);
2042         JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
2043         JCTree built = builder.build(make.Ident(var));
2044         JCTree res = make.LetExpr(def, built);
2045         res.type = built.type;
2046         return res;
2047     }
2048 
2049     // same as above, with the type of the temporary variable computed
2050     JCTree abstractRval(JCTree rval, TreeBuilder builder) {
2051         return abstractRval(rval, rval.type, builder);
2052     }
2053 
2054     // same as above, but for an expression that may be used as either
2055     // an rvalue or an lvalue.  This requires special handling for
2056     // Select expressions, where we place the left-hand-side of the
2057     // select in a temporary, and for Indexed expressions, where we
2058     // place both the indexed expression and the index value in temps.
2059     JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
2060         lval = TreeInfo.skipParens(lval);
2061         switch (lval.getTag()) {
2062         case JCTree.IDENT:
2063             return builder.build(lval);
2064         case JCTree.SELECT: {
2065             final JCFieldAccess s = (JCFieldAccess)lval;
2066             JCTree selected = TreeInfo.skipParens(s.selected);
2067             Symbol lid = TreeInfo.symbol(s.selected);
2068             if (lid != null && lid.kind == TYP) return builder.build(lval);
2069             return abstractRval(s.selected, new TreeBuilder() {
2070                     public JCTree build(final JCTree selected) {
2071                         return builder.build(make.Select((JCExpression)selected, s.sym));
2072                     }
2073                 });
2074         }
2075         case JCTree.INDEXED: {
2076             final JCArrayAccess i = (JCArrayAccess)lval;
2077             return abstractRval(i.indexed, new TreeBuilder() {
2078                     public JCTree build(final JCTree indexed) {
2079                         return abstractRval(i.index, syms.intType, new TreeBuilder() {
2080                                 public JCTree build(final JCTree index) {
2081                                     JCTree newLval = make.Indexed((JCExpression)indexed,
2082                                                                 (JCExpression)index);
2083                                     newLval.setType(i.type);
2084                                     return builder.build(newLval);
2085                                 }
2086                             });
2087                     }
2088                 });
2089         }
2090         case JCTree.TYPECAST: {
2091             return abstractLval(((JCTypeCast)lval).expr, builder);
2092         }
2093         }
2094         throw new AssertionError(lval);
2095     }
2096 
2097     // evaluate and discard the first expression, then evaluate the second.
2098     JCTree makeComma(final JCTree expr1, final JCTree expr2) {
2099         return abstractRval(expr1, new TreeBuilder() {
2100                 public JCTree build(final JCTree discarded) {
2101                     return expr2;
2102                 }
2103             });
2104     }
2105 
2106 /**************************************************************************
2107  * Translation methods
2108  *************************************************************************/
2109 
2110     /** Visitor argument: enclosing operator node.
2111      */
2112     private JCExpression enclOp;
2113 
2114     /** Visitor method: Translate a single node.
2115      *  Attach the source position from the old tree to its replacement tree.
2116      */
2117     public <T extends JCTree> T translate(T tree) {
2118         if (tree == null) {
2119             return null;
2120         } else {
2121             make_at(tree.pos());
2122             T result = super.translate(tree);
2123             if (endPositions != null && result != tree) {
2124                 Integer endPos = endPositions.remove(tree);
2125                 if (endPos != null) endPositions.put(result, endPos);
2126             }
2127             return result;
2128         }
2129     }
2130 
2131     /** Visitor method: Translate a single node, boxing or unboxing if needed.
2132      */
2133     public <T extends JCTree> T translate(T tree, Type type) {
2134         return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2135     }
2136 
2137     /** Visitor method: Translate tree.
2138      */
2139     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2140         JCExpression prevEnclOp = this.enclOp;
2141         this.enclOp = enclOp;
2142         T res = translate(tree);
2143         this.enclOp = prevEnclOp;
2144         return res;
2145     }
2146 
2147     /** Visitor method: Translate list of trees.
2148      */
2149     public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2150         JCExpression prevEnclOp = this.enclOp;
2151         this.enclOp = enclOp;
2152         List<T> res = translate(trees);
2153         this.enclOp = prevEnclOp;
2154         return res;
2155     }
2156 
2157     /** Visitor method: Translate list of trees.
2158      */
2159     public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
2160         if (trees == null) return null;
2161         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2162             l.head = translate(l.head, type);
2163         return trees;
2164     }
2165 
2166     public void visitTopLevel(JCCompilationUnit tree) {
2167         if (needPackageInfoClass(tree)) {
2168             Name name = names.package_info;
2169             long flags = Flags.ABSTRACT | Flags.INTERFACE;
2170             if (target.isPackageInfoSynthetic())
2171                 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2172                 flags = flags | Flags.SYNTHETIC;
2173             JCClassDecl packageAnnotationsClass
2174                 = make.ClassDef(make.Modifiers(flags,
2175                                                tree.packageAnnotations),
2176                                 name, List.<JCTypeParameter>nil(),
2177                                 null, List.<JCExpression>nil(), List.<JCTree>nil());
2178             ClassSymbol c = tree.packge.package_info;
2179             c.flags_field |= flags;
2180             c.attributes_field = tree.packge.attributes_field;
2181             ClassType ctype = (ClassType) c.type;
2182             ctype.supertype_field = syms.objectType;
2183             ctype.interfaces_field = List.nil();
2184             packageAnnotationsClass.sym = c;
2185 
2186             translated.append(packageAnnotationsClass);
2187         }
2188     }
2189     // where
2190     private boolean needPackageInfoClass(JCCompilationUnit tree) {
2191         switch (pkginfoOpt) {
2192             case ALWAYS:
2193                 return true;
2194             case LEGACY:
2195                 return tree.packageAnnotations.nonEmpty();
2196             case NONEMPTY:
2197                 for (Attribute.Compound a: tree.packge.attributes_field) {
2198                     Attribute.RetentionPolicy p = types.getRetention(a);
2199                     if (p != Attribute.RetentionPolicy.SOURCE)
2200                         return true;
2201                 }
2202                 return false;
2203         }
2204         throw new AssertionError();
2205     }
2206 
2207     public void visitClassDef(JCClassDecl tree) {
2208         ClassSymbol currentClassPrev = currentClass;
2209         MethodSymbol currentMethodSymPrev = currentMethodSym;
2210         currentClass = tree.sym;
2211         currentMethodSym = null;
2212         classdefs.put(currentClass, tree);
2213 
2214         proxies = proxies.dup(currentClass);
2215         List<VarSymbol> prevOuterThisStack = outerThisStack;
2216 
2217         // If this is an enum definition
2218         if ((tree.mods.flags & ENUM) != 0 &&
2219             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2220             visitEnumDef(tree);
2221 
2222         // If this is a nested class, define a this$n field for
2223         // it and add to proxies.
2224         JCVariableDecl otdef = null;
2225         if (currentClass.hasOuterInstance())
2226             otdef = outerThisDef(tree.pos, currentClass);
2227 
2228         // If this is a local class, define proxies for all its free variables.
2229         List<JCVariableDecl> fvdefs = freevarDefs(
2230             tree.pos, freevars(currentClass), currentClass);
2231 
2232         // Recursively translate superclass, interfaces.
2233         tree.extending = translate(tree.extending);
2234         tree.implementing = translate(tree.implementing);
2235 
2236         // Recursively translate members, taking into account that new members
2237         // might be created during the translation and prepended to the member
2238         // list `tree.defs'.
2239         List<JCTree> seen = List.nil();
2240         while (tree.defs != seen) {
2241             List<JCTree> unseen = tree.defs;
2242             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2243                 JCTree outermostMemberDefPrev = outermostMemberDef;
2244                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2245                 l.head = translate(l.head);
2246                 outermostMemberDef = outermostMemberDefPrev;
2247             }
2248             seen = unseen;
2249         }
2250 
2251         // Convert a protected modifier to public, mask static modifier.
2252         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2253         tree.mods.flags &= ClassFlags;
2254 
2255         // Convert name to flat representation, replacing '.' by '$'.
2256         tree.name = Convert.shortName(currentClass.flatName());
2257 
2258         // Add this$n and free variables proxy definitions to class.
2259         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2260             tree.defs = tree.defs.prepend(l.head);
2261             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2262         }
2263         if (currentClass.hasOuterInstance()) {
2264             tree.defs = tree.defs.prepend(otdef);
2265             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2266         }
2267 
2268         proxies = proxies.leave();
2269         outerThisStack = prevOuterThisStack;
2270 
2271         // Append translated tree to `translated' queue.
2272         translated.append(tree);
2273 
2274         currentClass = currentClassPrev;
2275         currentMethodSym = currentMethodSymPrev;
2276 
2277         // Return empty block {} as a placeholder for an inner class.
2278         result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
2279     }
2280 
2281     /** Translate an enum class. */
2282     private void visitEnumDef(JCClassDecl tree) {
2283         make_at(tree.pos());
2284 
2285         // add the supertype, if needed
2286         if (tree.extending == null)
2287             tree.extending = make.Type(types.supertype(tree.type));
2288 
2289         // classOfType adds a cache field to tree.defs unless
2290         // target.hasClassLiterals().
2291         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2292             setType(types.erasure(syms.classType));
2293 
2294         // process each enumeration constant, adding implicit constructor parameters
2295         int nextOrdinal = 0;
2296         ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
2297         ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
2298         ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
2299         for (List<JCTree> defs = tree.defs;
2300              defs.nonEmpty();
2301              defs=defs.tail) {
2302             if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2303                 JCVariableDecl var = (JCVariableDecl)defs.head;
2304                 visitEnumConstantDef(var, nextOrdinal++);
2305                 values.append(make.QualIdent(var.sym));
2306                 enumDefs.append(var);
2307             } else {
2308                 otherDefs.append(defs.head);
2309             }
2310         }
2311 
2312         // private static final T[] #VALUES = { a, b, c };
2313         Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2314         while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
2315             valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2316         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2317         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2318                                             valuesName,
2319                                             arrayType,
2320                                             tree.type.tsym);
2321         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2322                                           List.<JCExpression>nil(),
2323                                           values.toList());
2324         newArray.type = arrayType;
2325         enumDefs.append(make.VarDef(valuesVar, newArray));
2326         tree.sym.members().enter(valuesVar);
2327 
2328         Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2329                                         tree.type, List.<Type>nil());
2330         List<JCStatement> valuesBody;
2331         if (useClone()) {
2332             // return (T[]) $VALUES.clone();
2333             JCTypeCast valuesResult =
2334                 make.TypeCast(valuesSym.type.getReturnType(),
2335                               make.App(make.Select(make.Ident(valuesVar),
2336                                                    syms.arrayCloneMethod)));
2337             valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2338         } else {
2339             // template: T[] $result = new T[$values.length];
2340             Name resultName = names.fromString(target.syntheticNameChar() + "result");
2341             while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
2342                 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2343             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2344                                                 resultName,
2345                                                 arrayType,
2346                                                 valuesSym);
2347             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2348                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2349                                   null);
2350             resultArray.type = arrayType;
2351             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2352 
2353             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2354             if (systemArraycopyMethod == null) {
2355                 systemArraycopyMethod =
2356                     new MethodSymbol(PUBLIC | STATIC,
2357                                      names.fromString("arraycopy"),
2358                                      new MethodType(List.<Type>of(syms.objectType,
2359                                                             syms.intType,
2360                                                             syms.objectType,
2361                                                             syms.intType,
2362                                                             syms.intType),
2363                                                     syms.voidType,
2364                                                     List.<Type>nil(),
2365                                                     syms.methodClass),
2366                                      syms.systemType.tsym);
2367             }
2368             JCStatement copy =
2369                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2370                                                systemArraycopyMethod),
2371                           List.of(make.Ident(valuesVar), make.Literal(0),
2372                                   make.Ident(resultVar), make.Literal(0),
2373                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
2374 
2375             // template: return $result;
2376             JCStatement ret = make.Return(make.Ident(resultVar));
2377             valuesBody = List.<JCStatement>of(decl, copy, ret);
2378         }
2379 
2380         JCMethodDecl valuesDef =
2381              make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2382 
2383         enumDefs.append(valuesDef);
2384 
2385         if (debugLower)
2386             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2387 
2388         /** The template for the following code is:
2389          *
2390          *     public static E valueOf(String name) {
2391          *         return (E)Enum.valueOf(E.class, name);
2392          *     }
2393          *
2394          *  where E is tree.sym
2395          */
2396         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2397                          names.valueOf,
2398                          tree.sym.type,
2399                          List.of(syms.stringType));
2400         Assert.check((valueOfSym.flags() & STATIC) != 0);
2401         VarSymbol nameArgSym = valueOfSym.params.head;
2402         JCIdent nameVal = make.Ident(nameArgSym);
2403         JCStatement enum_ValueOf =
2404             make.Return(make.TypeCast(tree.sym.type,
2405                                       makeCall(make.Ident(syms.enumSym),
2406                                                names.valueOf,
2407                                                List.of(e_class, nameVal))));
2408         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2409                                            make.Block(0, List.of(enum_ValueOf)));
2410         nameVal.sym = valueOf.params.head.sym;
2411         if (debugLower)
2412             System.err.println(tree.sym + ".valueOf = " + valueOf);
2413         enumDefs.append(valueOf);
2414 
2415         enumDefs.appendList(otherDefs.toList());
2416         tree.defs = enumDefs.toList();
2417 
2418         // Add the necessary members for the EnumCompatibleMode
2419         if (target.compilerBootstrap(tree.sym)) {
2420             addEnumCompatibleMembers(tree);
2421         }
2422     }
2423         // where
2424         private MethodSymbol systemArraycopyMethod;
2425         private boolean useClone() {
2426             try {
2427                 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
2428                 return (e.sym != null);
2429             }
2430             catch (CompletionFailure e) {
2431                 return false;
2432             }
2433         }
2434 
2435     /** Translate an enumeration constant and its initializer. */
2436     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2437         JCNewClass varDef = (JCNewClass)var.init;
2438         varDef.args = varDef.args.
2439             prepend(makeLit(syms.intType, ordinal)).
2440             prepend(makeLit(syms.stringType, var.name.toString()));
2441     }
2442 
2443     public void visitMethodDef(JCMethodDecl tree) {
2444         if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2445             // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2446             // argument list for each constructor of an enum.
2447             JCVariableDecl nameParam = make_at(tree.pos()).
2448                 Param(names.fromString(target.syntheticNameChar() +
2449                                        "enum" + target.syntheticNameChar() + "name"),
2450                       syms.stringType, tree.sym);
2451             nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2452 
2453             JCVariableDecl ordParam = make.
2454                 Param(names.fromString(target.syntheticNameChar() +
2455                                        "enum" + target.syntheticNameChar() +
2456                                        "ordinal"),
2457                       syms.intType, tree.sym);
2458             ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2459 
2460             tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2461 
2462             MethodSymbol m = tree.sym;
2463             Type olderasure = m.erasure(types);
2464             m.erasure_field = new MethodType(
2465                 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2466                 olderasure.getReturnType(),
2467                 olderasure.getThrownTypes(),
2468                 syms.methodClass);
2469 
2470             if (target.compilerBootstrap(m.owner)) {
2471                 // Initialize synthetic name field
2472                 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
2473                                                     tree.sym.owner.members());
2474                 JCIdent nameIdent = make.Ident(nameParam.sym);
2475                 JCIdent id1 = make.Ident(nameVarSym);
2476                 JCAssign newAssign = make.Assign(id1, nameIdent);
2477                 newAssign.type = id1.type;
2478                 JCExpressionStatement nameAssign = make.Exec(newAssign);
2479                 nameAssign.type = id1.type;
2480                 tree.body.stats = tree.body.stats.prepend(nameAssign);
2481 
2482                 // Initialize synthetic ordinal field
2483                 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
2484                                                        tree.sym.owner.members());
2485                 JCIdent ordIdent = make.Ident(ordParam.sym);
2486                 id1 = make.Ident(ordinalVarSym);
2487                 newAssign = make.Assign(id1, ordIdent);
2488                 newAssign.type = id1.type;
2489                 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
2490                 ordinalAssign.type = id1.type;
2491                 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
2492             }
2493         }
2494 
2495         JCMethodDecl prevMethodDef = currentMethodDef;
2496         MethodSymbol prevMethodSym = currentMethodSym;
2497         try {
2498             currentMethodDef = tree;
2499             currentMethodSym = tree.sym;
2500             visitMethodDefInternal(tree);
2501         } finally {
2502             currentMethodDef = prevMethodDef;
2503             currentMethodSym = prevMethodSym;
2504         }
2505     }
2506     //where
2507     private void visitMethodDefInternal(JCMethodDecl tree) {
2508         if (tree.name == names.init &&
2509             (currentClass.isInner() ||
2510              (currentClass.owner.kind & (VAR | MTH)) != 0)) {
2511             // We are seeing a constructor of an inner class.
2512             MethodSymbol m = tree.sym;
2513 
2514             // Push a new proxy scope for constructor parameters.
2515             // and create definitions for any this$n and proxy parameters.
2516             proxies = proxies.dup(m);
2517             List<VarSymbol> prevOuterThisStack = outerThisStack;
2518             List<VarSymbol> fvs = freevars(currentClass);
2519             JCVariableDecl otdef = null;
2520             if (currentClass.hasOuterInstance())
2521                 otdef = outerThisDef(tree.pos, m);
2522             List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
2523 
2524             // Recursively translate result type, parameters and thrown list.
2525             tree.restype = translate(tree.restype);
2526             tree.params = translateVarDefs(tree.params);
2527             tree.thrown = translate(tree.thrown);
2528 
2529             // when compiling stubs, don't process body
2530             if (tree.body == null) {
2531                 result = tree;
2532                 return;
2533             }
2534 
2535             // Add this$n (if needed) in front of and free variables behind
2536             // constructor parameter list.
2537             tree.params = tree.params.appendList(fvdefs);
2538             if (currentClass.hasOuterInstance())
2539                 tree.params = tree.params.prepend(otdef);
2540 
2541             // If this is an initial constructor, i.e., it does not start with
2542             // this(...), insert initializers for this$n and proxies
2543             // before (pre-1.4, after) the call to superclass constructor.
2544             JCStatement selfCall = translate(tree.body.stats.head);
2545 
2546             List<JCStatement> added = List.nil();
2547             if (fvs.nonEmpty()) {
2548                 List<Type> addedargtypes = List.nil();
2549                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2550                     if (TreeInfo.isInitialConstructor(tree))
2551                         added = added.prepend(
2552                             initField(tree.body.pos, proxyName(l.head.name)));
2553                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2554                 }
2555                 Type olderasure = m.erasure(types);
2556                 m.erasure_field = new MethodType(
2557                     olderasure.getParameterTypes().appendList(addedargtypes),
2558                     olderasure.getReturnType(),
2559                     olderasure.getThrownTypes(),
2560                     syms.methodClass);
2561             }
2562             if (currentClass.hasOuterInstance() &&
2563                 TreeInfo.isInitialConstructor(tree))
2564             {
2565                 added = added.prepend(initOuterThis(tree.body.pos));
2566             }
2567 
2568             // pop local variables from proxy stack
2569             proxies = proxies.leave();
2570 
2571             // recursively translate following local statements and
2572             // combine with this- or super-call
2573             List<JCStatement> stats = translate(tree.body.stats.tail);
2574             if (target.initializeFieldsBeforeSuper())
2575                 tree.body.stats = stats.prepend(selfCall).prependList(added);
2576             else
2577                 tree.body.stats = stats.prependList(added).prepend(selfCall);
2578 
2579             outerThisStack = prevOuterThisStack;
2580         } else {
2581             super.visitMethodDef(tree);
2582         }
2583         result = tree;
2584     }
2585 
2586     public void visitTypeCast(JCTypeCast tree) {
2587         tree.clazz = translate(tree.clazz);
2588         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2589             tree.expr = translate(tree.expr, tree.type);
2590         else
2591             tree.expr = translate(tree.expr);
2592         result = tree;
2593     }
2594 
2595     public void visitNewClass(JCNewClass tree) {
2596         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2597 
2598         // Box arguments, if necessary
2599         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2600         List<Type> argTypes = tree.constructor.type.getParameterTypes();
2601         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2602         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2603         tree.varargsElement = null;
2604 
2605         // If created class is local, add free variables after
2606         // explicit constructor arguments.
2607         if ((c.owner.kind & (VAR | MTH)) != 0) {
2608             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2609         }
2610 
2611         // If an access constructor is used, append null as a last argument.
2612         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2613         if (constructor != tree.constructor) {
2614             tree.args = tree.args.append(makeNull());
2615             tree.constructor = constructor;
2616         }
2617 
2618         // If created class has an outer instance, and new is qualified, pass
2619         // qualifier as first argument. If new is not qualified, pass the
2620         // correct outer instance as first argument.
2621         if (c.hasOuterInstance()) {
2622             JCExpression thisArg;
2623             if (tree.encl != null) {
2624                 thisArg = attr.makeNullCheck(translate(tree.encl));
2625                 thisArg.type = tree.encl.type;
2626             } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2627                 // local class
2628                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2629             } else {
2630                 // nested class
2631                 thisArg = makeOwnerThis(tree.pos(), c, false);
2632             }
2633             tree.args = tree.args.prepend(thisArg);
2634         }
2635         tree.encl = null;
2636 
2637         // If we have an anonymous class, create its flat version, rather
2638         // than the class or interface following new.
2639         if (tree.def != null) {
2640             translate(tree.def);
2641             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2642             tree.def = null;
2643         } else {
2644             tree.clazz = access(c, tree.clazz, enclOp, false);
2645         }
2646         result = tree;
2647     }
2648 
2649     // Simplify conditionals with known constant controlling expressions.
2650     // This allows us to avoid generating supporting declarations for
2651     // the dead code, which will not be eliminated during code generation.
2652     // Note that Flow.isFalse and Flow.isTrue only return true
2653     // for constant expressions in the sense of JLS 15.27, which
2654     // are guaranteed to have no side-effects.  More aggressive
2655     // constant propagation would require that we take care to
2656     // preserve possible side-effects in the condition expression.
2657 
2658     /** Visitor method for conditional expressions.
2659      */
2660     public void visitConditional(JCConditional tree) {
2661         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2662         if (cond.type.isTrue()) {
2663             result = convert(translate(tree.truepart, tree.type), tree.type);
2664         } else if (cond.type.isFalse()) {
2665             result = convert(translate(tree.falsepart, tree.type), tree.type);
2666         } else {
2667             // Condition is not a compile-time constant.
2668             tree.truepart = translate(tree.truepart, tree.type);
2669             tree.falsepart = translate(tree.falsepart, tree.type);
2670             result = tree;
2671         }
2672     }
2673 //where
2674         private JCTree convert(JCTree tree, Type pt) {
2675             if (tree.type == pt || tree.type.tag == TypeTags.BOT)
2676                 return tree;
2677             JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2678             result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2679                                                            : pt;
2680             return result;
2681         }
2682 
2683     /** Visitor method for if statements.
2684      */
2685     public void visitIf(JCIf tree) {
2686         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2687         if (cond.type.isTrue()) {
2688             result = translate(tree.thenpart);
2689         } else if (cond.type.isFalse()) {
2690             if (tree.elsepart != null) {
2691                 result = translate(tree.elsepart);
2692             } else {
2693                 result = make.Skip();
2694             }
2695         } else {
2696             // Condition is not a compile-time constant.
2697             tree.thenpart = translate(tree.thenpart);
2698             tree.elsepart = translate(tree.elsepart);
2699             result = tree;
2700         }
2701     }
2702 
2703     /** Visitor method for assert statements. Translate them away.
2704      */
2705     public void visitAssert(JCAssert tree) {
2706         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2707         tree.cond = translate(tree.cond, syms.booleanType);
2708         if (!tree.cond.type.isTrue()) {
2709             JCExpression cond = assertFlagTest(tree.pos());
2710             List<JCExpression> exnArgs = (tree.detail == null) ?
2711                 List.<JCExpression>nil() : List.of(translate(tree.detail));
2712             if (!tree.cond.type.isFalse()) {
2713                 cond = makeBinary
2714                     (JCTree.AND,
2715                      cond,
2716                      makeUnary(JCTree.NOT, tree.cond));
2717             }
2718             result =
2719                 make.If(cond,
2720                         make_at(detailPos).
2721                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2722                         null);
2723         } else {
2724             result = make.Skip();
2725         }
2726     }
2727 
2728     public void visitApply(JCMethodInvocation tree) {
2729         Symbol meth = TreeInfo.symbol(tree.meth);
2730         List<Type> argtypes = meth.type.getParameterTypes();
2731         if (allowEnums &&
2732             meth.name==names.init &&
2733             meth.owner == syms.enumSym)
2734             argtypes = argtypes.tail.tail;
2735         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2736         tree.varargsElement = null;
2737         Name methName = TreeInfo.name(tree.meth);
2738         if (meth.name==names.init) {
2739             // We are seeing a this(...) or super(...) constructor call.
2740             // If an access constructor is used, append null as a last argument.
2741             Symbol constructor = accessConstructor(tree.pos(), meth);
2742             if (constructor != meth) {
2743                 tree.args = tree.args.append(makeNull());
2744                 TreeInfo.setSymbol(tree.meth, constructor);
2745             }
2746 
2747             // If we are calling a constructor of a local class, add
2748             // free variables after explicit constructor arguments.
2749             ClassSymbol c = (ClassSymbol)constructor.owner;
2750             if ((c.owner.kind & (VAR | MTH)) != 0) {
2751                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2752             }
2753 
2754             // If we are calling a constructor of an enum class, pass
2755             // along the name and ordinal arguments
2756             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2757                 List<JCVariableDecl> params = currentMethodDef.params;
2758                 if (currentMethodSym.owner.hasOuterInstance())
2759                     params = params.tail; // drop this$n
2760                 tree.args = tree.args
2761                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2762                     .prepend(make.Ident(params.head.sym)); // name
2763             }
2764 
2765             // If we are calling a constructor of a class with an outer
2766             // instance, and the call
2767             // is qualified, pass qualifier as first argument in front of
2768             // the explicit constructor arguments. If the call
2769             // is not qualified, pass the correct outer instance as
2770             // first argument.
2771             if (c.hasOuterInstance()) {
2772                 JCExpression thisArg;
2773                 if (tree.meth.getTag() == JCTree.SELECT) {
2774                     thisArg = attr.
2775                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2776                     tree.meth = make.Ident(constructor);
2777                     ((JCIdent) tree.meth).name = methName;
2778                 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2779                     // local class or this() call
2780                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2781                 } else {
2782                     // super() call of nested class
2783                     thisArg = makeOwnerThis(tree.meth.pos(), c, false);
2784                 }
2785                 tree.args = tree.args.prepend(thisArg);
2786             }
2787         } else {
2788             // We are seeing a normal method invocation; translate this as usual.
2789             tree.meth = translate(tree.meth);
2790 
2791             // If the translated method itself is an Apply tree, we are
2792             // seeing an access method invocation. In this case, append
2793             // the method arguments to the arguments of the access method.
2794             if (tree.meth.getTag() == JCTree.APPLY) {
2795                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
2796                 app.args = tree.args.prependList(app.args);
2797                 result = app;
2798                 return;
2799             }
2800         }
2801         result = tree;
2802     }
2803 
2804     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
2805         List<JCExpression> args = _args;
2806         if (parameters.isEmpty()) return args;
2807         boolean anyChanges = false;
2808         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
2809         while (parameters.tail.nonEmpty()) {
2810             JCExpression arg = translate(args.head, parameters.head);
2811             anyChanges |= (arg != args.head);
2812             result.append(arg);
2813             args = args.tail;
2814             parameters = parameters.tail;
2815         }
2816         Type parameter = parameters.head;
2817         if (varargsElement != null) {
2818             anyChanges = true;
2819             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
2820             while (args.nonEmpty()) {
2821                 JCExpression arg = translate(args.head, varargsElement);
2822                 elems.append(arg);
2823                 args = args.tail;
2824             }
2825             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
2826                                                List.<JCExpression>nil(),
2827                                                elems.toList());
2828             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
2829             result.append(boxedArgs);
2830         } else {
2831             if (args.length() != 1) throw new AssertionError(args);
2832             JCExpression arg = translate(args.head, parameter);
2833             anyChanges |= (arg != args.head);
2834             result.append(arg);
2835             if (!anyChanges) return _args;
2836         }
2837         return result.toList();
2838     }
2839 
2840     /** Expand a boxing or unboxing conversion if needed. */
2841     @SuppressWarnings("unchecked") // XXX unchecked
2842     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
2843         boolean havePrimitive = tree.type.isPrimitive();
2844         if (havePrimitive == type.isPrimitive())
2845             return tree;
2846         if (havePrimitive) {
2847             Type unboxedTarget = types.unboxedType(type);
2848             if (unboxedTarget.tag != NONE) {
2849                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
2850                     tree.type = unboxedTarget.constType(tree.type.constValue());
2851                 return (T)boxPrimitive((JCExpression)tree, type);
2852             } else {
2853                 tree = (T)boxPrimitive((JCExpression)tree);
2854             }
2855         } else {
2856             tree = (T)unbox((JCExpression)tree, type);
2857         }
2858         return tree;
2859     }
2860 
2861     /** Box up a single primitive expression. */
2862     JCExpression boxPrimitive(JCExpression tree) {
2863         return boxPrimitive(tree, types.boxedClass(tree.type).type);
2864     }
2865 
2866     /** Box up a single primitive expression. */
2867     JCExpression boxPrimitive(JCExpression tree, Type box) {
2868         make_at(tree.pos());
2869         if (target.boxWithConstructors()) {
2870             Symbol ctor = lookupConstructor(tree.pos(),
2871                                             box,
2872                                             List.<Type>nil()
2873                                             .prepend(tree.type));
2874             return make.Create(ctor, List.of(tree));
2875         } else {
2876             Symbol valueOfSym = lookupMethod(tree.pos(),
2877                                              names.valueOf,
2878                                              box,
2879                                              List.<Type>nil()
2880                                              .prepend(tree.type));
2881             return make.App(make.QualIdent(valueOfSym), List.of(tree));
2882         }
2883     }
2884 
2885     /** Unbox an object to a primitive value. */
2886     JCExpression unbox(JCExpression tree, Type primitive) {
2887         Type unboxedType = types.unboxedType(tree.type);
2888         if (unboxedType.tag == NONE) {
2889             unboxedType = primitive;
2890             if (!unboxedType.isPrimitive())
2891                 throw new AssertionError(unboxedType);
2892             make_at(tree.pos());
2893             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
2894         } else {
2895             // There must be a conversion from unboxedType to primitive.
2896             if (!types.isSubtype(unboxedType, primitive))
2897                 throw new AssertionError(tree);
2898         }
2899         make_at(tree.pos());
2900         Symbol valueSym = lookupMethod(tree.pos(),
2901                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
2902                                        tree.type,
2903                                        List.<Type>nil());
2904         return make.App(make.Select(tree, valueSym));
2905     }
2906 
2907     /** Visitor method for parenthesized expressions.
2908      *  If the subexpression has changed, omit the parens.
2909      */
2910     public void visitParens(JCParens tree) {
2911         JCTree expr = translate(tree.expr);
2912         result = ((expr == tree.expr) ? tree : expr);
2913     }
2914 
2915     public void visitIndexed(JCArrayAccess tree) {
2916         tree.indexed = translate(tree.indexed);
2917         tree.index = translate(tree.index, syms.intType);
2918         result = tree;
2919     }
2920 
2921     public void visitAssign(JCAssign tree) {
2922         tree.lhs = translate(tree.lhs, tree);
2923         tree.rhs = translate(tree.rhs, tree.lhs.type);
2924 
2925         // If translated left hand side is an Apply, we are
2926         // seeing an access method invocation. In this case, append
2927         // right hand side as last argument of the access method.
2928         if (tree.lhs.getTag() == JCTree.APPLY) {
2929             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2930             app.args = List.of(tree.rhs).prependList(app.args);
2931             result = app;
2932         } else {
2933             result = tree;
2934         }
2935     }
2936 
2937     public void visitAssignop(final JCAssignOp tree) {
2938         if (!tree.lhs.type.isPrimitive() &&
2939             tree.operator.type.getReturnType().isPrimitive()) {
2940             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
2941             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
2942             // (but without recomputing x)
2943             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
2944                     public JCTree build(final JCTree lhs) {
2945                         int newTag = tree.getTag() - JCTree.ASGOffset;
2946                         // Erasure (TransTypes) can change the type of
2947                         // tree.lhs.  However, we can still get the
2948                         // unerased type of tree.lhs as it is stored
2949                         // in tree.type in Attr.
2950                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
2951                                                                       newTag,
2952                                                                       attrEnv,
2953                                                                       tree.type,
2954                                                                       tree.rhs.type);
2955                         JCExpression expr = (JCExpression)lhs;
2956                         if (expr.type != tree.type)
2957                             expr = make.TypeCast(tree.type, expr);
2958                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
2959                         opResult.operator = newOperator;
2960                         opResult.type = newOperator.type.getReturnType();
2961                         JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
2962                                                           opResult);
2963                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
2964                     }
2965                 });
2966             result = translate(newTree);
2967             return;
2968         }
2969         tree.lhs = translate(tree.lhs, tree);
2970         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
2971 
2972         // If translated left hand side is an Apply, we are
2973         // seeing an access method invocation. In this case, append
2974         // right hand side as last argument of the access method.
2975         if (tree.lhs.getTag() == JCTree.APPLY) {
2976             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2977             // if operation is a += on strings,
2978             // make sure to convert argument to string
2979             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
2980               ? makeString(tree.rhs)
2981               : tree.rhs;
2982             app.args = List.of(rhs).prependList(app.args);
2983             result = app;
2984         } else {
2985             result = tree;
2986         }
2987     }
2988 
2989     /** Lower a tree of the form e++ or e-- where e is an object type */
2990     JCTree lowerBoxedPostop(final JCUnary tree) {
2991         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
2992         // or
2993         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
2994         // where OP is += or -=
2995         final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
2996         return abstractLval(tree.arg, new TreeBuilder() {
2997                 public JCTree build(final JCTree tmp1) {
2998                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
2999                             public JCTree build(final JCTree tmp2) {
3000                                 int opcode = (tree.getTag() == JCTree.POSTINC)
3001                                     ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
3002                                 JCTree lhs = cast
3003                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
3004                                     : tmp1;
3005                                 JCTree update = makeAssignop(opcode,
3006                                                              lhs,
3007                                                              make.Literal(1));
3008                                 return makeComma(update, tmp2);
3009                             }
3010                         });
3011                 }
3012             });
3013     }
3014 
3015     public void visitUnary(JCUnary tree) {
3016         boolean isUpdateOperator =
3017             JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC;
3018         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3019             switch(tree.getTag()) {
3020             case JCTree.PREINC:            // ++ e
3021                     // translate to e += 1
3022             case JCTree.PREDEC:            // -- e
3023                     // translate to e -= 1
3024                 {
3025                     int opcode = (tree.getTag() == JCTree.PREINC)
3026                         ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
3027                     JCAssignOp newTree = makeAssignop(opcode,
3028                                                     tree.arg,
3029                                                     make.Literal(1));
3030                     result = translate(newTree, tree.type);
3031                     return;
3032                 }
3033             case JCTree.POSTINC:           // e ++
3034             case JCTree.POSTDEC:           // e --
3035                 {
3036                     result = translate(lowerBoxedPostop(tree), tree.type);
3037                     return;
3038                 }
3039             }
3040             throw new AssertionError(tree);
3041         }
3042 
3043         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3044 
3045         if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) {
3046             tree.type = cfolder.fold1(bool_not, tree.arg.type);
3047         }
3048 
3049         // If translated left hand side is an Apply, we are
3050         // seeing an access method invocation. In this case, return
3051         // that access method invocation as result.
3052         if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) {
3053             result = tree.arg;
3054         } else {
3055             result = tree;
3056         }
3057     }
3058 
3059     public void visitBinary(JCBinary tree) {
3060         List<Type> formals = tree.operator.type.getParameterTypes();
3061         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3062         switch (tree.getTag()) {
3063         case JCTree.OR:
3064             if (lhs.type.isTrue()) {
3065                 result = lhs;
3066                 return;
3067             }
3068             if (lhs.type.isFalse()) {
3069                 result = translate(tree.rhs, formals.tail.head);
3070                 return;
3071             }
3072             break;
3073         case JCTree.AND:
3074             if (lhs.type.isFalse()) {
3075                 result = lhs;
3076                 return;
3077             }
3078             if (lhs.type.isTrue()) {
3079                 result = translate(tree.rhs, formals.tail.head);
3080                 return;
3081             }
3082             break;
3083         }
3084         tree.rhs = translate(tree.rhs, formals.tail.head);
3085         result = tree;
3086     }
3087 
3088     public void visitIdent(JCIdent tree) {
3089         result = access(tree.sym, tree, enclOp, false);
3090     }
3091 
3092     /** Translate away the foreach loop.  */
3093     public void visitForeachLoop(JCEnhancedForLoop tree) {
3094         if (types.elemtype(tree.expr.type) == null)
3095             visitIterableForeachLoop(tree);
3096         else
3097             visitArrayForeachLoop(tree);
3098     }
3099         // where
3100         /**
3101          * A statement of the form
3102          *
3103          * <pre>
3104          *     for ( T v : arrayexpr ) stmt;
3105          * </pre>
3106          *
3107          * (where arrayexpr is of an array type) gets translated to
3108          *
3109          * <pre>
3110          *     for ( { arraytype #arr = arrayexpr;
3111          *             int #len = array.length;
3112          *             int #i = 0; };
3113          *           #i < #len; i$++ ) {
3114          *         T v = arr$[#i];
3115          *         stmt;
3116          *     }
3117          * </pre>
3118          *
3119          * where #arr, #len, and #i are freshly named synthetic local variables.
3120          */
3121         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3122             make_at(tree.expr.pos());
3123             VarSymbol arraycache = new VarSymbol(0,
3124                                                  names.fromString("arr" + target.syntheticNameChar()),
3125                                                  tree.expr.type,
3126                                                  currentMethodSym);
3127             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3128             VarSymbol lencache = new VarSymbol(0,
3129                                                names.fromString("len" + target.syntheticNameChar()),
3130                                                syms.intType,
3131                                                currentMethodSym);
3132             JCStatement lencachedef = make.
3133                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3134             VarSymbol index = new VarSymbol(0,
3135                                             names.fromString("i" + target.syntheticNameChar()),
3136                                             syms.intType,
3137                                             currentMethodSym);
3138 
3139             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3140             indexdef.init.type = indexdef.type = syms.intType.constType(0);
3141 
3142             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3143             JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache));
3144 
3145             JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index)));
3146 
3147             Type elemtype = types.elemtype(tree.expr.type);
3148             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3149                                                     make.Ident(index)).setType(elemtype);
3150             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3151                                                   tree.var.name,
3152                                                   tree.var.vartype,
3153                                                   loopvarinit).setType(tree.var.type);
3154             loopvardef.sym = tree.var.sym;
3155             JCBlock body = make.
3156                 Block(0, List.of(loopvardef, tree.body));
3157 
3158             result = translate(make.
3159                                ForLoop(loopinit,
3160                                        cond,
3161                                        List.of(step),
3162                                        body));
3163             patchTargets(body, tree, result);
3164         }
3165         /** Patch up break and continue targets. */
3166         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3167             class Patcher extends TreeScanner {
3168                 public void visitBreak(JCBreak tree) {
3169                     if (tree.target == src)
3170                         tree.target = dest;
3171                 }
3172                 public void visitContinue(JCContinue tree) {
3173                     if (tree.target == src)
3174                         tree.target = dest;
3175                 }
3176                 public void visitClassDef(JCClassDecl tree) {}
3177             }
3178             new Patcher().scan(body);
3179         }
3180         /**
3181          * A statement of the form
3182          *
3183          * <pre>
3184          *     for ( T v : coll ) stmt ;
3185          * </pre>
3186          *
3187          * (where coll implements Iterable<? extends T>) gets translated to
3188          *
3189          * <pre>
3190          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3191          *         T v = (T) #i.next();
3192          *         stmt;
3193          *     }
3194          * </pre>
3195          *
3196          * where #i is a freshly named synthetic local variable.
3197          */
3198         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3199             make_at(tree.expr.pos());
3200             Type iteratorTarget = syms.objectType;
3201             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
3202                                               syms.iterableType.tsym);
3203             if (iterableType.getTypeArguments().nonEmpty())
3204                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3205             Type eType = tree.expr.type;
3206             tree.expr.type = types.erasure(eType);
3207             if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
3208                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3209             Symbol iterator = lookupMethod(tree.expr.pos(),
3210                                            names.iterator,
3211                                            types.erasure(syms.iterableType),
3212                                            List.<Type>nil());
3213             VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
3214                                             types.erasure(iterator.type.getReturnType()),
3215                                             currentMethodSym);
3216             JCStatement init = make.
3217                 VarDef(itvar,
3218                        make.App(make.Select(tree.expr, iterator)));
3219             Symbol hasNext = lookupMethod(tree.expr.pos(),
3220                                           names.hasNext,
3221                                           itvar.type,
3222                                           List.<Type>nil());
3223             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3224             Symbol next = lookupMethod(tree.expr.pos(),
3225                                        names.next,
3226                                        itvar.type,
3227                                        List.<Type>nil());
3228             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3229             if (tree.var.type.isPrimitive())
3230                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3231             else
3232                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3233             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3234                                                   tree.var.name,
3235                                                   tree.var.vartype,
3236                                                   vardefinit).setType(tree.var.type);
3237             indexDef.sym = tree.var.sym;
3238             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3239             body.endpos = TreeInfo.endPos(tree.body);
3240             result = translate(make.
3241                 ForLoop(List.of(init),
3242                         cond,
3243                         List.<JCExpressionStatement>nil(),
3244                         body));
3245             patchTargets(body, tree, result);
3246         }
3247 
3248     public void visitVarDef(JCVariableDecl tree) {
3249         MethodSymbol oldMethodSym = currentMethodSym;
3250         tree.mods = translate(tree.mods);
3251         tree.vartype = translate(tree.vartype);
3252         if (currentMethodSym == null) {
3253             // A class or instance field initializer.
3254             currentMethodSym =
3255                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3256                                  names.empty, null,
3257                                  currentClass);
3258         }
3259         if (tree.init != null) tree.init = translate(tree.init, tree.type);
3260         result = tree;
3261         currentMethodSym = oldMethodSym;
3262     }
3263 
3264     public void visitBlock(JCBlock tree) {
3265         MethodSymbol oldMethodSym = currentMethodSym;
3266         if (currentMethodSym == null) {
3267             // Block is a static or instance initializer.
3268             currentMethodSym =
3269                 new MethodSymbol(tree.flags | BLOCK,
3270                                  names.empty, null,
3271                                  currentClass);
3272         }
3273         super.visitBlock(tree);
3274         currentMethodSym = oldMethodSym;
3275     }
3276 
3277     public void visitDoLoop(JCDoWhileLoop tree) {
3278         tree.body = translate(tree.body);
3279         tree.cond = translate(tree.cond, syms.booleanType);
3280         result = tree;
3281     }
3282 
3283     public void visitWhileLoop(JCWhileLoop tree) {
3284         tree.cond = translate(tree.cond, syms.booleanType);
3285         tree.body = translate(tree.body);
3286         result = tree;
3287     }
3288 
3289     public void visitForLoop(JCForLoop tree) {
3290         tree.init = translate(tree.init);
3291         if (tree.cond != null)
3292             tree.cond = translate(tree.cond, syms.booleanType);
3293         tree.step = translate(tree.step);
3294         tree.body = translate(tree.body);
3295         result = tree;
3296     }
3297 
3298     public void visitReturn(JCReturn tree) {
3299         if (tree.expr != null)
3300             tree.expr = translate(tree.expr,
3301                                   types.erasure(currentMethodDef
3302                                                 .restype.type));
3303         result = tree;
3304     }
3305 
3306     public void visitSwitch(JCSwitch tree) {
3307         Type selsuper = types.supertype(tree.selector.type);
3308         boolean enumSwitch = selsuper != null &&
3309             (tree.selector.type.tsym.flags() & ENUM) != 0;
3310         boolean stringSwitch = selsuper != null &&
3311             types.isSameType(tree.selector.type, syms.stringType);
3312         Type target = enumSwitch ? tree.selector.type :
3313             (stringSwitch? syms.stringType : syms.intType);
3314         tree.selector = translate(tree.selector, target);
3315         tree.cases = translateCases(tree.cases);
3316         if (enumSwitch) {
3317             result = visitEnumSwitch(tree);
3318         } else if (stringSwitch) {
3319             result = visitStringSwitch(tree);
3320         } else {
3321             result = tree;
3322         }
3323     }
3324 
3325     public JCTree visitEnumSwitch(JCSwitch tree) {
3326         TypeSymbol enumSym = tree.selector.type.tsym;
3327         EnumMapping map = mapForEnum(tree.pos(), enumSym);
3328         make_at(tree.pos());
3329         Symbol ordinalMethod = lookupMethod(tree.pos(),
3330                                             names.ordinal,
3331                                             tree.selector.type,
3332                                             List.<Type>nil());
3333         JCArrayAccess selector = make.Indexed(map.mapVar,
3334                                         make.App(make.Select(tree.selector,
3335                                                              ordinalMethod)));
3336         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3337         for (JCCase c : tree.cases) {
3338             if (c.pat != null) {
3339                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3340                 JCLiteral pat = map.forConstant(label);
3341                 cases.append(make.Case(pat, c.stats));
3342             } else {
3343                 cases.append(c);
3344             }
3345         }
3346         JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3347         patchTargets(enumSwitch, tree, enumSwitch);
3348         return enumSwitch;
3349     }
3350 
3351     public JCTree visitStringSwitch(JCSwitch tree) {
3352         List<JCCase> caseList = tree.getCases();
3353         int alternatives = caseList.size();
3354 
3355         if (alternatives == 0) { // Strange but legal possibility
3356             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3357         } else {
3358             /*
3359              * The general approach used is to translate a single
3360              * string switch statement into a series of two chained
3361              * switch statements: the first a synthesized statement
3362              * switching on the argument string's hash value and
3363              * computing a string's position in the list of original
3364              * case labels, if any, followed by a second switch on the
3365              * computed integer value.  The second switch has the same
3366              * code structure as the original string switch statement
3367              * except that the string case labels are replaced with
3368              * positional integer constants starting at 0.
3369              *
3370              * The first switch statement can be thought of as an
3371              * inlined map from strings to their position in the case
3372              * label list.  An alternate implementation would use an
3373              * actual Map for this purpose, as done for enum switches.
3374              *
3375              * With some additional effort, it would be possible to
3376              * use a single switch statement on the hash code of the
3377              * argument, but care would need to be taken to preserve
3378              * the proper control flow in the presence of hash
3379              * collisions and other complications, such as
3380              * fallthroughs.  Switch statements with one or two
3381              * alternatives could also be specially translated into
3382              * if-then statements to omit the computation of the hash
3383              * code.
3384              *
3385              * The generated code assumes that the hashing algorithm
3386              * of String is the same in the compilation environment as
3387              * in the environment the code will run in.  The string
3388              * hashing algorithm in the SE JDK has been unchanged
3389              * since at least JDK 1.2.  Since the algorithm has been
3390              * specified since that release as well, it is very
3391              * unlikely to be changed in the future.
3392              *
3393              * Different hashing algorithms, such as the length of the
3394              * strings or a perfect hashing algorithm over the
3395              * particular set of case labels, could potentially be
3396              * used instead of String.hashCode.
3397              */
3398 
3399             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
3400 
3401             // Map from String case labels to their original position in
3402             // the list of case labels.
3403             Map<String, Integer> caseLabelToPosition =
3404                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
3405 
3406             // Map of hash codes to the string case labels having that hashCode.
3407             Map<Integer, Set<String>> hashToString =
3408                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
3409 
3410             int casePosition = 0;
3411             for(JCCase oneCase : caseList) {
3412                 JCExpression expression = oneCase.getExpression();
3413 
3414                 if (expression != null) { // expression for a "default" case is null
3415                     String labelExpr = (String) expression.type.constValue();
3416                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3417                     Assert.checkNull(mapping);
3418                     int hashCode = labelExpr.hashCode();
3419 
3420                     Set<String> stringSet = hashToString.get(hashCode);
3421                     if (stringSet == null) {
3422                         stringSet = new LinkedHashSet<String>(1, 1.0f);
3423                         stringSet.add(labelExpr);
3424                         hashToString.put(hashCode, stringSet);
3425                     } else {
3426                         boolean added = stringSet.add(labelExpr);
3427                         Assert.check(added);
3428                     }
3429                 }
3430                 casePosition++;
3431             }
3432 
3433             // Synthesize a switch statement that has the effect of
3434             // mapping from a string to the integer position of that
3435             // string in the list of case labels.  This is done by
3436             // switching on the hashCode of the string followed by an
3437             // if-then-else chain comparing the input for equality
3438             // with all the case labels having that hash value.
3439 
3440             /*
3441              * s$ = top of stack;
3442              * tmp$ = -1;
3443              * switch($s.hashCode()) {
3444              *     case caseLabel.hashCode:
3445              *         if (s$.equals("caseLabel_1")
3446              *           tmp$ = caseLabelToPosition("caseLabel_1");
3447              *         else if (s$.equals("caseLabel_2"))
3448              *           tmp$ = caseLabelToPosition("caseLabel_2");
3449              *         ...
3450              *         break;
3451              * ...
3452              * }
3453              */
3454 
3455             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3456                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
3457                                                syms.stringType,
3458                                                currentMethodSym);
3459             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3460 
3461             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3462                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3463                                                  syms.intType,
3464                                                  currentMethodSym);
3465             JCVariableDecl dollar_tmp_def =
3466                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3467             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3468             stmtList.append(dollar_tmp_def);
3469             ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
3470             // hashCode will trigger nullcheck on original switch expression
3471             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3472                                                        names.hashCode,
3473                                                        List.<JCExpression>nil()).setType(syms.intType);
3474             JCSwitch switch1 = make.Switch(hashCodeCall,
3475                                         caseBuffer.toList());
3476             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3477                 int hashCode = entry.getKey();
3478                 Set<String> stringsWithHashCode = entry.getValue();
3479                 Assert.check(stringsWithHashCode.size() >= 1);
3480 
3481                 JCStatement elsepart = null;
3482                 for(String caseLabel : stringsWithHashCode ) {
3483                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3484                                                                    names.equals,
3485                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
3486                     elsepart = make.If(stringEqualsCall,
3487                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
3488                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
3489                                                  setType(dollar_tmp.type)),
3490                                        elsepart);
3491                 }
3492 
3493                 ListBuffer<JCStatement> lb = ListBuffer.lb();
3494                 JCBreak breakStmt = make.Break(null);
3495                 breakStmt.target = switch1;
3496                 lb.append(elsepart).append(breakStmt);
3497 
3498                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3499             }
3500 
3501             switch1.cases = caseBuffer.toList();
3502             stmtList.append(switch1);
3503 
3504             // Make isomorphic switch tree replacing string labels
3505             // with corresponding integer ones from the label to
3506             // position map.
3507 
3508             ListBuffer<JCCase> lb = ListBuffer.lb();
3509             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3510             for(JCCase oneCase : caseList ) {
3511                 // Rewire up old unlabeled break statements to the
3512                 // replacement switch being created.
3513                 patchTargets(oneCase, tree, switch2);
3514 
3515                 boolean isDefault = (oneCase.getExpression() == null);
3516                 JCExpression caseExpr;
3517                 if (isDefault)
3518                     caseExpr = null;
3519                 else {
3520                     caseExpr = make.Literal(caseLabelToPosition.get((String)oneCase.
3521                                                                     getExpression().
3522                                                                     type.constValue()));
3523                 }
3524 
3525                 lb.append(make.Case(caseExpr,
3526                                     oneCase.getStatements()));
3527             }
3528 
3529             switch2.cases = lb.toList();
3530             stmtList.append(switch2);
3531 
3532             return make.Block(0L, stmtList.toList());
3533         }
3534     }
3535 
3536     public void visitNewArray(JCNewArray tree) {
3537         tree.elemtype = translate(tree.elemtype);
3538         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3539             if (t.head != null) t.head = translate(t.head, syms.intType);
3540         tree.elems = translate(tree.elems, types.elemtype(tree.type));
3541         result = tree;
3542     }
3543 
3544     public void visitSelect(JCFieldAccess tree) {
3545         // need to special case-access of the form C.super.x
3546         // these will always need an access method.
3547         boolean qualifiedSuperAccess =
3548             tree.selected.getTag() == JCTree.SELECT &&
3549             TreeInfo.name(tree.selected) == names._super;
3550         tree.selected = translate(tree.selected);
3551         if (tree.name == names._class)
3552             result = classOf(tree.selected);
3553         else if (tree.name == names._this || tree.name == names._super)
3554             result = makeThis(tree.pos(), tree.selected.type.tsym);
3555         else
3556             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3557     }
3558 
3559     public void visitLetExpr(LetExpr tree) {
3560         tree.defs = translateVarDefs(tree.defs);
3561         tree.expr = translate(tree.expr, tree.type);
3562         result = tree;
3563     }
3564 
3565     // There ought to be nothing to rewrite here;
3566     // we don't generate code.
3567     public void visitAnnotation(JCAnnotation tree) {
3568         result = tree;
3569     }
3570 
3571     @Override
3572     public void visitTry(JCTry tree) {
3573         if (tree.resources.isEmpty()) {
3574             super.visitTry(tree);
3575         } else {
3576             result = makeArmTry(tree);
3577         }
3578     }
3579 
3580 /**************************************************************************
3581  * main method
3582  *************************************************************************/
3583 
3584     /** Translate a toplevel class and return a list consisting of
3585      *  the translated class and translated versions of all inner classes.
3586      *  @param env   The attribution environment current at the class definition.
3587      *               We need this for resolving some additional symbols.
3588      *  @param cdef  The tree representing the class definition.
3589      */
3590     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3591         ListBuffer<JCTree> translated = null;
3592         try {
3593             attrEnv = env;
3594             this.make = make;
3595             endPositions = env.toplevel.endPositions;
3596             currentClass = null;
3597             currentMethodDef = null;
3598             outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null;
3599             outermostMemberDef = null;
3600             this.translated = new ListBuffer<JCTree>();
3601             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3602             actualSymbols = new HashMap<Symbol,Symbol>();
3603             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3604             proxies = new Scope(syms.noSymbol);
3605             twrVars = new Scope(syms.noSymbol);
3606             outerThisStack = List.nil();
3607             accessNums = new HashMap<Symbol,Integer>();
3608             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3609             accessConstrs = new HashMap<Symbol,MethodSymbol>();
3610             accessConstrTags = List.nil();
3611             accessed = new ListBuffer<Symbol>();
3612             translate(cdef, (JCExpression)null);
3613             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3614                 makeAccessible(l.head);
3615             for (EnumMapping map : enumSwitchMap.values())
3616                 map.translate();
3617             checkConflicts(this.translated.toList());
3618             checkAccessConstructorTags();
3619             translated = this.translated;
3620         } finally {
3621             // note that recursive invocations of this method fail hard
3622             attrEnv = null;
3623             this.make = null;
3624             endPositions = null;
3625             currentClass = null;
3626             currentMethodDef = null;
3627             outermostClassDef = null;
3628             outermostMemberDef = null;
3629             this.translated = null;
3630             classdefs = null;
3631             actualSymbols = null;
3632             freevarCache = null;
3633             proxies = null;
3634             outerThisStack = null;
3635             accessNums = null;
3636             accessSyms = null;
3637             accessConstrs = null;
3638             accessConstrTags = null;
3639             accessed = null;
3640             enumSwitchMap.clear();
3641         }
3642         return translated.toList();
3643     }
3644 
3645     //////////////////////////////////////////////////////////////
3646     // The following contributed by Borland for bootstrapping purposes
3647     //////////////////////////////////////////////////////////////
3648     private void addEnumCompatibleMembers(JCClassDecl cdef) {
3649         make_at(null);
3650 
3651         // Add the special enum fields
3652         VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
3653         VarSymbol nameFieldSym = addEnumNameField(cdef);
3654 
3655         // Add the accessor methods for name and ordinal
3656         MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
3657         MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
3658 
3659         // Add the toString method
3660         addEnumToString(cdef, nameFieldSym);
3661 
3662         // Add the compareTo method
3663         addEnumCompareTo(cdef, ordinalFieldSym);
3664     }
3665 
3666     private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
3667         VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3668                                           names.fromString("$ordinal"),
3669                                           syms.intType,
3670                                           cdef.sym);
3671         cdef.sym.members().enter(ordinal);
3672         cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
3673         return ordinal;
3674     }
3675 
3676     private VarSymbol addEnumNameField(JCClassDecl cdef) {
3677         VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3678                                           names.fromString("$name"),
3679                                           syms.stringType,
3680                                           cdef.sym);
3681         cdef.sym.members().enter(name);
3682         cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
3683         return name;
3684     }
3685 
3686     private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3687         // Add the accessor methods for ordinal
3688         Symbol ordinalSym = lookupMethod(cdef.pos(),
3689                                          names.ordinal,
3690                                          cdef.type,
3691                                          List.<Type>nil());
3692 
3693         Assert.check(ordinalSym instanceof MethodSymbol);
3694 
3695         JCStatement ret = make.Return(make.Ident(ordinalSymbol));
3696         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
3697                                                     make.Block(0L, List.of(ret))));
3698 
3699         return (MethodSymbol)ordinalSym;
3700     }
3701 
3702     private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
3703         // Add the accessor methods for name
3704         Symbol nameSym = lookupMethod(cdef.pos(),
3705                                    names._name,
3706                                    cdef.type,
3707                                    List.<Type>nil());
3708 
3709         Assert.check(nameSym instanceof MethodSymbol);
3710 
3711         JCStatement ret = make.Return(make.Ident(nameSymbol));
3712 
3713         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
3714                                                     make.Block(0L, List.of(ret))));
3715 
3716         return (MethodSymbol)nameSym;
3717     }
3718 
3719     private MethodSymbol addEnumToString(JCClassDecl cdef,
3720                                          VarSymbol nameSymbol) {
3721         Symbol toStringSym = lookupMethod(cdef.pos(),
3722                                           names.toString,
3723                                           cdef.type,
3724                                           List.<Type>nil());
3725 
3726         JCTree toStringDecl = null;
3727         if (toStringSym != null)
3728             toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
3729 
3730         if (toStringDecl != null)
3731             return (MethodSymbol)toStringSym;
3732 
3733         JCStatement ret = make.Return(make.Ident(nameSymbol));
3734 
3735         JCTree resTypeTree = make.Type(syms.stringType);
3736 
3737         MethodType toStringType = new MethodType(List.<Type>nil(),
3738                                                  syms.stringType,
3739                                                  List.<Type>nil(),
3740                                                  cdef.sym);
3741         toStringSym = new MethodSymbol(PUBLIC,
3742                                        names.toString,
3743                                        toStringType,
3744                                        cdef.type.tsym);
3745         toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
3746                                       make.Block(0L, List.of(ret)));
3747 
3748         cdef.defs = cdef.defs.prepend(toStringDecl);
3749         cdef.sym.members().enter(toStringSym);
3750 
3751         return (MethodSymbol)toStringSym;
3752     }
3753 
3754     private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3755         Symbol compareToSym = lookupMethod(cdef.pos(),
3756                                    names.compareTo,
3757                                    cdef.type,
3758                                    List.of(cdef.sym.type));
3759 
3760         Assert.check(compareToSym instanceof MethodSymbol);
3761 
3762         JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
3763 
3764         ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
3765 
3766         JCModifiers mod1 = make.Modifiers(0L);
3767         Name oName = names.fromString("o");
3768         JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
3769 
3770         JCIdent paramId1 = make.Ident(names.java_lang_Object);
3771         paramId1.type = cdef.type;
3772         paramId1.sym = par1.sym;
3773 
3774         ((MethodSymbol)compareToSym).params = List.of(par1.sym);
3775 
3776         JCIdent par1UsageId = make.Ident(par1.sym);
3777         JCIdent castTargetIdent = make.Ident(cdef.sym);
3778         JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
3779         cast.setType(castTargetIdent.type);
3780 
3781         Name otherName = names.fromString("other");
3782 
3783         VarSymbol otherVarSym = new VarSymbol(mod1.flags,
3784                                               otherName,
3785                                               cdef.type,
3786                                               compareToSym);
3787         JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
3788         blockStatements.append(otherVar);
3789 
3790         JCIdent id1 = make.Ident(ordinalSymbol);
3791 
3792         JCIdent fLocUsageId = make.Ident(otherVarSym);
3793         JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
3794         JCBinary bin = makeBinary(JCTree.MINUS, id1, sel);
3795         JCReturn ret = make.Return(bin);
3796         blockStatements.append(ret);
3797         JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
3798                                                    make.Block(0L,
3799                                                               blockStatements.toList()));
3800         compareToMethod.params = List.of(par1);
3801         cdef.defs = cdef.defs.append(compareToMethod);
3802 
3803         return (MethodSymbol)compareToSym;
3804     }
3805     //////////////////////////////////////////////////////////////
3806     // The above contributed by Borland for bootstrapping purposes
3807     //////////////////////////////////////////////////////////////
3808 }