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