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 (primaryException != null) {try...} else resourceClose;
1529         JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
1530                                         tryTree,
1531                                         makeResourceCloseInvocation(resource));
1532         return make.Block(0L, List.<JCStatement>of(closeIfStatement));
1533     }
1534 
1535     private JCStatement makeResourceCloseInvocation(JCExpression resource) {
1536         // create resource.close() method invocation protected by a null-check
1537 
1538         JCExpression resourceClose = makeCall(resource,
1539                                               names.close,
1540                                               List.<JCExpression>nil());
1541 
1542         return make.If(makeNonNullCheck(resource), make.Exec(resourceClose), null);
1543     }
1544 
1545     private JCExpression makeNonNullCheck(JCExpression expression) {
1546         return makeBinary(JCTree.NE, expression, makeNull());
1547     }
1548 
1549     /** Construct a tree that represents the outer instance
1550      *  <C.this>. Never pick the current `this'.
1551      *  @param pos           The source code position to be used for the tree.
1552      *  @param c             The qualifier class.
1553      */
1554     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1555         List<VarSymbol> ots = outerThisStack;
1556         if (ots.isEmpty()) {
1557             log.error(pos, "no.encl.instance.of.type.in.scope", c);
1558             Assert.error();
1559             return makeNull();
1560         }
1561         VarSymbol ot = ots.head;
1562         JCExpression tree = access(make.at(pos).Ident(ot));
1563         TypeSymbol otc = ot.type.tsym;
1564         while (otc != c) {
1565             do {
1566                 ots = ots.tail;
1567                 if (ots.isEmpty()) {
1568                     log.error(pos,
1569                               "no.encl.instance.of.type.in.scope",
1570                               c);
1571                     Assert.error(); // should have been caught in Attr
1572                     return tree;
1573                 }
1574                 ot = ots.head;
1575             } while (ot.owner != otc);
1576             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1577                 chk.earlyRefError(pos, c);
1578                 Assert.error(); // should have been caught in Attr
1579                 return makeNull();
1580             }
1581             tree = access(make.at(pos).Select(tree, ot));
1582             otc = ot.type.tsym;
1583         }
1584         return tree;
1585     }
1586 
1587     /** Construct a tree that represents the closest outer instance
1588      *  <C.this> such that the given symbol is a member of C.
1589      *  @param pos           The source code position to be used for the tree.
1590      *  @param sym           The accessed symbol.
1591      *  @param preciseMatch  should we accept a type that is a subtype of
1592      *                       sym's owner, even if it doesn't contain sym
1593      *                       due to hiding, overriding, or non-inheritance
1594      *                       due to protection?
1595      */
1596     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1597         Symbol c = sym.owner;
1598         if (preciseMatch ? sym.isMemberOf(currentClass, types)
1599                          : currentClass.isSubClass(sym.owner, types)) {
1600             // in this case, `this' works fine
1601             return make.at(pos).This(c.erasure(types));
1602         } else {
1603             // need to go via this$n
1604             return makeOwnerThisN(pos, sym, preciseMatch);
1605         }
1606     }
1607 
1608     /**
1609      * Similar to makeOwnerThis but will never pick "this".
1610      */
1611     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1612         Symbol c = sym.owner;
1613         List<VarSymbol> ots = outerThisStack;
1614         if (ots.isEmpty()) {
1615             log.error(pos, "no.encl.instance.of.type.in.scope", c);
1616             Assert.error();
1617             return makeNull();
1618         }
1619         VarSymbol ot = ots.head;
1620         JCExpression tree = access(make.at(pos).Ident(ot));
1621         TypeSymbol otc = ot.type.tsym;
1622         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1623             do {
1624                 ots = ots.tail;
1625                 if (ots.isEmpty()) {
1626                     log.error(pos,
1627                         "no.encl.instance.of.type.in.scope",
1628                         c);
1629                     Assert.error();
1630                     return tree;
1631                 }
1632                 ot = ots.head;
1633             } while (ot.owner != otc);
1634             tree = access(make.at(pos).Select(tree, ot));
1635             otc = ot.type.tsym;
1636         }
1637         return tree;
1638     }
1639 
1640     /** Return tree simulating the assignment <this.name = name>, where
1641      *  name is the name of a free variable.
1642      */
1643     JCStatement initField(int pos, Name name) {
1644         Scope.Entry e = proxies.lookup(name);
1645         Symbol rhs = e.sym;
1646         Assert.check(rhs.owner.kind == MTH);
1647         Symbol lhs = e.next().sym;
1648         Assert.check(rhs.owner.owner == lhs.owner);
1649         make.at(pos);
1650         return
1651             make.Exec(
1652                 make.Assign(
1653                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
1654                     make.Ident(rhs)).setType(lhs.erasure(types)));
1655     }
1656 
1657     /** Return tree simulating the assignment <this.this$n = this$n>.
1658      */
1659     JCStatement initOuterThis(int pos) {
1660         VarSymbol rhs = outerThisStack.head;
1661         Assert.check(rhs.owner.kind == MTH);
1662         VarSymbol lhs = outerThisStack.tail.head;
1663         Assert.check(rhs.owner.owner == lhs.owner);
1664         make.at(pos);
1665         return
1666             make.Exec(
1667                 make.Assign(
1668                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
1669                     make.Ident(rhs)).setType(lhs.erasure(types)));
1670     }
1671 
1672 /**************************************************************************
1673  * Code for .class
1674  *************************************************************************/
1675 
1676     /** Return the symbol of a class to contain a cache of
1677      *  compiler-generated statics such as class$ and the
1678      *  $assertionsDisabled flag.  We create an anonymous nested class
1679      *  (unless one already exists) and return its symbol.  However,
1680      *  for backward compatibility in 1.4 and earlier we use the
1681      *  top-level class itself.
1682      */
1683     private ClassSymbol outerCacheClass() {
1684         ClassSymbol clazz = outermostClassDef.sym;
1685         if ((clazz.flags() & INTERFACE) == 0 &&
1686             !target.useInnerCacheClass()) return clazz;
1687         Scope s = clazz.members();
1688         for (Scope.Entry e = s.elems; e != null; e = e.sibling)
1689             if (e.sym.kind == TYP &&
1690                 e.sym.name == names.empty &&
1691                 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
1692         return makeEmptyClass(STATIC | SYNTHETIC, clazz);
1693     }
1694 
1695     /** Return symbol for "class$" method. If there is no method definition
1696      *  for class$, construct one as follows:
1697      *
1698      *    class class$(String x0) {
1699      *      try {
1700      *        return Class.forName(x0);
1701      *      } catch (ClassNotFoundException x1) {
1702      *        throw new NoClassDefFoundError(x1.getMessage());
1703      *      }
1704      *    }
1705      */
1706     private MethodSymbol classDollarSym(DiagnosticPosition pos) {
1707         ClassSymbol outerCacheClass = outerCacheClass();
1708         MethodSymbol classDollarSym =
1709             (MethodSymbol)lookupSynthetic(classDollar,
1710                                           outerCacheClass.members());
1711         if (classDollarSym == null) {
1712             classDollarSym = new MethodSymbol(
1713                 STATIC | SYNTHETIC,
1714                 classDollar,
1715                 new MethodType(
1716                     List.of(syms.stringType),
1717                     types.erasure(syms.classType),
1718                     List.<Type>nil(),
1719                     syms.methodClass),
1720                 outerCacheClass);
1721             enterSynthetic(pos, classDollarSym, outerCacheClass.members());
1722 
1723             JCMethodDecl md = make.MethodDef(classDollarSym, null);
1724             try {
1725                 md.body = classDollarSymBody(pos, md);
1726             } catch (CompletionFailure ex) {
1727                 md.body = make.Block(0, List.<JCStatement>nil());
1728                 chk.completionError(pos, ex);
1729             }
1730             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1731             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
1732         }
1733         return classDollarSym;
1734     }
1735 
1736     /** Generate code for class$(String name). */
1737     JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
1738         MethodSymbol classDollarSym = md.sym;
1739         ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
1740 
1741         JCBlock returnResult;
1742 
1743         // in 1.4.2 and above, we use
1744         // Class.forName(String name, boolean init, ClassLoader loader);
1745         // which requires we cache the current loader in cl$
1746         if (target.classLiteralsNoInit()) {
1747             // clsym = "private static ClassLoader cl$"
1748             VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
1749                                             names.fromString("cl" + target.syntheticNameChar()),
1750                                             syms.classLoaderType,
1751                                             outerCacheClass);
1752             enterSynthetic(pos, clsym, outerCacheClass.members());
1753 
1754             // emit "private static ClassLoader cl$;"
1755             JCVariableDecl cldef = make.VarDef(clsym, null);
1756             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1757             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
1758 
1759             // newcache := "new cache$1[0]"
1760             JCNewArray newcache = make.
1761                 NewArray(make.Type(outerCacheClass.type),
1762                          List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
1763                          null);
1764             newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
1765                                           syms.arrayClass);
1766 
1767             // forNameSym := java.lang.Class.forName(
1768             //     String s,boolean init,ClassLoader loader)
1769             Symbol forNameSym = lookupMethod(make_pos, names.forName,
1770                                              types.erasure(syms.classType),
1771                                              List.of(syms.stringType,
1772                                                      syms.booleanType,
1773                                                      syms.classLoaderType));
1774             // clvalue := "(cl$ == null) ?
1775             // $newcache.getClass().getComponentType().getClassLoader() : cl$"
1776             JCExpression clvalue =
1777                 make.Conditional(
1778                     makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()),
1779                     make.Assign(
1780                         make.Ident(clsym),
1781                         makeCall(
1782                             makeCall(makeCall(newcache,
1783                                               names.getClass,
1784                                               List.<JCExpression>nil()),
1785                                      names.getComponentType,
1786                                      List.<JCExpression>nil()),
1787                             names.getClassLoader,
1788                             List.<JCExpression>nil())).setType(syms.classLoaderType),
1789                     make.Ident(clsym)).setType(syms.classLoaderType);
1790 
1791             // returnResult := "{ return Class.forName(param1, false, cl$); }"
1792             List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
1793                                               makeLit(syms.booleanType, 0),
1794                                               clvalue);
1795             returnResult = make.
1796                 Block(0, List.<JCStatement>of(make.
1797                               Call(make. // return
1798                                    App(make.
1799                                        Ident(forNameSym), args))));
1800         } else {
1801             // forNameSym := java.lang.Class.forName(String s)
1802             Symbol forNameSym = lookupMethod(make_pos,
1803                                              names.forName,
1804                                              types.erasure(syms.classType),
1805                                              List.of(syms.stringType));
1806             // returnResult := "{ return Class.forName(param1); }"
1807             returnResult = make.
1808                 Block(0, List.of(make.
1809                           Call(make. // return
1810                               App(make.
1811                                   QualIdent(forNameSym),
1812                                   List.<JCExpression>of(make.
1813                                                         Ident(md.params.
1814                                                               head.sym))))));
1815         }
1816 
1817         // catchParam := ClassNotFoundException e1
1818         VarSymbol catchParam =
1819             new VarSymbol(0, make.paramName(1),
1820                           syms.classNotFoundExceptionType,
1821                           classDollarSym);
1822 
1823         JCStatement rethrow;
1824         if (target.hasInitCause()) {
1825             // rethrow = "throw new NoClassDefFoundError().initCause(e);
1826             JCTree throwExpr =
1827                 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
1828                                       List.<JCExpression>nil()),
1829                          names.initCause,
1830                          List.<JCExpression>of(make.Ident(catchParam)));
1831             rethrow = make.Throw(throwExpr);
1832         } else {
1833             // getMessageSym := ClassNotFoundException.getMessage()
1834             Symbol getMessageSym = lookupMethod(make_pos,
1835                                                 names.getMessage,
1836                                                 syms.classNotFoundExceptionType,
1837                                                 List.<Type>nil());
1838             // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
1839             rethrow = make.
1840                 Throw(makeNewClass(syms.noClassDefFoundErrorType,
1841                           List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
1842                                                                      getMessageSym),
1843                                                          List.<JCExpression>nil()))));
1844         }
1845 
1846         // rethrowStmt := "( $rethrow )"
1847         JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
1848 
1849         // catchBlock := "catch ($catchParam) $rethrowStmt"
1850         JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
1851                                       rethrowStmt);
1852 
1853         // tryCatch := "try $returnResult $catchBlock"
1854         JCStatement tryCatch = make.Try(returnResult,
1855                                         List.of(catchBlock), null);
1856 
1857         return make.Block(0, List.of(tryCatch));
1858     }
1859     // where
1860         /** Create an attributed tree of the form left.name(). */
1861         private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1862             Assert.checkNonNull(left.type);
1863             Symbol funcsym = lookupMethod(make_pos, name, left.type,
1864                                           TreeInfo.types(args));
1865             return make.App(make.Select(left, funcsym), args);
1866         }
1867 
1868     /** The Name Of The variable to cache T.class values.
1869      *  @param sig      The signature of type T.
1870      */
1871     private Name cacheName(String sig) {
1872         StringBuffer buf = new StringBuffer();
1873         if (sig.startsWith("[")) {
1874             buf = buf.append("array");
1875             while (sig.startsWith("[")) {
1876                 buf = buf.append(target.syntheticNameChar());
1877                 sig = sig.substring(1);
1878             }
1879             if (sig.startsWith("L")) {
1880                 sig = sig.substring(0, sig.length() - 1);
1881             }
1882         } else {
1883             buf = buf.append("class" + target.syntheticNameChar());
1884         }
1885         buf = buf.append(sig.replace('.', target.syntheticNameChar()));
1886         return names.fromString(buf.toString());
1887     }
1888 
1889     /** The variable symbol that caches T.class values.
1890      *  If none exists yet, create a definition.
1891      *  @param sig      The signature of type T.
1892      *  @param pos      The position to report diagnostics, if any.
1893      */
1894     private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
1895         ClassSymbol outerCacheClass = outerCacheClass();
1896         Name cname = cacheName(sig);
1897         VarSymbol cacheSym =
1898             (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
1899         if (cacheSym == null) {
1900             cacheSym = new VarSymbol(
1901                 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
1902             enterSynthetic(pos, cacheSym, outerCacheClass.members());
1903 
1904             JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
1905             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1906             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
1907         }
1908         return cacheSym;
1909     }
1910 
1911     /** The tree simulating a T.class expression.
1912      *  @param clazz      The tree identifying type T.
1913      */
1914     private JCExpression classOf(JCTree clazz) {
1915         return classOfType(clazz.type, clazz.pos());
1916     }
1917 
1918     private JCExpression classOfType(Type type, DiagnosticPosition pos) {
1919         switch (type.tag) {
1920         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1921         case DOUBLE: case BOOLEAN: case VOID:
1922             // replace with <BoxedClass>.TYPE
1923             ClassSymbol c = types.boxedClass(type);
1924             Symbol typeSym =
1925                 rs.access(
1926                     rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
1927                     pos, c.type, names.TYPE, true);
1928             if (typeSym.kind == VAR)
1929                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
1930             return make.QualIdent(typeSym);
1931         case CLASS: case ARRAY:
1932             if (target.hasClassLiterals()) {
1933                 VarSymbol sym = new VarSymbol(
1934                         STATIC | PUBLIC | FINAL, names._class,
1935                         syms.classType, type.tsym);
1936                 return make_at(pos).Select(make.Type(type), sym);
1937             }
1938             // replace with <cache == null ? cache = class$(tsig) : cache>
1939             // where
1940             //  - <tsig>  is the type signature of T,
1941             //  - <cache> is the cache variable for tsig.
1942             String sig =
1943                 writer.xClassName(type).toString().replace('/', '.');
1944             Symbol cs = cacheSym(pos, sig);
1945             return make_at(pos).Conditional(
1946                 makeBinary(JCTree.EQ, make.Ident(cs), makeNull()),
1947                 make.Assign(
1948                     make.Ident(cs),
1949                     make.App(
1950                         make.Ident(classDollarSym(pos)),
1951                         List.<JCExpression>of(make.Literal(CLASS, sig)
1952                                               .setType(syms.stringType))))
1953                 .setType(types.erasure(syms.classType)),
1954                 make.Ident(cs)).setType(types.erasure(syms.classType));
1955         default:
1956             throw new AssertionError();
1957         }
1958     }
1959 
1960 /**************************************************************************
1961  * Code for enabling/disabling assertions.
1962  *************************************************************************/
1963 
1964     // This code is not particularly robust if the user has
1965     // previously declared a member named '$assertionsDisabled'.
1966     // The same faulty idiom also appears in the translation of
1967     // class literals above.  We should report an error if a
1968     // previous declaration is not synthetic.
1969 
1970     private JCExpression assertFlagTest(DiagnosticPosition pos) {
1971         // Outermost class may be either true class or an interface.
1972         ClassSymbol outermostClass = outermostClassDef.sym;
1973 
1974         // note that this is a class, as an interface can't contain a statement.
1975         ClassSymbol container = currentClass;
1976 
1977         VarSymbol assertDisabledSym =
1978             (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
1979                                        container.members());
1980         if (assertDisabledSym == null) {
1981             assertDisabledSym =
1982                 new VarSymbol(STATIC | FINAL | SYNTHETIC,
1983                               dollarAssertionsDisabled,
1984                               syms.booleanType,
1985                               container);
1986             enterSynthetic(pos, assertDisabledSym, container.members());
1987             Symbol desiredAssertionStatusSym = lookupMethod(pos,
1988                                                             names.desiredAssertionStatus,
1989                                                             types.erasure(syms.classType),
1990                                                             List.<Type>nil());
1991             JCClassDecl containerDef = classDef(container);
1992             make_at(containerDef.pos());
1993             JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select(
1994                     classOfType(types.erasure(outermostClass.type),
1995                                 containerDef.pos()),
1996                     desiredAssertionStatusSym)));
1997             JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
1998                                                    notStatus);
1999             containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
2000         }
2001         make_at(pos);
2002         return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym));
2003     }
2004 
2005 
2006 /**************************************************************************
2007  * Building blocks for let expressions
2008  *************************************************************************/
2009 
2010     interface TreeBuilder {
2011         JCTree build(JCTree arg);
2012     }
2013 
2014     /** Construct an expression using the builder, with the given rval
2015      *  expression as an argument to the builder.  However, the rval
2016      *  expression must be computed only once, even if used multiple
2017      *  times in the result of the builder.  We do that by
2018      *  constructing a "let" expression that saves the rvalue into a
2019      *  temporary variable and then uses the temporary variable in
2020      *  place of the expression built by the builder.  The complete
2021      *  resulting expression is of the form
2022      *  <pre>
2023      *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
2024      *     in (<b>BUILDER</b>(<b>TEMP</b>)))
2025      *  </pre>
2026      *  where <code><b>TEMP</b></code> is a newly declared variable
2027      *  in the let expression.
2028      */
2029     JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
2030         rval = TreeInfo.skipParens(rval);
2031         switch (rval.getTag()) {
2032         case JCTree.LITERAL:
2033             return builder.build(rval);
2034         case JCTree.IDENT:
2035             JCIdent id = (JCIdent) rval;
2036             if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
2037                 return builder.build(rval);
2038         }
2039         VarSymbol var =
2040             new VarSymbol(FINAL|SYNTHETIC,
2041                           names.fromString(
2042                                           target.syntheticNameChar()
2043                                           + "" + rval.hashCode()),
2044                                       type,
2045                                       currentMethodSym);
2046         rval = convert(rval,type);
2047         JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
2048         JCTree built = builder.build(make.Ident(var));
2049         JCTree res = make.LetExpr(def, built);
2050         res.type = built.type;
2051         return res;
2052     }
2053 
2054     // same as above, with the type of the temporary variable computed
2055     JCTree abstractRval(JCTree rval, TreeBuilder builder) {
2056         return abstractRval(rval, rval.type, builder);
2057     }
2058 
2059     // same as above, but for an expression that may be used as either
2060     // an rvalue or an lvalue.  This requires special handling for
2061     // Select expressions, where we place the left-hand-side of the
2062     // select in a temporary, and for Indexed expressions, where we
2063     // place both the indexed expression and the index value in temps.
2064     JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
2065         lval = TreeInfo.skipParens(lval);
2066         switch (lval.getTag()) {
2067         case JCTree.IDENT:
2068             return builder.build(lval);
2069         case JCTree.SELECT: {
2070             final JCFieldAccess s = (JCFieldAccess)lval;
2071             JCTree selected = TreeInfo.skipParens(s.selected);
2072             Symbol lid = TreeInfo.symbol(s.selected);
2073             if (lid != null && lid.kind == TYP) return builder.build(lval);
2074             return abstractRval(s.selected, new TreeBuilder() {
2075                     public JCTree build(final JCTree selected) {
2076                         return builder.build(make.Select((JCExpression)selected, s.sym));
2077                     }
2078                 });
2079         }
2080         case JCTree.INDEXED: {
2081             final JCArrayAccess i = (JCArrayAccess)lval;
2082             return abstractRval(i.indexed, new TreeBuilder() {
2083                     public JCTree build(final JCTree indexed) {
2084                         return abstractRval(i.index, syms.intType, new TreeBuilder() {
2085                                 public JCTree build(final JCTree index) {
2086                                     JCTree newLval = make.Indexed((JCExpression)indexed,
2087                                                                 (JCExpression)index);
2088                                     newLval.setType(i.type);
2089                                     return builder.build(newLval);
2090                                 }
2091                             });
2092                     }
2093                 });
2094         }
2095         case JCTree.TYPECAST: {
2096             return abstractLval(((JCTypeCast)lval).expr, builder);
2097         }
2098         }
2099         throw new AssertionError(lval);
2100     }
2101 
2102     // evaluate and discard the first expression, then evaluate the second.
2103     JCTree makeComma(final JCTree expr1, final JCTree expr2) {
2104         return abstractRval(expr1, new TreeBuilder() {
2105                 public JCTree build(final JCTree discarded) {
2106                     return expr2;
2107                 }
2108             });
2109     }
2110 
2111 /**************************************************************************
2112  * Translation methods
2113  *************************************************************************/
2114 
2115     /** Visitor argument: enclosing operator node.
2116      */
2117     private JCExpression enclOp;
2118 
2119     /** Visitor method: Translate a single node.
2120      *  Attach the source position from the old tree to its replacement tree.
2121      */
2122     public <T extends JCTree> T translate(T tree) {
2123         if (tree == null) {
2124             return null;
2125         } else {
2126             make_at(tree.pos());
2127             T result = super.translate(tree);
2128             if (endPositions != null && result != tree) {
2129                 Integer endPos = endPositions.remove(tree);
2130                 if (endPos != null) endPositions.put(result, endPos);
2131             }
2132             return result;
2133         }
2134     }
2135 
2136     /** Visitor method: Translate a single node, boxing or unboxing if needed.
2137      */
2138     public <T extends JCTree> T translate(T tree, Type type) {
2139         return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2140     }
2141 
2142     /** Visitor method: Translate tree.
2143      */
2144     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2145         JCExpression prevEnclOp = this.enclOp;
2146         this.enclOp = enclOp;
2147         T res = translate(tree);
2148         this.enclOp = prevEnclOp;
2149         return res;
2150     }
2151 
2152     /** Visitor method: Translate list of trees.
2153      */
2154     public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2155         JCExpression prevEnclOp = this.enclOp;
2156         this.enclOp = enclOp;
2157         List<T> res = translate(trees);
2158         this.enclOp = prevEnclOp;
2159         return res;
2160     }
2161 
2162     /** Visitor method: Translate list of trees.
2163      */
2164     public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
2165         if (trees == null) return null;
2166         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2167             l.head = translate(l.head, type);
2168         return trees;
2169     }
2170 
2171     public void visitTopLevel(JCCompilationUnit tree) {
2172         if (needPackageInfoClass(tree)) {
2173             Name name = names.package_info;
2174             long flags = Flags.ABSTRACT | Flags.INTERFACE;
2175             if (target.isPackageInfoSynthetic())
2176                 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2177                 flags = flags | Flags.SYNTHETIC;
2178             JCClassDecl packageAnnotationsClass
2179                 = make.ClassDef(make.Modifiers(flags,
2180                                                tree.packageAnnotations),
2181                                 name, List.<JCTypeParameter>nil(),
2182                                 null, List.<JCExpression>nil(), List.<JCTree>nil());
2183             ClassSymbol c = tree.packge.package_info;
2184             c.flags_field |= flags;
2185             c.attributes_field = tree.packge.attributes_field;
2186             ClassType ctype = (ClassType) c.type;
2187             ctype.supertype_field = syms.objectType;
2188             ctype.interfaces_field = List.nil();
2189             packageAnnotationsClass.sym = c;
2190 
2191             translated.append(packageAnnotationsClass);
2192         }
2193     }
2194     // where
2195     private boolean needPackageInfoClass(JCCompilationUnit tree) {
2196         switch (pkginfoOpt) {
2197             case ALWAYS:
2198                 return true;
2199             case LEGACY:
2200                 return tree.packageAnnotations.nonEmpty();
2201             case NONEMPTY:
2202                 for (Attribute.Compound a: tree.packge.attributes_field) {
2203                     Attribute.RetentionPolicy p = types.getRetention(a);
2204                     if (p != Attribute.RetentionPolicy.SOURCE)
2205                         return true;
2206                 }
2207                 return false;
2208         }
2209         throw new AssertionError();
2210     }
2211 
2212     public void visitClassDef(JCClassDecl tree) {
2213         ClassSymbol currentClassPrev = currentClass;
2214         MethodSymbol currentMethodSymPrev = currentMethodSym;
2215         currentClass = tree.sym;
2216         currentMethodSym = null;
2217         classdefs.put(currentClass, tree);
2218 
2219         proxies = proxies.dup(currentClass);
2220         List<VarSymbol> prevOuterThisStack = outerThisStack;
2221 
2222         // If this is an enum definition
2223         if ((tree.mods.flags & ENUM) != 0 &&
2224             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2225             visitEnumDef(tree);
2226 
2227         // If this is a nested class, define a this$n field for
2228         // it and add to proxies.
2229         JCVariableDecl otdef = null;
2230         if (currentClass.hasOuterInstance())
2231             otdef = outerThisDef(tree.pos, currentClass);
2232 
2233         // If this is a local class, define proxies for all its free variables.
2234         List<JCVariableDecl> fvdefs = freevarDefs(
2235             tree.pos, freevars(currentClass), currentClass);
2236 
2237         // Recursively translate superclass, interfaces.
2238         tree.extending = translate(tree.extending);
2239         tree.implementing = translate(tree.implementing);
2240 
2241         // Recursively translate members, taking into account that new members
2242         // might be created during the translation and prepended to the member
2243         // list `tree.defs'.
2244         List<JCTree> seen = List.nil();
2245         while (tree.defs != seen) {
2246             List<JCTree> unseen = tree.defs;
2247             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2248                 JCTree outermostMemberDefPrev = outermostMemberDef;
2249                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2250                 l.head = translate(l.head);
2251                 outermostMemberDef = outermostMemberDefPrev;
2252             }
2253             seen = unseen;
2254         }
2255 
2256         // Convert a protected modifier to public, mask static modifier.
2257         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2258         tree.mods.flags &= ClassFlags;
2259 
2260         // Convert name to flat representation, replacing '.' by '$'.
2261         tree.name = Convert.shortName(currentClass.flatName());
2262 
2263         // Add this$n and free variables proxy definitions to class.
2264         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2265             tree.defs = tree.defs.prepend(l.head);
2266             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2267         }
2268         if (currentClass.hasOuterInstance()) {
2269             tree.defs = tree.defs.prepend(otdef);
2270             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2271         }
2272 
2273         proxies = proxies.leave();
2274         outerThisStack = prevOuterThisStack;
2275 
2276         // Append translated tree to `translated' queue.
2277         translated.append(tree);
2278 
2279         currentClass = currentClassPrev;
2280         currentMethodSym = currentMethodSymPrev;
2281 
2282         // Return empty block {} as a placeholder for an inner class.
2283         result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
2284     }
2285 
2286     /** Translate an enum class. */
2287     private void visitEnumDef(JCClassDecl tree) {
2288         make_at(tree.pos());
2289 
2290         // add the supertype, if needed
2291         if (tree.extending == null)
2292             tree.extending = make.Type(types.supertype(tree.type));
2293 
2294         // classOfType adds a cache field to tree.defs unless
2295         // target.hasClassLiterals().
2296         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2297             setType(types.erasure(syms.classType));
2298 
2299         // process each enumeration constant, adding implicit constructor parameters
2300         int nextOrdinal = 0;
2301         ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
2302         ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
2303         ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
2304         for (List<JCTree> defs = tree.defs;
2305              defs.nonEmpty();
2306              defs=defs.tail) {
2307             if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2308                 JCVariableDecl var = (JCVariableDecl)defs.head;
2309                 visitEnumConstantDef(var, nextOrdinal++);
2310                 values.append(make.QualIdent(var.sym));
2311                 enumDefs.append(var);
2312             } else {
2313                 otherDefs.append(defs.head);
2314             }
2315         }
2316 
2317         // private static final T[] #VALUES = { a, b, c };
2318         Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2319         while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
2320             valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2321         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2322         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2323                                             valuesName,
2324                                             arrayType,
2325                                             tree.type.tsym);
2326         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2327                                           List.<JCExpression>nil(),
2328                                           values.toList());
2329         newArray.type = arrayType;
2330         enumDefs.append(make.VarDef(valuesVar, newArray));
2331         tree.sym.members().enter(valuesVar);
2332 
2333         Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2334                                         tree.type, List.<Type>nil());
2335         List<JCStatement> valuesBody;
2336         if (useClone()) {
2337             // return (T[]) $VALUES.clone();
2338             JCTypeCast valuesResult =
2339                 make.TypeCast(valuesSym.type.getReturnType(),
2340                               make.App(make.Select(make.Ident(valuesVar),
2341                                                    syms.arrayCloneMethod)));
2342             valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2343         } else {
2344             // template: T[] $result = new T[$values.length];
2345             Name resultName = names.fromString(target.syntheticNameChar() + "result");
2346             while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
2347                 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2348             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2349                                                 resultName,
2350                                                 arrayType,
2351                                                 valuesSym);
2352             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2353                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2354                                   null);
2355             resultArray.type = arrayType;
2356             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2357 
2358             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2359             if (systemArraycopyMethod == null) {
2360                 systemArraycopyMethod =
2361                     new MethodSymbol(PUBLIC | STATIC,
2362                                      names.fromString("arraycopy"),
2363                                      new MethodType(List.<Type>of(syms.objectType,
2364                                                             syms.intType,
2365                                                             syms.objectType,
2366                                                             syms.intType,
2367                                                             syms.intType),
2368                                                     syms.voidType,
2369                                                     List.<Type>nil(),
2370                                                     syms.methodClass),
2371                                      syms.systemType.tsym);
2372             }
2373             JCStatement copy =
2374                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2375                                                systemArraycopyMethod),
2376                           List.of(make.Ident(valuesVar), make.Literal(0),
2377                                   make.Ident(resultVar), make.Literal(0),
2378                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
2379 
2380             // template: return $result;
2381             JCStatement ret = make.Return(make.Ident(resultVar));
2382             valuesBody = List.<JCStatement>of(decl, copy, ret);
2383         }
2384 
2385         JCMethodDecl valuesDef =
2386              make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2387 
2388         enumDefs.append(valuesDef);
2389 
2390         if (debugLower)
2391             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2392 
2393         /** The template for the following code is:
2394          *
2395          *     public static E valueOf(String name) {
2396          *         return (E)Enum.valueOf(E.class, name);
2397          *     }
2398          *
2399          *  where E is tree.sym
2400          */
2401         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2402                          names.valueOf,
2403                          tree.sym.type,
2404                          List.of(syms.stringType));
2405         Assert.check((valueOfSym.flags() & STATIC) != 0);
2406         VarSymbol nameArgSym = valueOfSym.params.head;
2407         JCIdent nameVal = make.Ident(nameArgSym);
2408         JCStatement enum_ValueOf =
2409             make.Return(make.TypeCast(tree.sym.type,
2410                                       makeCall(make.Ident(syms.enumSym),
2411                                                names.valueOf,
2412                                                List.of(e_class, nameVal))));
2413         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2414                                            make.Block(0, List.of(enum_ValueOf)));
2415         nameVal.sym = valueOf.params.head.sym;
2416         if (debugLower)
2417             System.err.println(tree.sym + ".valueOf = " + valueOf);
2418         enumDefs.append(valueOf);
2419 
2420         enumDefs.appendList(otherDefs.toList());
2421         tree.defs = enumDefs.toList();
2422 
2423         // Add the necessary members for the EnumCompatibleMode
2424         if (target.compilerBootstrap(tree.sym)) {
2425             addEnumCompatibleMembers(tree);
2426         }
2427     }
2428         // where
2429         private MethodSymbol systemArraycopyMethod;
2430         private boolean useClone() {
2431             try {
2432                 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
2433                 return (e.sym != null);
2434             }
2435             catch (CompletionFailure e) {
2436                 return false;
2437             }
2438         }
2439 
2440     /** Translate an enumeration constant and its initializer. */
2441     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2442         JCNewClass varDef = (JCNewClass)var.init;
2443         varDef.args = varDef.args.
2444             prepend(makeLit(syms.intType, ordinal)).
2445             prepend(makeLit(syms.stringType, var.name.toString()));
2446     }
2447 
2448     public void visitMethodDef(JCMethodDecl tree) {
2449         if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2450             // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2451             // argument list for each constructor of an enum.
2452             JCVariableDecl nameParam = make_at(tree.pos()).
2453                 Param(names.fromString(target.syntheticNameChar() +
2454                                        "enum" + target.syntheticNameChar() + "name"),
2455                       syms.stringType, tree.sym);
2456             nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2457 
2458             JCVariableDecl ordParam = make.
2459                 Param(names.fromString(target.syntheticNameChar() +
2460                                        "enum" + target.syntheticNameChar() +
2461                                        "ordinal"),
2462                       syms.intType, tree.sym);
2463             ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2464 
2465             tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2466 
2467             MethodSymbol m = tree.sym;
2468             Type olderasure = m.erasure(types);
2469             m.erasure_field = new MethodType(
2470                 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2471                 olderasure.getReturnType(),
2472                 olderasure.getThrownTypes(),
2473                 syms.methodClass);
2474 
2475             if (target.compilerBootstrap(m.owner)) {
2476                 // Initialize synthetic name field
2477                 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
2478                                                     tree.sym.owner.members());
2479                 JCIdent nameIdent = make.Ident(nameParam.sym);
2480                 JCIdent id1 = make.Ident(nameVarSym);
2481                 JCAssign newAssign = make.Assign(id1, nameIdent);
2482                 newAssign.type = id1.type;
2483                 JCExpressionStatement nameAssign = make.Exec(newAssign);
2484                 nameAssign.type = id1.type;
2485                 tree.body.stats = tree.body.stats.prepend(nameAssign);
2486 
2487                 // Initialize synthetic ordinal field
2488                 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
2489                                                        tree.sym.owner.members());
2490                 JCIdent ordIdent = make.Ident(ordParam.sym);
2491                 id1 = make.Ident(ordinalVarSym);
2492                 newAssign = make.Assign(id1, ordIdent);
2493                 newAssign.type = id1.type;
2494                 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
2495                 ordinalAssign.type = id1.type;
2496                 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
2497             }
2498         }
2499 
2500         JCMethodDecl prevMethodDef = currentMethodDef;
2501         MethodSymbol prevMethodSym = currentMethodSym;
2502         try {
2503             currentMethodDef = tree;
2504             currentMethodSym = tree.sym;
2505             visitMethodDefInternal(tree);
2506         } finally {
2507             currentMethodDef = prevMethodDef;
2508             currentMethodSym = prevMethodSym;
2509         }
2510     }
2511     //where
2512     private void visitMethodDefInternal(JCMethodDecl tree) {
2513         if (tree.name == names.init &&
2514             (currentClass.isInner() ||
2515              (currentClass.owner.kind & (VAR | MTH)) != 0)) {
2516             // We are seeing a constructor of an inner class.
2517             MethodSymbol m = tree.sym;
2518 
2519             // Push a new proxy scope for constructor parameters.
2520             // and create definitions for any this$n and proxy parameters.
2521             proxies = proxies.dup(m);
2522             List<VarSymbol> prevOuterThisStack = outerThisStack;
2523             List<VarSymbol> fvs = freevars(currentClass);
2524             JCVariableDecl otdef = null;
2525             if (currentClass.hasOuterInstance())
2526                 otdef = outerThisDef(tree.pos, m);
2527             List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
2528 
2529             // Recursively translate result type, parameters and thrown list.
2530             tree.restype = translate(tree.restype);
2531             tree.params = translateVarDefs(tree.params);
2532             tree.thrown = translate(tree.thrown);
2533 
2534             // when compiling stubs, don't process body
2535             if (tree.body == null) {
2536                 result = tree;
2537                 return;
2538             }
2539 
2540             // Add this$n (if needed) in front of and free variables behind
2541             // constructor parameter list.
2542             tree.params = tree.params.appendList(fvdefs);
2543             if (currentClass.hasOuterInstance())
2544                 tree.params = tree.params.prepend(otdef);
2545 
2546             // If this is an initial constructor, i.e., it does not start with
2547             // this(...), insert initializers for this$n and proxies
2548             // before (pre-1.4, after) the call to superclass constructor.
2549             JCStatement selfCall = translate(tree.body.stats.head);
2550 
2551             List<JCStatement> added = List.nil();
2552             if (fvs.nonEmpty()) {
2553                 List<Type> addedargtypes = List.nil();
2554                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2555                     if (TreeInfo.isInitialConstructor(tree))
2556                         added = added.prepend(
2557                             initField(tree.body.pos, proxyName(l.head.name)));
2558                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2559                 }
2560                 Type olderasure = m.erasure(types);
2561                 m.erasure_field = new MethodType(
2562                     olderasure.getParameterTypes().appendList(addedargtypes),
2563                     olderasure.getReturnType(),
2564                     olderasure.getThrownTypes(),
2565                     syms.methodClass);
2566             }
2567             if (currentClass.hasOuterInstance() &&
2568                 TreeInfo.isInitialConstructor(tree))
2569             {
2570                 added = added.prepend(initOuterThis(tree.body.pos));
2571             }
2572 
2573             // pop local variables from proxy stack
2574             proxies = proxies.leave();
2575 
2576             // recursively translate following local statements and
2577             // combine with this- or super-call
2578             List<JCStatement> stats = translate(tree.body.stats.tail);
2579             if (target.initializeFieldsBeforeSuper())
2580                 tree.body.stats = stats.prepend(selfCall).prependList(added);
2581             else
2582                 tree.body.stats = stats.prependList(added).prepend(selfCall);
2583 
2584             outerThisStack = prevOuterThisStack;
2585         } else {
2586             super.visitMethodDef(tree);
2587         }
2588         result = tree;
2589     }
2590 
2591     public void visitTypeCast(JCTypeCast tree) {
2592         tree.clazz = translate(tree.clazz);
2593         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2594             tree.expr = translate(tree.expr, tree.type);
2595         else
2596             tree.expr = translate(tree.expr);
2597         result = tree;
2598     }
2599 
2600     public void visitNewClass(JCNewClass tree) {
2601         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2602 
2603         // Box arguments, if necessary
2604         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2605         List<Type> argTypes = tree.constructor.type.getParameterTypes();
2606         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2607         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2608         tree.varargsElement = null;
2609 
2610         // If created class is local, add free variables after
2611         // explicit constructor arguments.
2612         if ((c.owner.kind & (VAR | MTH)) != 0) {
2613             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2614         }
2615 
2616         // If an access constructor is used, append null as a last argument.
2617         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2618         if (constructor != tree.constructor) {
2619             tree.args = tree.args.append(makeNull());
2620             tree.constructor = constructor;
2621         }
2622 
2623         // If created class has an outer instance, and new is qualified, pass
2624         // qualifier as first argument. If new is not qualified, pass the
2625         // correct outer instance as first argument.
2626         if (c.hasOuterInstance()) {
2627             JCExpression thisArg;
2628             if (tree.encl != null) {
2629                 thisArg = attr.makeNullCheck(translate(tree.encl));
2630                 thisArg.type = tree.encl.type;
2631             } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2632                 // local class
2633                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2634             } else {
2635                 // nested class
2636                 thisArg = makeOwnerThis(tree.pos(), c, false);
2637             }
2638             tree.args = tree.args.prepend(thisArg);
2639         }
2640         tree.encl = null;
2641 
2642         // If we have an anonymous class, create its flat version, rather
2643         // than the class or interface following new.
2644         if (tree.def != null) {
2645             translate(tree.def);
2646             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2647             tree.def = null;
2648         } else {
2649             tree.clazz = access(c, tree.clazz, enclOp, false);
2650         }
2651         result = tree;
2652     }
2653 
2654     // Simplify conditionals with known constant controlling expressions.
2655     // This allows us to avoid generating supporting declarations for
2656     // the dead code, which will not be eliminated during code generation.
2657     // Note that Flow.isFalse and Flow.isTrue only return true
2658     // for constant expressions in the sense of JLS 15.27, which
2659     // are guaranteed to have no side-effects.  More aggressive
2660     // constant propagation would require that we take care to
2661     // preserve possible side-effects in the condition expression.
2662 
2663     /** Visitor method for conditional expressions.
2664      */
2665     public void visitConditional(JCConditional tree) {
2666         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2667         if (cond.type.isTrue()) {
2668             result = convert(translate(tree.truepart, tree.type), tree.type);
2669         } else if (cond.type.isFalse()) {
2670             result = convert(translate(tree.falsepart, tree.type), tree.type);
2671         } else {
2672             // Condition is not a compile-time constant.
2673             tree.truepart = translate(tree.truepart, tree.type);
2674             tree.falsepart = translate(tree.falsepart, tree.type);
2675             result = tree;
2676         }
2677     }
2678 //where
2679         private JCTree convert(JCTree tree, Type pt) {
2680             if (tree.type == pt || tree.type.tag == TypeTags.BOT)
2681                 return tree;
2682             JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2683             result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2684                                                            : pt;
2685             return result;
2686         }
2687 
2688     /** Visitor method for if statements.
2689      */
2690     public void visitIf(JCIf tree) {
2691         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2692         if (cond.type.isTrue()) {
2693             result = translate(tree.thenpart);
2694         } else if (cond.type.isFalse()) {
2695             if (tree.elsepart != null) {
2696                 result = translate(tree.elsepart);
2697             } else {
2698                 result = make.Skip();
2699             }
2700         } else {
2701             // Condition is not a compile-time constant.
2702             tree.thenpart = translate(tree.thenpart);
2703             tree.elsepart = translate(tree.elsepart);
2704             result = tree;
2705         }
2706     }
2707 
2708     /** Visitor method for assert statements. Translate them away.
2709      */
2710     public void visitAssert(JCAssert tree) {
2711         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2712         tree.cond = translate(tree.cond, syms.booleanType);
2713         if (!tree.cond.type.isTrue()) {
2714             JCExpression cond = assertFlagTest(tree.pos());
2715             List<JCExpression> exnArgs = (tree.detail == null) ?
2716                 List.<JCExpression>nil() : List.of(translate(tree.detail));
2717             if (!tree.cond.type.isFalse()) {
2718                 cond = makeBinary
2719                     (JCTree.AND,
2720                      cond,
2721                      makeUnary(JCTree.NOT, tree.cond));
2722             }
2723             result =
2724                 make.If(cond,
2725                         make_at(detailPos).
2726                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2727                         null);
2728         } else {
2729             result = make.Skip();
2730         }
2731     }
2732 
2733     public void visitApply(JCMethodInvocation tree) {
2734         Symbol meth = TreeInfo.symbol(tree.meth);
2735         List<Type> argtypes = meth.type.getParameterTypes();
2736         if (allowEnums &&
2737             meth.name==names.init &&
2738             meth.owner == syms.enumSym)
2739             argtypes = argtypes.tail.tail;
2740         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2741         tree.varargsElement = null;
2742         Name methName = TreeInfo.name(tree.meth);
2743         if (meth.name==names.init) {
2744             // We are seeing a this(...) or super(...) constructor call.
2745             // If an access constructor is used, append null as a last argument.
2746             Symbol constructor = accessConstructor(tree.pos(), meth);
2747             if (constructor != meth) {
2748                 tree.args = tree.args.append(makeNull());
2749                 TreeInfo.setSymbol(tree.meth, constructor);
2750             }
2751 
2752             // If we are calling a constructor of a local class, add
2753             // free variables after explicit constructor arguments.
2754             ClassSymbol c = (ClassSymbol)constructor.owner;
2755             if ((c.owner.kind & (VAR | MTH)) != 0) {
2756                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2757             }
2758 
2759             // If we are calling a constructor of an enum class, pass
2760             // along the name and ordinal arguments
2761             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2762                 List<JCVariableDecl> params = currentMethodDef.params;
2763                 if (currentMethodSym.owner.hasOuterInstance())
2764                     params = params.tail; // drop this$n
2765                 tree.args = tree.args
2766                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2767                     .prepend(make.Ident(params.head.sym)); // name
2768             }
2769 
2770             // If we are calling a constructor of a class with an outer
2771             // instance, and the call
2772             // is qualified, pass qualifier as first argument in front of
2773             // the explicit constructor arguments. If the call
2774             // is not qualified, pass the correct outer instance as
2775             // first argument.
2776             if (c.hasOuterInstance()) {
2777                 JCExpression thisArg;
2778                 if (tree.meth.getTag() == JCTree.SELECT) {
2779                     thisArg = attr.
2780                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2781                     tree.meth = make.Ident(constructor);
2782                     ((JCIdent) tree.meth).name = methName;
2783                 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2784                     // local class or this() call
2785                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2786                 } else {
2787                     // super() call of nested class
2788                     thisArg = makeOwnerThis(tree.meth.pos(), c, false);
2789                 }
2790                 tree.args = tree.args.prepend(thisArg);
2791             }
2792         } else {
2793             // We are seeing a normal method invocation; translate this as usual.
2794             tree.meth = translate(tree.meth);
2795 
2796             // If the translated method itself is an Apply tree, we are
2797             // seeing an access method invocation. In this case, append
2798             // the method arguments to the arguments of the access method.
2799             if (tree.meth.getTag() == JCTree.APPLY) {
2800                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
2801                 app.args = tree.args.prependList(app.args);
2802                 result = app;
2803                 return;
2804             }
2805         }
2806         result = tree;
2807     }
2808 
2809     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
2810         List<JCExpression> args = _args;
2811         if (parameters.isEmpty()) return args;
2812         boolean anyChanges = false;
2813         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
2814         while (parameters.tail.nonEmpty()) {
2815             JCExpression arg = translate(args.head, parameters.head);
2816             anyChanges |= (arg != args.head);
2817             result.append(arg);
2818             args = args.tail;
2819             parameters = parameters.tail;
2820         }
2821         Type parameter = parameters.head;
2822         if (varargsElement != null) {
2823             anyChanges = true;
2824             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
2825             while (args.nonEmpty()) {
2826                 JCExpression arg = translate(args.head, varargsElement);
2827                 elems.append(arg);
2828                 args = args.tail;
2829             }
2830             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
2831                                                List.<JCExpression>nil(),
2832                                                elems.toList());
2833             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
2834             result.append(boxedArgs);
2835         } else {
2836             if (args.length() != 1) throw new AssertionError(args);
2837             JCExpression arg = translate(args.head, parameter);
2838             anyChanges |= (arg != args.head);
2839             result.append(arg);
2840             if (!anyChanges) return _args;
2841         }
2842         return result.toList();
2843     }
2844 
2845     /** Expand a boxing or unboxing conversion if needed. */
2846     @SuppressWarnings("unchecked") // XXX unchecked
2847     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
2848         boolean havePrimitive = tree.type.isPrimitive();
2849         if (havePrimitive == type.isPrimitive())
2850             return tree;
2851         if (havePrimitive) {
2852             Type unboxedTarget = types.unboxedType(type);
2853             if (unboxedTarget.tag != NONE) {
2854                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
2855                     tree.type = unboxedTarget.constType(tree.type.constValue());
2856                 return (T)boxPrimitive((JCExpression)tree, type);
2857             } else {
2858                 tree = (T)boxPrimitive((JCExpression)tree);
2859             }
2860         } else {
2861             tree = (T)unbox((JCExpression)tree, type);
2862         }
2863         return tree;
2864     }
2865 
2866     /** Box up a single primitive expression. */
2867     JCExpression boxPrimitive(JCExpression tree) {
2868         return boxPrimitive(tree, types.boxedClass(tree.type).type);
2869     }
2870 
2871     /** Box up a single primitive expression. */
2872     JCExpression boxPrimitive(JCExpression tree, Type box) {
2873         make_at(tree.pos());
2874         if (target.boxWithConstructors()) {
2875             Symbol ctor = lookupConstructor(tree.pos(),
2876                                             box,
2877                                             List.<Type>nil()
2878                                             .prepend(tree.type));
2879             return make.Create(ctor, List.of(tree));
2880         } else {
2881             Symbol valueOfSym = lookupMethod(tree.pos(),
2882                                              names.valueOf,
2883                                              box,
2884                                              List.<Type>nil()
2885                                              .prepend(tree.type));
2886             return make.App(make.QualIdent(valueOfSym), List.of(tree));
2887         }
2888     }
2889 
2890     /** Unbox an object to a primitive value. */
2891     JCExpression unbox(JCExpression tree, Type primitive) {
2892         Type unboxedType = types.unboxedType(tree.type);
2893         if (unboxedType.tag == NONE) {
2894             unboxedType = primitive;
2895             if (!unboxedType.isPrimitive())
2896                 throw new AssertionError(unboxedType);
2897             make_at(tree.pos());
2898             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
2899         } else {
2900             // There must be a conversion from unboxedType to primitive.
2901             if (!types.isSubtype(unboxedType, primitive))
2902                 throw new AssertionError(tree);
2903         }
2904         make_at(tree.pos());
2905         Symbol valueSym = lookupMethod(tree.pos(),
2906                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
2907                                        tree.type,
2908                                        List.<Type>nil());
2909         return make.App(make.Select(tree, valueSym));
2910     }
2911 
2912     /** Visitor method for parenthesized expressions.
2913      *  If the subexpression has changed, omit the parens.
2914      */
2915     public void visitParens(JCParens tree) {
2916         JCTree expr = translate(tree.expr);
2917         result = ((expr == tree.expr) ? tree : expr);
2918     }
2919 
2920     public void visitIndexed(JCArrayAccess tree) {
2921         tree.indexed = translate(tree.indexed);
2922         tree.index = translate(tree.index, syms.intType);
2923         result = tree;
2924     }
2925 
2926     public void visitAssign(JCAssign tree) {
2927         tree.lhs = translate(tree.lhs, tree);
2928         tree.rhs = translate(tree.rhs, tree.lhs.type);
2929 
2930         // If translated left hand side is an Apply, we are
2931         // seeing an access method invocation. In this case, append
2932         // right hand side as last argument of the access method.
2933         if (tree.lhs.getTag() == JCTree.APPLY) {
2934             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2935             app.args = List.of(tree.rhs).prependList(app.args);
2936             result = app;
2937         } else {
2938             result = tree;
2939         }
2940     }
2941 
2942     public void visitAssignop(final JCAssignOp tree) {
2943         if (!tree.lhs.type.isPrimitive() &&
2944             tree.operator.type.getReturnType().isPrimitive()) {
2945             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
2946             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
2947             // (but without recomputing x)
2948             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
2949                     public JCTree build(final JCTree lhs) {
2950                         int newTag = tree.getTag() - JCTree.ASGOffset;
2951                         // Erasure (TransTypes) can change the type of
2952                         // tree.lhs.  However, we can still get the
2953                         // unerased type of tree.lhs as it is stored
2954                         // in tree.type in Attr.
2955                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
2956                                                                       newTag,
2957                                                                       attrEnv,
2958                                                                       tree.type,
2959                                                                       tree.rhs.type);
2960                         JCExpression expr = (JCExpression)lhs;
2961                         if (expr.type != tree.type)
2962                             expr = make.TypeCast(tree.type, expr);
2963                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
2964                         opResult.operator = newOperator;
2965                         opResult.type = newOperator.type.getReturnType();
2966                         JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
2967                                                           opResult);
2968                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
2969                     }
2970                 });
2971             result = translate(newTree);
2972             return;
2973         }
2974         tree.lhs = translate(tree.lhs, tree);
2975         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
2976 
2977         // If translated left hand side is an Apply, we are
2978         // seeing an access method invocation. In this case, append
2979         // right hand side as last argument of the access method.
2980         if (tree.lhs.getTag() == JCTree.APPLY) {
2981             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2982             // if operation is a += on strings,
2983             // make sure to convert argument to string
2984             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
2985               ? makeString(tree.rhs)
2986               : tree.rhs;
2987             app.args = List.of(rhs).prependList(app.args);
2988             result = app;
2989         } else {
2990             result = tree;
2991         }
2992     }
2993 
2994     /** Lower a tree of the form e++ or e-- where e is an object type */
2995     JCTree lowerBoxedPostop(final JCUnary tree) {
2996         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
2997         // or
2998         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
2999         // where OP is += or -=
3000         final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
3001         return abstractLval(tree.arg, new TreeBuilder() {
3002                 public JCTree build(final JCTree tmp1) {
3003                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3004                             public JCTree build(final JCTree tmp2) {
3005                                 int opcode = (tree.getTag() == JCTree.POSTINC)
3006                                     ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
3007                                 JCTree lhs = cast
3008                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
3009                                     : tmp1;
3010                                 JCTree update = makeAssignop(opcode,
3011                                                              lhs,
3012                                                              make.Literal(1));
3013                                 return makeComma(update, tmp2);
3014                             }
3015                         });
3016                 }
3017             });
3018     }
3019 
3020     public void visitUnary(JCUnary tree) {
3021         boolean isUpdateOperator =
3022             JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC;
3023         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3024             switch(tree.getTag()) {
3025             case JCTree.PREINC:            // ++ e
3026                     // translate to e += 1
3027             case JCTree.PREDEC:            // -- e
3028                     // translate to e -= 1
3029                 {
3030                     int opcode = (tree.getTag() == JCTree.PREINC)
3031                         ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
3032                     JCAssignOp newTree = makeAssignop(opcode,
3033                                                     tree.arg,
3034                                                     make.Literal(1));
3035                     result = translate(newTree, tree.type);
3036                     return;
3037                 }
3038             case JCTree.POSTINC:           // e ++
3039             case JCTree.POSTDEC:           // e --
3040                 {
3041                     result = translate(lowerBoxedPostop(tree), tree.type);
3042                     return;
3043                 }
3044             }
3045             throw new AssertionError(tree);
3046         }
3047 
3048         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3049 
3050         if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) {
3051             tree.type = cfolder.fold1(bool_not, tree.arg.type);
3052         }
3053 
3054         // If translated left hand side is an Apply, we are
3055         // seeing an access method invocation. In this case, return
3056         // that access method invocation as result.
3057         if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) {
3058             result = tree.arg;
3059         } else {
3060             result = tree;
3061         }
3062     }
3063 
3064     public void visitBinary(JCBinary tree) {
3065         List<Type> formals = tree.operator.type.getParameterTypes();
3066         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3067         switch (tree.getTag()) {
3068         case JCTree.OR:
3069             if (lhs.type.isTrue()) {
3070                 result = lhs;
3071                 return;
3072             }
3073             if (lhs.type.isFalse()) {
3074                 result = translate(tree.rhs, formals.tail.head);
3075                 return;
3076             }
3077             break;
3078         case JCTree.AND:
3079             if (lhs.type.isFalse()) {
3080                 result = lhs;
3081                 return;
3082             }
3083             if (lhs.type.isTrue()) {
3084                 result = translate(tree.rhs, formals.tail.head);
3085                 return;
3086             }
3087             break;
3088         }
3089         tree.rhs = translate(tree.rhs, formals.tail.head);
3090         result = tree;
3091     }
3092 
3093     public void visitIdent(JCIdent tree) {
3094         result = access(tree.sym, tree, enclOp, false);
3095     }
3096 
3097     /** Translate away the foreach loop.  */
3098     public void visitForeachLoop(JCEnhancedForLoop tree) {
3099         if (types.elemtype(tree.expr.type) == null)
3100             visitIterableForeachLoop(tree);
3101         else
3102             visitArrayForeachLoop(tree);
3103     }
3104         // where
3105         /**
3106          * A statement of the form
3107          *
3108          * <pre>
3109          *     for ( T v : arrayexpr ) stmt;
3110          * </pre>
3111          *
3112          * (where arrayexpr is of an array type) gets translated to
3113          *
3114          * <pre>
3115          *     for ( { arraytype #arr = arrayexpr;
3116          *             int #len = array.length;
3117          *             int #i = 0; };
3118          *           #i < #len; i$++ ) {
3119          *         T v = arr$[#i];
3120          *         stmt;
3121          *     }
3122          * </pre>
3123          *
3124          * where #arr, #len, and #i are freshly named synthetic local variables.
3125          */
3126         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3127             make_at(tree.expr.pos());
3128             VarSymbol arraycache = new VarSymbol(0,
3129                                                  names.fromString("arr" + target.syntheticNameChar()),
3130                                                  tree.expr.type,
3131                                                  currentMethodSym);
3132             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3133             VarSymbol lencache = new VarSymbol(0,
3134                                                names.fromString("len" + target.syntheticNameChar()),
3135                                                syms.intType,
3136                                                currentMethodSym);
3137             JCStatement lencachedef = make.
3138                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3139             VarSymbol index = new VarSymbol(0,
3140                                             names.fromString("i" + target.syntheticNameChar()),
3141                                             syms.intType,
3142                                             currentMethodSym);
3143 
3144             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3145             indexdef.init.type = indexdef.type = syms.intType.constType(0);
3146 
3147             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3148             JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache));
3149 
3150             JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index)));
3151 
3152             Type elemtype = types.elemtype(tree.expr.type);
3153             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3154                                                     make.Ident(index)).setType(elemtype);
3155             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3156                                                   tree.var.name,
3157                                                   tree.var.vartype,
3158                                                   loopvarinit).setType(tree.var.type);
3159             loopvardef.sym = tree.var.sym;
3160             JCBlock body = make.
3161                 Block(0, List.of(loopvardef, tree.body));
3162 
3163             result = translate(make.
3164                                ForLoop(loopinit,
3165                                        cond,
3166                                        List.of(step),
3167                                        body));
3168             patchTargets(body, tree, result);
3169         }
3170         /** Patch up break and continue targets. */
3171         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3172             class Patcher extends TreeScanner {
3173                 public void visitBreak(JCBreak tree) {
3174                     if (tree.target == src)
3175                         tree.target = dest;
3176                 }
3177                 public void visitContinue(JCContinue tree) {
3178                     if (tree.target == src)
3179                         tree.target = dest;
3180                 }
3181                 public void visitClassDef(JCClassDecl tree) {}
3182             }
3183             new Patcher().scan(body);
3184         }
3185         /**
3186          * A statement of the form
3187          *
3188          * <pre>
3189          *     for ( T v : coll ) stmt ;
3190          * </pre>
3191          *
3192          * (where coll implements Iterable<? extends T>) gets translated to
3193          *
3194          * <pre>
3195          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3196          *         T v = (T) #i.next();
3197          *         stmt;
3198          *     }
3199          * </pre>
3200          *
3201          * where #i is a freshly named synthetic local variable.
3202          */
3203         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3204             make_at(tree.expr.pos());
3205             Type iteratorTarget = syms.objectType;
3206             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
3207                                               syms.iterableType.tsym);
3208             if (iterableType.getTypeArguments().nonEmpty())
3209                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3210             Type eType = tree.expr.type;
3211             tree.expr.type = types.erasure(eType);
3212             if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
3213                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3214             Symbol iterator = lookupMethod(tree.expr.pos(),
3215                                            names.iterator,
3216                                            types.erasure(syms.iterableType),
3217                                            List.<Type>nil());
3218             VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
3219                                             types.erasure(iterator.type.getReturnType()),
3220                                             currentMethodSym);
3221             JCStatement init = make.
3222                 VarDef(itvar,
3223                        make.App(make.Select(tree.expr, iterator)));
3224             Symbol hasNext = lookupMethod(tree.expr.pos(),
3225                                           names.hasNext,
3226                                           itvar.type,
3227                                           List.<Type>nil());
3228             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3229             Symbol next = lookupMethod(tree.expr.pos(),
3230                                        names.next,
3231                                        itvar.type,
3232                                        List.<Type>nil());
3233             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3234             if (tree.var.type.isPrimitive())
3235                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3236             else
3237                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3238             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3239                                                   tree.var.name,
3240                                                   tree.var.vartype,
3241                                                   vardefinit).setType(tree.var.type);
3242             indexDef.sym = tree.var.sym;
3243             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3244             body.endpos = TreeInfo.endPos(tree.body);
3245             result = translate(make.
3246                 ForLoop(List.of(init),
3247                         cond,
3248                         List.<JCExpressionStatement>nil(),
3249                         body));
3250             patchTargets(body, tree, result);
3251         }
3252 
3253     public void visitVarDef(JCVariableDecl tree) {
3254         MethodSymbol oldMethodSym = currentMethodSym;
3255         tree.mods = translate(tree.mods);
3256         tree.vartype = translate(tree.vartype);
3257         if (currentMethodSym == null) {
3258             // A class or instance field initializer.
3259             currentMethodSym =
3260                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3261                                  names.empty, null,
3262                                  currentClass);
3263         }
3264         if (tree.init != null) tree.init = translate(tree.init, tree.type);
3265         result = tree;
3266         currentMethodSym = oldMethodSym;
3267     }
3268 
3269     public void visitBlock(JCBlock tree) {
3270         MethodSymbol oldMethodSym = currentMethodSym;
3271         if (currentMethodSym == null) {
3272             // Block is a static or instance initializer.
3273             currentMethodSym =
3274                 new MethodSymbol(tree.flags | BLOCK,
3275                                  names.empty, null,
3276                                  currentClass);
3277         }
3278         super.visitBlock(tree);
3279         currentMethodSym = oldMethodSym;
3280     }
3281 
3282     public void visitDoLoop(JCDoWhileLoop tree) {
3283         tree.body = translate(tree.body);
3284         tree.cond = translate(tree.cond, syms.booleanType);
3285         result = tree;
3286     }
3287 
3288     public void visitWhileLoop(JCWhileLoop tree) {
3289         tree.cond = translate(tree.cond, syms.booleanType);
3290         tree.body = translate(tree.body);
3291         result = tree;
3292     }
3293 
3294     public void visitForLoop(JCForLoop tree) {
3295         tree.init = translate(tree.init);
3296         if (tree.cond != null)
3297             tree.cond = translate(tree.cond, syms.booleanType);
3298         tree.step = translate(tree.step);
3299         tree.body = translate(tree.body);
3300         result = tree;
3301     }
3302 
3303     public void visitReturn(JCReturn tree) {
3304         if (tree.expr != null)
3305             tree.expr = translate(tree.expr,
3306                                   types.erasure(currentMethodDef
3307                                                 .restype.type));
3308         result = tree;
3309     }
3310 
3311     public void visitSwitch(JCSwitch tree) {
3312         Type selsuper = types.supertype(tree.selector.type);
3313         boolean enumSwitch = selsuper != null &&
3314             (tree.selector.type.tsym.flags() & ENUM) != 0;
3315         boolean stringSwitch = selsuper != null &&
3316             types.isSameType(tree.selector.type, syms.stringType);
3317         Type target = enumSwitch ? tree.selector.type :
3318             (stringSwitch? syms.stringType : syms.intType);
3319         tree.selector = translate(tree.selector, target);
3320         tree.cases = translateCases(tree.cases);
3321         if (enumSwitch) {
3322             result = visitEnumSwitch(tree);
3323         } else if (stringSwitch) {
3324             result = visitStringSwitch(tree);
3325         } else {
3326             result = tree;
3327         }
3328     }
3329 
3330     public JCTree visitEnumSwitch(JCSwitch tree) {
3331         TypeSymbol enumSym = tree.selector.type.tsym;
3332         EnumMapping map = mapForEnum(tree.pos(), enumSym);
3333         make_at(tree.pos());
3334         Symbol ordinalMethod = lookupMethod(tree.pos(),
3335                                             names.ordinal,
3336                                             tree.selector.type,
3337                                             List.<Type>nil());
3338         JCArrayAccess selector = make.Indexed(map.mapVar,
3339                                         make.App(make.Select(tree.selector,
3340                                                              ordinalMethod)));
3341         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3342         for (JCCase c : tree.cases) {
3343             if (c.pat != null) {
3344                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3345                 JCLiteral pat = map.forConstant(label);
3346                 cases.append(make.Case(pat, c.stats));
3347             } else {
3348                 cases.append(c);
3349             }
3350         }
3351         JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3352         patchTargets(enumSwitch, tree, enumSwitch);
3353         return enumSwitch;
3354     }
3355 
3356     public JCTree visitStringSwitch(JCSwitch tree) {
3357         List<JCCase> caseList = tree.getCases();
3358         int alternatives = caseList.size();
3359 
3360         if (alternatives == 0) { // Strange but legal possibility
3361             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3362         } else {
3363             /*
3364              * The general approach used is to translate a single
3365              * string switch statement into a series of two chained
3366              * switch statements: the first a synthesized statement
3367              * switching on the argument string's hash value and
3368              * computing a string's position in the list of original
3369              * case labels, if any, followed by a second switch on the
3370              * computed integer value.  The second switch has the same
3371              * code structure as the original string switch statement
3372              * except that the string case labels are replaced with
3373              * positional integer constants starting at 0.
3374              *
3375              * The first switch statement can be thought of as an
3376              * inlined map from strings to their position in the case
3377              * label list.  An alternate implementation would use an
3378              * actual Map for this purpose, as done for enum switches.
3379              *
3380              * With some additional effort, it would be possible to
3381              * use a single switch statement on the hash code of the
3382              * argument, but care would need to be taken to preserve
3383              * the proper control flow in the presence of hash
3384              * collisions and other complications, such as
3385              * fallthroughs.  Switch statements with one or two
3386              * alternatives could also be specially translated into
3387              * if-then statements to omit the computation of the hash
3388              * code.
3389              *
3390              * The generated code assumes that the hashing algorithm
3391              * of String is the same in the compilation environment as
3392              * in the environment the code will run in.  The string
3393              * hashing algorithm in the SE JDK has been unchanged
3394              * since at least JDK 1.2.  Since the algorithm has been
3395              * specified since that release as well, it is very
3396              * unlikely to be changed in the future.
3397              *
3398              * Different hashing algorithms, such as the length of the
3399              * strings or a perfect hashing algorithm over the
3400              * particular set of case labels, could potentially be
3401              * used instead of String.hashCode.
3402              */
3403 
3404             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
3405 
3406             // Map from String case labels to their original position in
3407             // the list of case labels.
3408             Map<String, Integer> caseLabelToPosition =
3409                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
3410 
3411             // Map of hash codes to the string case labels having that hashCode.
3412             Map<Integer, Set<String>> hashToString =
3413                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
3414 
3415             int casePosition = 0;
3416             for(JCCase oneCase : caseList) {
3417                 JCExpression expression = oneCase.getExpression();
3418 
3419                 if (expression != null) { // expression for a "default" case is null
3420                     String labelExpr = (String) expression.type.constValue();
3421                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3422                     Assert.checkNull(mapping);
3423                     int hashCode = labelExpr.hashCode();
3424 
3425                     Set<String> stringSet = hashToString.get(hashCode);
3426                     if (stringSet == null) {
3427                         stringSet = new LinkedHashSet<String>(1, 1.0f);
3428                         stringSet.add(labelExpr);
3429                         hashToString.put(hashCode, stringSet);
3430                     } else {
3431                         boolean added = stringSet.add(labelExpr);
3432                         Assert.check(added);
3433                     }
3434                 }
3435                 casePosition++;
3436             }
3437 
3438             // Synthesize a switch statement that has the effect of
3439             // mapping from a string to the integer position of that
3440             // string in the list of case labels.  This is done by
3441             // switching on the hashCode of the string followed by an
3442             // if-then-else chain comparing the input for equality
3443             // with all the case labels having that hash value.
3444 
3445             /*
3446              * s$ = top of stack;
3447              * tmp$ = -1;
3448              * switch($s.hashCode()) {
3449              *     case caseLabel.hashCode:
3450              *         if (s$.equals("caseLabel_1")
3451              *           tmp$ = caseLabelToPosition("caseLabel_1");
3452              *         else if (s$.equals("caseLabel_2"))
3453              *           tmp$ = caseLabelToPosition("caseLabel_2");
3454              *         ...
3455              *         break;
3456              * ...
3457              * }
3458              */
3459 
3460             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3461                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
3462                                                syms.stringType,
3463                                                currentMethodSym);
3464             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3465 
3466             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3467                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3468                                                  syms.intType,
3469                                                  currentMethodSym);
3470             JCVariableDecl dollar_tmp_def =
3471                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3472             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3473             stmtList.append(dollar_tmp_def);
3474             ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
3475             // hashCode will trigger nullcheck on original switch expression
3476             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3477                                                        names.hashCode,
3478                                                        List.<JCExpression>nil()).setType(syms.intType);
3479             JCSwitch switch1 = make.Switch(hashCodeCall,
3480                                         caseBuffer.toList());
3481             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3482                 int hashCode = entry.getKey();
3483                 Set<String> stringsWithHashCode = entry.getValue();
3484                 Assert.check(stringsWithHashCode.size() >= 1);
3485 
3486                 JCStatement elsepart = null;
3487                 for(String caseLabel : stringsWithHashCode ) {
3488                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3489                                                                    names.equals,
3490                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
3491                     elsepart = make.If(stringEqualsCall,
3492                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
3493                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
3494                                                  setType(dollar_tmp.type)),
3495                                        elsepart);
3496                 }
3497 
3498                 ListBuffer<JCStatement> lb = ListBuffer.lb();
3499                 JCBreak breakStmt = make.Break(null);
3500                 breakStmt.target = switch1;
3501                 lb.append(elsepart).append(breakStmt);
3502 
3503                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3504             }
3505 
3506             switch1.cases = caseBuffer.toList();
3507             stmtList.append(switch1);
3508 
3509             // Make isomorphic switch tree replacing string labels
3510             // with corresponding integer ones from the label to
3511             // position map.
3512 
3513             ListBuffer<JCCase> lb = ListBuffer.lb();
3514             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3515             for(JCCase oneCase : caseList ) {
3516                 // Rewire up old unlabeled break statements to the
3517                 // replacement switch being created.
3518                 patchTargets(oneCase, tree, switch2);
3519 
3520                 boolean isDefault = (oneCase.getExpression() == null);
3521                 JCExpression caseExpr;
3522                 if (isDefault)
3523                     caseExpr = null;
3524                 else {
3525                     caseExpr = make.Literal(caseLabelToPosition.get((String)oneCase.
3526                                                                     getExpression().
3527                                                                     type.constValue()));
3528                 }
3529 
3530                 lb.append(make.Case(caseExpr,
3531                                     oneCase.getStatements()));
3532             }
3533 
3534             switch2.cases = lb.toList();
3535             stmtList.append(switch2);
3536 
3537             return make.Block(0L, stmtList.toList());
3538         }
3539     }
3540 
3541     public void visitNewArray(JCNewArray tree) {
3542         tree.elemtype = translate(tree.elemtype);
3543         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3544             if (t.head != null) t.head = translate(t.head, syms.intType);
3545         tree.elems = translate(tree.elems, types.elemtype(tree.type));
3546         result = tree;
3547     }
3548 
3549     public void visitSelect(JCFieldAccess tree) {
3550         // need to special case-access of the form C.super.x
3551         // these will always need an access method.
3552         boolean qualifiedSuperAccess =
3553             tree.selected.getTag() == JCTree.SELECT &&
3554             TreeInfo.name(tree.selected) == names._super;
3555         tree.selected = translate(tree.selected);
3556         if (tree.name == names._class)
3557             result = classOf(tree.selected);
3558         else if (tree.name == names._this || tree.name == names._super)
3559             result = makeThis(tree.pos(), tree.selected.type.tsym);
3560         else
3561             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3562     }
3563 
3564     public void visitLetExpr(LetExpr tree) {
3565         tree.defs = translateVarDefs(tree.defs);
3566         tree.expr = translate(tree.expr, tree.type);
3567         result = tree;
3568     }
3569 
3570     // There ought to be nothing to rewrite here;
3571     // we don't generate code.
3572     public void visitAnnotation(JCAnnotation tree) {
3573         result = tree;
3574     }
3575 
3576     @Override
3577     public void visitTry(JCTry tree) {
3578         if (tree.resources.isEmpty()) {
3579             super.visitTry(tree);
3580         } else {
3581             result = makeArmTry(tree);
3582         }
3583     }
3584 
3585 /**************************************************************************
3586  * main method
3587  *************************************************************************/
3588 
3589     /** Translate a toplevel class and return a list consisting of
3590      *  the translated class and translated versions of all inner classes.
3591      *  @param env   The attribution environment current at the class definition.
3592      *               We need this for resolving some additional symbols.
3593      *  @param cdef  The tree representing the class definition.
3594      */
3595     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3596         ListBuffer<JCTree> translated = null;
3597         try {
3598             attrEnv = env;
3599             this.make = make;
3600             endPositions = env.toplevel.endPositions;
3601             currentClass = null;
3602             currentMethodDef = null;
3603             outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null;
3604             outermostMemberDef = null;
3605             this.translated = new ListBuffer<JCTree>();
3606             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3607             actualSymbols = new HashMap<Symbol,Symbol>();
3608             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3609             proxies = new Scope(syms.noSymbol);
3610             twrVars = new Scope(syms.noSymbol);
3611             outerThisStack = List.nil();
3612             accessNums = new HashMap<Symbol,Integer>();
3613             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3614             accessConstrs = new HashMap<Symbol,MethodSymbol>();
3615             accessConstrTags = List.nil();
3616             accessed = new ListBuffer<Symbol>();
3617             translate(cdef, (JCExpression)null);
3618             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3619                 makeAccessible(l.head);
3620             for (EnumMapping map : enumSwitchMap.values())
3621                 map.translate();
3622             checkConflicts(this.translated.toList());
3623             checkAccessConstructorTags();
3624             translated = this.translated;
3625         } finally {
3626             // note that recursive invocations of this method fail hard
3627             attrEnv = null;
3628             this.make = null;
3629             endPositions = null;
3630             currentClass = null;
3631             currentMethodDef = null;
3632             outermostClassDef = null;
3633             outermostMemberDef = null;
3634             this.translated = null;
3635             classdefs = null;
3636             actualSymbols = null;
3637             freevarCache = null;
3638             proxies = null;
3639             outerThisStack = null;
3640             accessNums = null;
3641             accessSyms = null;
3642             accessConstrs = null;
3643             accessConstrTags = null;
3644             accessed = null;
3645             enumSwitchMap.clear();
3646         }
3647         return translated.toList();
3648     }
3649 
3650     //////////////////////////////////////////////////////////////
3651     // The following contributed by Borland for bootstrapping purposes
3652     //////////////////////////////////////////////////////////////
3653     private void addEnumCompatibleMembers(JCClassDecl cdef) {
3654         make_at(null);
3655 
3656         // Add the special enum fields
3657         VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
3658         VarSymbol nameFieldSym = addEnumNameField(cdef);
3659 
3660         // Add the accessor methods for name and ordinal
3661         MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
3662         MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
3663 
3664         // Add the toString method
3665         addEnumToString(cdef, nameFieldSym);
3666 
3667         // Add the compareTo method
3668         addEnumCompareTo(cdef, ordinalFieldSym);
3669     }
3670 
3671     private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
3672         VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3673                                           names.fromString("$ordinal"),
3674                                           syms.intType,
3675                                           cdef.sym);
3676         cdef.sym.members().enter(ordinal);
3677         cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
3678         return ordinal;
3679     }
3680 
3681     private VarSymbol addEnumNameField(JCClassDecl cdef) {
3682         VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3683                                           names.fromString("$name"),
3684                                           syms.stringType,
3685                                           cdef.sym);
3686         cdef.sym.members().enter(name);
3687         cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
3688         return name;
3689     }
3690 
3691     private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3692         // Add the accessor methods for ordinal
3693         Symbol ordinalSym = lookupMethod(cdef.pos(),
3694                                          names.ordinal,
3695                                          cdef.type,
3696                                          List.<Type>nil());
3697 
3698         Assert.check(ordinalSym instanceof MethodSymbol);
3699 
3700         JCStatement ret = make.Return(make.Ident(ordinalSymbol));
3701         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
3702                                                     make.Block(0L, List.of(ret))));
3703 
3704         return (MethodSymbol)ordinalSym;
3705     }
3706 
3707     private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
3708         // Add the accessor methods for name
3709         Symbol nameSym = lookupMethod(cdef.pos(),
3710                                    names._name,
3711                                    cdef.type,
3712                                    List.<Type>nil());
3713 
3714         Assert.check(nameSym instanceof MethodSymbol);
3715 
3716         JCStatement ret = make.Return(make.Ident(nameSymbol));
3717 
3718         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
3719                                                     make.Block(0L, List.of(ret))));
3720 
3721         return (MethodSymbol)nameSym;
3722     }
3723 
3724     private MethodSymbol addEnumToString(JCClassDecl cdef,
3725                                          VarSymbol nameSymbol) {
3726         Symbol toStringSym = lookupMethod(cdef.pos(),
3727                                           names.toString,
3728                                           cdef.type,
3729                                           List.<Type>nil());
3730 
3731         JCTree toStringDecl = null;
3732         if (toStringSym != null)
3733             toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
3734 
3735         if (toStringDecl != null)
3736             return (MethodSymbol)toStringSym;
3737 
3738         JCStatement ret = make.Return(make.Ident(nameSymbol));
3739 
3740         JCTree resTypeTree = make.Type(syms.stringType);
3741 
3742         MethodType toStringType = new MethodType(List.<Type>nil(),
3743                                                  syms.stringType,
3744                                                  List.<Type>nil(),
3745                                                  cdef.sym);
3746         toStringSym = new MethodSymbol(PUBLIC,
3747                                        names.toString,
3748                                        toStringType,
3749                                        cdef.type.tsym);
3750         toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
3751                                       make.Block(0L, List.of(ret)));
3752 
3753         cdef.defs = cdef.defs.prepend(toStringDecl);
3754         cdef.sym.members().enter(toStringSym);
3755 
3756         return (MethodSymbol)toStringSym;
3757     }
3758 
3759     private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3760         Symbol compareToSym = lookupMethod(cdef.pos(),
3761                                    names.compareTo,
3762                                    cdef.type,
3763                                    List.of(cdef.sym.type));
3764 
3765         Assert.check(compareToSym instanceof MethodSymbol);
3766 
3767         JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
3768 
3769         ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
3770 
3771         JCModifiers mod1 = make.Modifiers(0L);
3772         Name oName = names.fromString("o");
3773         JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
3774 
3775         JCIdent paramId1 = make.Ident(names.java_lang_Object);
3776         paramId1.type = cdef.type;
3777         paramId1.sym = par1.sym;
3778 
3779         ((MethodSymbol)compareToSym).params = List.of(par1.sym);
3780 
3781         JCIdent par1UsageId = make.Ident(par1.sym);
3782         JCIdent castTargetIdent = make.Ident(cdef.sym);
3783         JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
3784         cast.setType(castTargetIdent.type);
3785 
3786         Name otherName = names.fromString("other");
3787 
3788         VarSymbol otherVarSym = new VarSymbol(mod1.flags,
3789                                               otherName,
3790                                               cdef.type,
3791                                               compareToSym);
3792         JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
3793         blockStatements.append(otherVar);
3794 
3795         JCIdent id1 = make.Ident(ordinalSymbol);
3796 
3797         JCIdent fLocUsageId = make.Ident(otherVarSym);
3798         JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
3799         JCBinary bin = makeBinary(JCTree.MINUS, id1, sel);
3800         JCReturn ret = make.Return(bin);
3801         blockStatements.append(ret);
3802         JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
3803                                                    make.Block(0L,
3804                                                               blockStatements.toList()));
3805         compareToMethod.params = List.of(par1);
3806         cdef.defs = cdef.defs.append(compareToMethod);
3807 
3808         return (MethodSymbol)compareToSym;
3809     }
3810     //////////////////////////////////////////////////////////////
3811     // The above contributed by Borland for bootstrapping purposes
3812     //////////////////////////////////////////////////////////////
3813 }