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