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