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                         added = added.prepend(
2716                             initField(tree.body.pos, proxyName(l.head.name)));
2717                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2718                 }
2719                 Type olderasure = m.erasure(types);
2720                 m.erasure_field = new MethodType(
2721                     olderasure.getParameterTypes().appendList(addedargtypes),
2722                     olderasure.getReturnType(),
2723                     olderasure.getThrownTypes(),
2724                     syms.methodClass);
2725             }
2726             if (currentClass.hasOuterInstance() &&
2727                 TreeInfo.isInitialConstructor(tree))
2728             {
2729                 added = added.prepend(initOuterThis(tree.body.pos));
2730             }
2731 
2732             // pop local variables from proxy stack
2733             proxies = proxies.leave();
2734 
2735             // recursively translate following local statements and
2736             // combine with this- or super-call
2737             List<JCStatement> stats = translate(tree.body.stats.tail);
2738             if (target.initializeFieldsBeforeSuper())
2739                 tree.body.stats = stats.prepend(selfCall).prependList(added);
2740             else
2741                 tree.body.stats = stats.prependList(added).prepend(selfCall);
2742 
2743             outerThisStack = prevOuterThisStack;
2744         } else {
2745             Map<Symbol, Symbol> prevLambdaTranslationMap =
2746                     lambdaTranslationMap;
2747             try {
2748                 lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
2749                         tree.sym.name.startsWith(names.lambda) ?
2750                         makeTranslationMap(tree) : null;
2751                 super.visitMethodDef(tree);
2752             } finally {
2753                 lambdaTranslationMap = prevLambdaTranslationMap;
2754             }
2755         }
2756         result = tree;
2757     }
2758     //where
2759         private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
2760             Map<Symbol, Symbol> translationMap = new HashMap<Symbol,Symbol>();
2761             for (JCVariableDecl vd : tree.params) {
2762                 Symbol p = vd.sym;
2763                 if (p != p.baseSymbol()) {
2764                     translationMap.put(p.baseSymbol(), p);
2765                 }
2766             }
2767             return translationMap;
2768         }
2769 
2770     public void visitAnnotatedType(JCAnnotatedType tree) {
2771         // No need to retain type annotations in the tree
2772         // tree.annotations = translate(tree.annotations);
2773         tree.annotations = List.nil();
2774         tree.underlyingType = translate(tree.underlyingType);
2775         // but maintain type annotations in the type.
2776         if (tree.type.isAnnotated()) {
2777             if (tree.underlyingType.type.isAnnotated()) {
2778                 // The erasure of a type variable might be annotated.
2779                 // Merge all annotations.
2780                 AnnotatedType newat = (AnnotatedType) tree.underlyingType.type;
2781                 AnnotatedType at = (AnnotatedType) tree.type;
2782                 at.underlyingType = newat.underlyingType;
2783                 newat.typeAnnotations = at.typeAnnotations.appendList(newat.typeAnnotations);
2784                 tree.type = newat;
2785             } else {
2786                 // Create a new AnnotatedType to have the correct tag.
2787                 AnnotatedType oldat = (AnnotatedType) tree.type;
2788                 tree.type = new AnnotatedType(tree.underlyingType.type);
2789                 ((AnnotatedType) tree.type).typeAnnotations = oldat.typeAnnotations;
2790             }
2791         }
2792         result = tree;
2793     }
2794 
2795     public void visitTypeCast(JCTypeCast tree) {
2796         tree.clazz = translate(tree.clazz);
2797         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2798             tree.expr = translate(tree.expr, tree.type);
2799         else
2800             tree.expr = translate(tree.expr);
2801         result = tree;
2802     }
2803 
2804     public void visitNewClass(JCNewClass tree) {
2805         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2806 
2807         // Box arguments, if necessary
2808         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2809         List<Type> argTypes = tree.constructor.type.getParameterTypes();
2810         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2811         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2812         tree.varargsElement = null;
2813 
2814         // If created class is local, add free variables after
2815         // explicit constructor arguments.
2816         if ((c.owner.kind & (VAR | MTH)) != 0) {
2817             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2818         }
2819 
2820         // If an access constructor is used, append null as a last argument.
2821         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2822         if (constructor != tree.constructor) {
2823             tree.args = tree.args.append(makeNull());
2824             tree.constructor = constructor;
2825         }
2826 
2827         // If created class has an outer instance, and new is qualified, pass
2828         // qualifier as first argument. If new is not qualified, pass the
2829         // correct outer instance as first argument.
2830         if (c.hasOuterInstance()) {
2831             JCExpression thisArg;
2832             if (tree.encl != null) {
2833                 thisArg = attr.makeNullCheck(translate(tree.encl));
2834                 thisArg.type = tree.encl.type;
2835             } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2836                 // local class
2837                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2838             } else {
2839                 // nested class
2840                 thisArg = makeOwnerThis(tree.pos(), c, false);
2841             }
2842             tree.args = tree.args.prepend(thisArg);
2843         }
2844         tree.encl = null;
2845 
2846         // If we have an anonymous class, create its flat version, rather
2847         // than the class or interface following new.
2848         if (tree.def != null) {
2849             translate(tree.def);
2850             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2851             tree.def = null;
2852         } else {
2853             tree.clazz = access(c, tree.clazz, enclOp, false);
2854         }
2855         result = tree;
2856     }
2857 
2858     // Simplify conditionals with known constant controlling expressions.
2859     // This allows us to avoid generating supporting declarations for
2860     // the dead code, which will not be eliminated during code generation.
2861     // Note that Flow.isFalse and Flow.isTrue only return true
2862     // for constant expressions in the sense of JLS 15.27, which
2863     // are guaranteed to have no side-effects.  More aggressive
2864     // constant propagation would require that we take care to
2865     // preserve possible side-effects in the condition expression.
2866 
2867     /** Visitor method for conditional expressions.
2868      */
2869     @Override
2870     public void visitConditional(JCConditional tree) {
2871         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2872         if (cond.type.isTrue()) {
2873             result = convert(translate(tree.truepart, tree.type), tree.type);
2874             addPrunedInfo(cond);
2875         } else if (cond.type.isFalse()) {
2876             result = convert(translate(tree.falsepart, tree.type), tree.type);
2877             addPrunedInfo(cond);
2878         } else {
2879             // Condition is not a compile-time constant.
2880             tree.truepart = translate(tree.truepart, tree.type);
2881             tree.falsepart = translate(tree.falsepart, tree.type);
2882             result = tree;
2883         }
2884     }
2885 //where
2886     private JCTree convert(JCTree tree, Type pt) {
2887         if (tree.type == pt || tree.type.hasTag(BOT))
2888             return tree;
2889         JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2890         result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2891                                                        : pt;
2892         return result;
2893     }
2894 
2895     /** Visitor method for if statements.
2896      */
2897     public void visitIf(JCIf tree) {
2898         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2899         if (cond.type.isTrue()) {
2900             result = translate(tree.thenpart);
2901             addPrunedInfo(cond);
2902         } else if (cond.type.isFalse()) {
2903             if (tree.elsepart != null) {
2904                 result = translate(tree.elsepart);
2905             } else {
2906                 result = make.Skip();
2907             }
2908             addPrunedInfo(cond);
2909         } else {
2910             // Condition is not a compile-time constant.
2911             tree.thenpart = translate(tree.thenpart);
2912             tree.elsepart = translate(tree.elsepart);
2913             result = tree;
2914         }
2915     }
2916 
2917     /** Visitor method for assert statements. Translate them away.
2918      */
2919     public void visitAssert(JCAssert tree) {
2920         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2921         tree.cond = translate(tree.cond, syms.booleanType);
2922         if (!tree.cond.type.isTrue()) {
2923             JCExpression cond = assertFlagTest(tree.pos());
2924             List<JCExpression> exnArgs = (tree.detail == null) ?
2925                 List.<JCExpression>nil() : List.of(translate(tree.detail));
2926             if (!tree.cond.type.isFalse()) {
2927                 cond = makeBinary
2928                     (AND,
2929                      cond,
2930                      makeUnary(NOT, tree.cond));
2931             }
2932             result =
2933                 make.If(cond,
2934                         make_at(tree).
2935                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2936                         null);
2937         } else {
2938             result = make.Skip();
2939         }
2940     }
2941 
2942     public void visitApply(JCMethodInvocation tree) {
2943         Symbol meth = TreeInfo.symbol(tree.meth);
2944         List<Type> argtypes = meth.type.getParameterTypes();
2945         if (allowEnums &&
2946             meth.name==names.init &&
2947             meth.owner == syms.enumSym)
2948             argtypes = argtypes.tail.tail;
2949         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2950         tree.varargsElement = null;
2951         Name methName = TreeInfo.name(tree.meth);
2952         if (meth.name==names.init) {
2953             // We are seeing a this(...) or super(...) constructor call.
2954             // If an access constructor is used, append null as a last argument.
2955             Symbol constructor = accessConstructor(tree.pos(), meth);
2956             if (constructor != meth) {
2957                 tree.args = tree.args.append(makeNull());
2958                 TreeInfo.setSymbol(tree.meth, constructor);
2959             }
2960 
2961             // If we are calling a constructor of a local class, add
2962             // free variables after explicit constructor arguments.
2963             ClassSymbol c = (ClassSymbol)constructor.owner;
2964             if ((c.owner.kind & (VAR | MTH)) != 0) {
2965                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2966             }
2967 
2968             // If we are calling a constructor of an enum class, pass
2969             // along the name and ordinal arguments
2970             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2971                 List<JCVariableDecl> params = currentMethodDef.params;
2972                 if (currentMethodSym.owner.hasOuterInstance())
2973                     params = params.tail; // drop this$n
2974                 tree.args = tree.args
2975                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2976                     .prepend(make.Ident(params.head.sym)); // name
2977             }
2978 
2979             // If we are calling a constructor of a class with an outer
2980             // instance, and the call
2981             // is qualified, pass qualifier as first argument in front of
2982             // the explicit constructor arguments. If the call
2983             // is not qualified, pass the correct outer instance as
2984             // first argument.
2985             if (c.hasOuterInstance()) {
2986                 JCExpression thisArg;
2987                 if (tree.meth.hasTag(SELECT)) {
2988                     thisArg = attr.
2989                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2990                     tree.meth = make.Ident(constructor);
2991                     ((JCIdent) tree.meth).name = methName;
2992                 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2993                     // local class or this() call
2994                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2995                 } else {
2996                     // super() call of nested class - never pick 'this'
2997                     thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
2998                 }
2999                 tree.args = tree.args.prepend(thisArg);
3000             }
3001         } else {
3002             // We are seeing a normal method invocation; translate this as usual.
3003             tree.meth = translate(tree.meth);
3004 
3005             // If the translated method itself is an Apply tree, we are
3006             // seeing an access method invocation. In this case, append
3007             // the method arguments to the arguments of the access method.
3008             if (tree.meth.hasTag(APPLY)) {
3009                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3010                 app.args = tree.args.prependList(app.args);
3011                 result = app;
3012                 return;
3013             }
3014         }
3015         result = tree;
3016     }
3017 
3018     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3019         List<JCExpression> args = _args;
3020         if (parameters.isEmpty()) return args;
3021         boolean anyChanges = false;
3022         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
3023         while (parameters.tail.nonEmpty()) {
3024             JCExpression arg = translate(args.head, parameters.head);
3025             anyChanges |= (arg != args.head);
3026             result.append(arg);
3027             args = args.tail;
3028             parameters = parameters.tail;
3029         }
3030         Type parameter = parameters.head;
3031         if (varargsElement != null) {
3032             anyChanges = true;
3033             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
3034             while (args.nonEmpty()) {
3035                 JCExpression arg = translate(args.head, varargsElement);
3036                 elems.append(arg);
3037                 args = args.tail;
3038             }
3039             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3040                                                List.<JCExpression>nil(),
3041                                                elems.toList());
3042             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3043             result.append(boxedArgs);
3044         } else {
3045             if (args.length() != 1) throw new AssertionError(args);
3046             JCExpression arg = translate(args.head, parameter);
3047             anyChanges |= (arg != args.head);
3048             result.append(arg);
3049             if (!anyChanges) return _args;
3050         }
3051         return result.toList();
3052     }
3053 
3054     /** Expand a boxing or unboxing conversion if needed. */
3055     @SuppressWarnings("unchecked") // XXX unchecked
3056     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
3057         boolean havePrimitive = tree.type.isPrimitive();
3058         if (havePrimitive == type.isPrimitive())
3059             return tree;
3060         if (havePrimitive) {
3061             Type unboxedTarget = types.unboxedType(type);
3062             if (!unboxedTarget.hasTag(NONE)) {
3063                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3064                     tree.type = unboxedTarget.constType(tree.type.constValue());
3065                 return (T)boxPrimitive((JCExpression)tree, type);
3066             } else {
3067                 tree = (T)boxPrimitive((JCExpression)tree);
3068             }
3069         } else {
3070             tree = (T)unbox((JCExpression)tree, type);
3071         }
3072         return tree;
3073     }
3074 
3075     /** Box up a single primitive expression. */
3076     JCExpression boxPrimitive(JCExpression tree) {
3077         return boxPrimitive(tree, types.boxedClass(tree.type).type);
3078     }
3079 
3080     /** Box up a single primitive expression. */
3081     JCExpression boxPrimitive(JCExpression tree, Type box) {
3082         make_at(tree.pos());
3083         if (target.boxWithConstructors()) {
3084             Symbol ctor = lookupConstructor(tree.pos(),
3085                                             box,
3086                                             List.<Type>nil()
3087                                             .prepend(tree.type));
3088             return make.Create(ctor, List.of(tree));
3089         } else {
3090             Symbol valueOfSym = lookupMethod(tree.pos(),
3091                                              names.valueOf,
3092                                              box,
3093                                              List.<Type>nil()
3094                                              .prepend(tree.type));
3095             return make.App(make.QualIdent(valueOfSym), List.of(tree));
3096         }
3097     }
3098 
3099     /** Unbox an object to a primitive value. */
3100     JCExpression unbox(JCExpression tree, Type primitive) {
3101         Type unboxedType = types.unboxedType(tree.type);
3102         if (unboxedType.hasTag(NONE)) {
3103             unboxedType = primitive;
3104             if (!unboxedType.isPrimitive())
3105                 throw new AssertionError(unboxedType);
3106             make_at(tree.pos());
3107             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3108         } else {
3109             // There must be a conversion from unboxedType to primitive.
3110             if (!types.isSubtype(unboxedType, primitive))
3111                 throw new AssertionError(tree);
3112         }
3113         make_at(tree.pos());
3114         Symbol valueSym = lookupMethod(tree.pos(),
3115                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
3116                                        tree.type,
3117                                        List.<Type>nil());
3118         return make.App(make.Select(tree, valueSym));
3119     }
3120 
3121     /** Visitor method for parenthesized expressions.
3122      *  If the subexpression has changed, omit the parens.
3123      */
3124     public void visitParens(JCParens tree) {
3125         JCTree expr = translate(tree.expr);
3126         result = ((expr == tree.expr) ? tree : expr);
3127     }
3128 
3129     public void visitIndexed(JCArrayAccess tree) {
3130         tree.indexed = translate(tree.indexed);
3131         tree.index = translate(tree.index, syms.intType);
3132         result = tree;
3133     }
3134 
3135     public void visitAssign(JCAssign tree) {
3136         tree.lhs = translate(tree.lhs, tree);
3137         tree.rhs = translate(tree.rhs, tree.lhs.type);
3138 
3139         // If translated left hand side is an Apply, we are
3140         // seeing an access method invocation. In this case, append
3141         // right hand side as last argument of the access method.
3142         if (tree.lhs.hasTag(APPLY)) {
3143             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3144             app.args = List.of(tree.rhs).prependList(app.args);
3145             result = app;
3146         } else {
3147             result = tree;
3148         }
3149     }
3150 
3151     public void visitAssignop(final JCAssignOp tree) {
3152         JCTree lhsAccess = access(TreeInfo.skipParens(tree.lhs));
3153         final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3154             tree.operator.type.getReturnType().isPrimitive();
3155 
3156         if (boxingReq || lhsAccess.hasTag(APPLY)) {
3157             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3158             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3159             // (but without recomputing x)
3160             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3161                     public JCTree build(final JCTree lhs) {
3162                         JCTree.Tag newTag = tree.getTag().noAssignOp();
3163                         // Erasure (TransTypes) can change the type of
3164                         // tree.lhs.  However, we can still get the
3165                         // unerased type of tree.lhs as it is stored
3166                         // in tree.type in Attr.
3167                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
3168                                                                       newTag,
3169                                                                       attrEnv,
3170                                                                       tree.type,
3171                                                                       tree.rhs.type);
3172                         JCExpression expr = (JCExpression)lhs;
3173                         if (expr.type != tree.type)
3174                             expr = make.TypeCast(tree.type, expr);
3175                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3176                         opResult.operator = newOperator;
3177                         opResult.type = newOperator.type.getReturnType();
3178                         JCExpression newRhs = boxingReq ?
3179                             make.TypeCast(types.unboxedType(tree.type), opResult) :
3180                             opResult;
3181                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
3182                     }
3183                 });
3184             result = translate(newTree);
3185             return;
3186         }
3187         tree.lhs = translate(tree.lhs, tree);
3188         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3189 
3190         // If translated left hand side is an Apply, we are
3191         // seeing an access method invocation. In this case, append
3192         // right hand side as last argument of the access method.
3193         if (tree.lhs.hasTag(APPLY)) {
3194             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3195             // if operation is a += on strings,
3196             // make sure to convert argument to string
3197             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
3198               ? makeString(tree.rhs)
3199               : tree.rhs;
3200             app.args = List.of(rhs).prependList(app.args);
3201             result = app;
3202         } else {
3203             result = tree;
3204         }
3205     }
3206 
3207     /** Lower a tree of the form e++ or e-- where e is an object type */
3208     JCTree lowerBoxedPostop(final JCUnary tree) {
3209         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3210         // or
3211         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3212         // where OP is += or -=
3213         final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3214         return abstractLval(tree.arg, new TreeBuilder() {
3215                 public JCTree build(final JCTree tmp1) {
3216                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3217                             public JCTree build(final JCTree tmp2) {
3218                                 JCTree.Tag opcode = (tree.hasTag(POSTINC))
3219                                     ? PLUS_ASG : MINUS_ASG;
3220                                 JCTree lhs = cast
3221                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
3222                                     : tmp1;
3223                                 JCTree update = makeAssignop(opcode,
3224                                                              lhs,
3225                                                              make.Literal(1));
3226                                 return makeComma(update, tmp2);
3227                             }
3228                         });
3229                 }
3230             });
3231     }
3232 
3233     public void visitUnary(JCUnary tree) {
3234         boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3235         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3236             switch(tree.getTag()) {
3237             case PREINC:            // ++ e
3238                     // translate to e += 1
3239             case PREDEC:            // -- e
3240                     // translate to e -= 1
3241                 {
3242                     JCTree.Tag opcode = (tree.hasTag(PREINC))
3243                         ? PLUS_ASG : MINUS_ASG;
3244                     JCAssignOp newTree = makeAssignop(opcode,
3245                                                     tree.arg,
3246                                                     make.Literal(1));
3247                     result = translate(newTree, tree.type);
3248                     return;
3249                 }
3250             case POSTINC:           // e ++
3251             case POSTDEC:           // e --
3252                 {
3253                     result = translate(lowerBoxedPostop(tree), tree.type);
3254                     return;
3255                 }
3256             }
3257             throw new AssertionError(tree);
3258         }
3259 
3260         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3261 
3262         if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3263             tree.type = cfolder.fold1(bool_not, tree.arg.type);
3264         }
3265 
3266         // If translated left hand side is an Apply, we are
3267         // seeing an access method invocation. In this case, return
3268         // that access method invocation as result.
3269         if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3270             result = tree.arg;
3271         } else {
3272             result = tree;
3273         }
3274     }
3275 
3276     public void visitBinary(JCBinary tree) {
3277         List<Type> formals = tree.operator.type.getParameterTypes();
3278         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3279         switch (tree.getTag()) {
3280         case OR:
3281             if (lhs.type.isTrue()) {
3282                 result = lhs;
3283                 return;
3284             }
3285             if (lhs.type.isFalse()) {
3286                 result = translate(tree.rhs, formals.tail.head);
3287                 return;
3288             }
3289             break;
3290         case AND:
3291             if (lhs.type.isFalse()) {
3292                 result = lhs;
3293                 return;
3294             }
3295             if (lhs.type.isTrue()) {
3296                 result = translate(tree.rhs, formals.tail.head);
3297                 return;
3298             }
3299             break;
3300         }
3301         tree.rhs = translate(tree.rhs, formals.tail.head);
3302         result = tree;
3303     }
3304 
3305     public void visitIdent(JCIdent tree) {
3306         result = access(tree.sym, tree, enclOp, false);
3307     }
3308 
3309     /** Translate away the foreach loop.  */
3310     public void visitForeachLoop(JCEnhancedForLoop tree) {
3311         if (types.elemtype(tree.expr.type) == null)
3312             visitIterableForeachLoop(tree);
3313         else
3314             visitArrayForeachLoop(tree);
3315     }
3316         // where
3317         /**
3318          * A statement of the form
3319          *
3320          * <pre>
3321          *     for ( T v : arrayexpr ) stmt;
3322          * </pre>
3323          *
3324          * (where arrayexpr is of an array type) gets translated to
3325          *
3326          * <pre>{@code
3327          *     for ( { arraytype #arr = arrayexpr;
3328          *             int #len = array.length;
3329          *             int #i = 0; };
3330          *           #i < #len; i$++ ) {
3331          *         T v = arr$[#i];
3332          *         stmt;
3333          *     }
3334          * }</pre>
3335          *
3336          * where #arr, #len, and #i are freshly named synthetic local variables.
3337          */
3338         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3339             make_at(tree.expr.pos());
3340             VarSymbol arraycache = new VarSymbol(0,
3341                                                  names.fromString("arr" + target.syntheticNameChar()),
3342                                                  tree.expr.type,
3343                                                  currentMethodSym);
3344             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3345             VarSymbol lencache = new VarSymbol(0,
3346                                                names.fromString("len" + target.syntheticNameChar()),
3347                                                syms.intType,
3348                                                currentMethodSym);
3349             JCStatement lencachedef = make.
3350                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3351             VarSymbol index = new VarSymbol(0,
3352                                             names.fromString("i" + target.syntheticNameChar()),
3353                                             syms.intType,
3354                                             currentMethodSym);
3355 
3356             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3357             indexdef.init.type = indexdef.type = syms.intType.constType(0);
3358 
3359             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3360             JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3361 
3362             JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3363 
3364             Type elemtype = types.elemtype(tree.expr.type);
3365             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3366                                                     make.Ident(index)).setType(elemtype);
3367             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3368                                                   tree.var.name,
3369                                                   tree.var.vartype,
3370                                                   loopvarinit).setType(tree.var.type);
3371             loopvardef.sym = tree.var.sym;
3372             JCBlock body = make.
3373                 Block(0, List.of(loopvardef, tree.body));
3374 
3375             result = translate(make.
3376                                ForLoop(loopinit,
3377                                        cond,
3378                                        List.of(step),
3379                                        body));
3380             patchTargets(body, tree, result);
3381         }
3382         /** Patch up break and continue targets. */
3383         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3384             class Patcher extends TreeScanner {
3385                 public void visitBreak(JCBreak tree) {
3386                     if (tree.target == src)
3387                         tree.target = dest;
3388                 }
3389                 public void visitContinue(JCContinue tree) {
3390                     if (tree.target == src)
3391                         tree.target = dest;
3392                 }
3393                 public void visitClassDef(JCClassDecl tree) {}
3394             }
3395             new Patcher().scan(body);
3396         }
3397         /**
3398          * A statement of the form
3399          *
3400          * <pre>
3401          *     for ( T v : coll ) stmt ;
3402          * </pre>
3403          *
3404          * (where coll implements {@code Iterable<? extends T>}) gets translated to
3405          *
3406          * <pre>{@code
3407          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3408          *         T v = (T) #i.next();
3409          *         stmt;
3410          *     }
3411          * }</pre>
3412          *
3413          * where #i is a freshly named synthetic local variable.
3414          */
3415         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3416             make_at(tree.expr.pos());
3417             Type iteratorTarget = syms.objectType;
3418             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
3419                                               syms.iterableType.tsym);
3420             if (iterableType.getTypeArguments().nonEmpty())
3421                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3422             Type eType = tree.expr.type;
3423             while (eType.hasTag(TYPEVAR)) {
3424                 eType = eType.getUpperBound();
3425             }
3426             tree.expr.type = types.erasure(eType);
3427             if (eType.isCompound())
3428                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3429             Symbol iterator = lookupMethod(tree.expr.pos(),
3430                                            names.iterator,
3431                                            eType,
3432                                            List.<Type>nil());
3433             VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
3434                                             types.erasure(iterator.type.getReturnType()),
3435                                             currentMethodSym);
3436 
3437              JCStatement init = make.
3438                 VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3439                      .setType(types.erasure(iterator.type))));
3440 
3441             Symbol hasNext = lookupMethod(tree.expr.pos(),
3442                                           names.hasNext,
3443                                           itvar.type,
3444                                           List.<Type>nil());
3445             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3446             Symbol next = lookupMethod(tree.expr.pos(),
3447                                        names.next,
3448                                        itvar.type,
3449                                        List.<Type>nil());
3450             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3451             if (tree.var.type.isPrimitive())
3452                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3453             else
3454                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3455             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3456                                                   tree.var.name,
3457                                                   tree.var.vartype,
3458                                                   vardefinit).setType(tree.var.type);
3459             indexDef.sym = tree.var.sym;
3460             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3461             body.endpos = TreeInfo.endPos(tree.body);
3462             result = translate(make.
3463                 ForLoop(List.of(init),
3464                         cond,
3465                         List.<JCExpressionStatement>nil(),
3466                         body));
3467             patchTargets(body, tree, result);
3468         }
3469 
3470     public void visitVarDef(JCVariableDecl tree) {
3471         MethodSymbol oldMethodSym = currentMethodSym;
3472         tree.mods = translate(tree.mods);
3473         tree.vartype = translate(tree.vartype);
3474         if (currentMethodSym == null) {
3475             // A class or instance field initializer.
3476             currentMethodSym =
3477                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3478                                  names.empty, null,
3479                                  currentClass);
3480         }
3481         if (tree.init != null) tree.init = translate(tree.init, tree.type);
3482         result = tree;
3483         currentMethodSym = oldMethodSym;
3484     }
3485 
3486     public void visitBlock(JCBlock tree) {
3487         MethodSymbol oldMethodSym = currentMethodSym;
3488         if (currentMethodSym == null) {
3489             // Block is a static or instance initializer.
3490             currentMethodSym =
3491                 new MethodSymbol(tree.flags | BLOCK,
3492                                  names.empty, null,
3493                                  currentClass);
3494         }
3495         super.visitBlock(tree);
3496         currentMethodSym = oldMethodSym;
3497     }
3498 
3499     public void visitDoLoop(JCDoWhileLoop tree) {
3500         tree.body = translate(tree.body);
3501         tree.cond = translate(tree.cond, syms.booleanType);
3502         result = tree;
3503     }
3504 
3505     public void visitWhileLoop(JCWhileLoop tree) {
3506         tree.cond = translate(tree.cond, syms.booleanType);
3507         tree.body = translate(tree.body);
3508         result = tree;
3509     }
3510 
3511     public void visitForLoop(JCForLoop tree) {
3512         tree.init = translate(tree.init);
3513         if (tree.cond != null)
3514             tree.cond = translate(tree.cond, syms.booleanType);
3515         tree.step = translate(tree.step);
3516         tree.body = translate(tree.body);
3517         result = tree;
3518     }
3519 
3520     public void visitReturn(JCReturn tree) {
3521         if (tree.expr != null)
3522             tree.expr = translate(tree.expr,
3523                                   types.erasure(currentMethodDef
3524                                                 .restype.type));
3525         result = tree;
3526     }
3527 
3528     public void visitSwitch(JCSwitch tree) {
3529         Type selsuper = types.supertype(tree.selector.type);
3530         boolean enumSwitch = selsuper != null &&
3531             (tree.selector.type.tsym.flags() & ENUM) != 0;
3532         boolean stringSwitch = selsuper != null &&
3533             types.isSameType(tree.selector.type, syms.stringType);
3534         Type target = enumSwitch ? tree.selector.type :
3535             (stringSwitch? syms.stringType : syms.intType);
3536         tree.selector = translate(tree.selector, target);
3537         tree.cases = translateCases(tree.cases);
3538         if (enumSwitch) {
3539             result = visitEnumSwitch(tree);
3540         } else if (stringSwitch) {
3541             result = visitStringSwitch(tree);
3542         } else {
3543             result = tree;
3544         }
3545     }
3546 
3547     public JCTree visitEnumSwitch(JCSwitch tree) {
3548         TypeSymbol enumSym = tree.selector.type.tsym;
3549         EnumMapping map = mapForEnum(tree.pos(), enumSym);
3550         make_at(tree.pos());
3551         Symbol ordinalMethod = lookupMethod(tree.pos(),
3552                                             names.ordinal,
3553                                             tree.selector.type,
3554                                             List.<Type>nil());
3555         JCArrayAccess selector = make.Indexed(map.mapVar,
3556                                         make.App(make.Select(tree.selector,
3557                                                              ordinalMethod)));
3558         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3559         for (JCCase c : tree.cases) {
3560             if (c.pat != null) {
3561                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3562                 JCLiteral pat = map.forConstant(label);
3563                 cases.append(make.Case(pat, c.stats));
3564             } else {
3565                 cases.append(c);
3566             }
3567         }
3568         JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3569         patchTargets(enumSwitch, tree, enumSwitch);
3570         return enumSwitch;
3571     }
3572 
3573     public JCTree visitStringSwitch(JCSwitch tree) {
3574         List<JCCase> caseList = tree.getCases();
3575         int alternatives = caseList.size();
3576 
3577         if (alternatives == 0) { // Strange but legal possibility
3578             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3579         } else {
3580             /*
3581              * The general approach used is to translate a single
3582              * string switch statement into a series of two chained
3583              * switch statements: the first a synthesized statement
3584              * switching on the argument string's hash value and
3585              * computing a string's position in the list of original
3586              * case labels, if any, followed by a second switch on the
3587              * computed integer value.  The second switch has the same
3588              * code structure as the original string switch statement
3589              * except that the string case labels are replaced with
3590              * positional integer constants starting at 0.
3591              *
3592              * The first switch statement can be thought of as an
3593              * inlined map from strings to their position in the case
3594              * label list.  An alternate implementation would use an
3595              * actual Map for this purpose, as done for enum switches.
3596              *
3597              * With some additional effort, it would be possible to
3598              * use a single switch statement on the hash code of the
3599              * argument, but care would need to be taken to preserve
3600              * the proper control flow in the presence of hash
3601              * collisions and other complications, such as
3602              * fallthroughs.  Switch statements with one or two
3603              * alternatives could also be specially translated into
3604              * if-then statements to omit the computation of the hash
3605              * code.
3606              *
3607              * The generated code assumes that the hashing algorithm
3608              * of String is the same in the compilation environment as
3609              * in the environment the code will run in.  The string
3610              * hashing algorithm in the SE JDK has been unchanged
3611              * since at least JDK 1.2.  Since the algorithm has been
3612              * specified since that release as well, it is very
3613              * unlikely to be changed in the future.
3614              *
3615              * Different hashing algorithms, such as the length of the
3616              * strings or a perfect hashing algorithm over the
3617              * particular set of case labels, could potentially be
3618              * used instead of String.hashCode.
3619              */
3620 
3621             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
3622 
3623             // Map from String case labels to their original position in
3624             // the list of case labels.
3625             Map<String, Integer> caseLabelToPosition =
3626                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
3627 
3628             // Map of hash codes to the string case labels having that hashCode.
3629             Map<Integer, Set<String>> hashToString =
3630                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
3631 
3632             int casePosition = 0;
3633             for(JCCase oneCase : caseList) {
3634                 JCExpression expression = oneCase.getExpression();
3635 
3636                 if (expression != null) { // expression for a "default" case is null
3637                     String labelExpr = (String) expression.type.constValue();
3638                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3639                     Assert.checkNull(mapping);
3640                     int hashCode = labelExpr.hashCode();
3641 
3642                     Set<String> stringSet = hashToString.get(hashCode);
3643                     if (stringSet == null) {
3644                         stringSet = new LinkedHashSet<String>(1, 1.0f);
3645                         stringSet.add(labelExpr);
3646                         hashToString.put(hashCode, stringSet);
3647                     } else {
3648                         boolean added = stringSet.add(labelExpr);
3649                         Assert.check(added);
3650                     }
3651                 }
3652                 casePosition++;
3653             }
3654 
3655             // Synthesize a switch statement that has the effect of
3656             // mapping from a string to the integer position of that
3657             // string in the list of case labels.  This is done by
3658             // switching on the hashCode of the string followed by an
3659             // if-then-else chain comparing the input for equality
3660             // with all the case labels having that hash value.
3661 
3662             /*
3663              * s$ = top of stack;
3664              * tmp$ = -1;
3665              * switch($s.hashCode()) {
3666              *     case caseLabel.hashCode:
3667              *         if (s$.equals("caseLabel_1")
3668              *           tmp$ = caseLabelToPosition("caseLabel_1");
3669              *         else if (s$.equals("caseLabel_2"))
3670              *           tmp$ = caseLabelToPosition("caseLabel_2");
3671              *         ...
3672              *         break;
3673              * ...
3674              * }
3675              */
3676 
3677             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3678                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
3679                                                syms.stringType,
3680                                                currentMethodSym);
3681             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3682 
3683             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3684                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3685                                                  syms.intType,
3686                                                  currentMethodSym);
3687             JCVariableDecl dollar_tmp_def =
3688                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3689             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3690             stmtList.append(dollar_tmp_def);
3691             ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
3692             // hashCode will trigger nullcheck on original switch expression
3693             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3694                                                        names.hashCode,
3695                                                        List.<JCExpression>nil()).setType(syms.intType);
3696             JCSwitch switch1 = make.Switch(hashCodeCall,
3697                                         caseBuffer.toList());
3698             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3699                 int hashCode = entry.getKey();
3700                 Set<String> stringsWithHashCode = entry.getValue();
3701                 Assert.check(stringsWithHashCode.size() >= 1);
3702 
3703                 JCStatement elsepart = null;
3704                 for(String caseLabel : stringsWithHashCode ) {
3705                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3706                                                                    names.equals,
3707                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
3708                     elsepart = make.If(stringEqualsCall,
3709                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
3710                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
3711                                                  setType(dollar_tmp.type)),
3712                                        elsepart);
3713                 }
3714 
3715                 ListBuffer<JCStatement> lb = ListBuffer.lb();
3716                 JCBreak breakStmt = make.Break(null);
3717                 breakStmt.target = switch1;
3718                 lb.append(elsepart).append(breakStmt);
3719 
3720                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3721             }
3722 
3723             switch1.cases = caseBuffer.toList();
3724             stmtList.append(switch1);
3725 
3726             // Make isomorphic switch tree replacing string labels
3727             // with corresponding integer ones from the label to
3728             // position map.
3729 
3730             ListBuffer<JCCase> lb = ListBuffer.lb();
3731             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3732             for(JCCase oneCase : caseList ) {
3733                 // Rewire up old unlabeled break statements to the
3734                 // replacement switch being created.
3735                 patchTargets(oneCase, tree, switch2);
3736 
3737                 boolean isDefault = (oneCase.getExpression() == null);
3738                 JCExpression caseExpr;
3739                 if (isDefault)
3740                     caseExpr = null;
3741                 else {
3742                     caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3743                                                                                                 getExpression()).
3744                                                                     type.constValue()));
3745                 }
3746 
3747                 lb.append(make.Case(caseExpr,
3748                                     oneCase.getStatements()));
3749             }
3750 
3751             switch2.cases = lb.toList();
3752             stmtList.append(switch2);
3753 
3754             return make.Block(0L, stmtList.toList());
3755         }
3756     }
3757 
3758     public void visitNewArray(JCNewArray tree) {
3759         tree.elemtype = translate(tree.elemtype);
3760         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3761             if (t.head != null) t.head = translate(t.head, syms.intType);
3762         tree.elems = translate(tree.elems, types.elemtype(tree.type));
3763         result = tree;
3764     }
3765 
3766     public void visitSelect(JCFieldAccess tree) {
3767         // need to special case-access of the form C.super.x
3768         // these will always need an access method, unless C
3769         // is a default interface subclassed by the current class.
3770         boolean qualifiedSuperAccess =
3771             tree.selected.hasTag(SELECT) &&
3772             TreeInfo.name(tree.selected) == names._super &&
3773             !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
3774         tree.selected = translate(tree.selected);
3775         if (tree.name == names._class) {
3776             result = classOf(tree.selected);
3777         }
3778         else if (tree.name == names._super &&
3779                 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
3780             //default super call!! Not a classic qualified super call
3781             TypeSymbol supSym = tree.selected.type.tsym;
3782             Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
3783             result = tree;
3784         }
3785         else if (tree.name == names._this || tree.name == names._super) {
3786             result = makeThis(tree.pos(), tree.selected.type.tsym);
3787         }
3788         else
3789             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3790     }
3791 
3792     public void visitLetExpr(LetExpr tree) {
3793         tree.defs = translateVarDefs(tree.defs);
3794         tree.expr = translate(tree.expr, tree.type);
3795         result = tree;
3796     }
3797 
3798     // There ought to be nothing to rewrite here;
3799     // we don't generate code.
3800     public void visitAnnotation(JCAnnotation tree) {
3801         result = tree;
3802     }
3803 
3804     @Override
3805     public void visitTry(JCTry tree) {
3806         /* special case of try without catchers and with finally emtpy.
3807          * Don't give it a try, translate only the body.
3808          */
3809         if (tree.resources.isEmpty()) {
3810             if (tree.catchers.isEmpty() &&
3811                 tree.finalizer.getStatements().isEmpty()) {
3812                 result = translate(tree.body);
3813             } else {
3814                 super.visitTry(tree);
3815             }
3816         } else {
3817             result = makeTwrTry(tree);
3818         }
3819     }
3820 
3821 /**************************************************************************
3822  * main method
3823  *************************************************************************/
3824 
3825     /** Translate a toplevel class and return a list consisting of
3826      *  the translated class and translated versions of all inner classes.
3827      *  @param env   The attribution environment current at the class definition.
3828      *               We need this for resolving some additional symbols.
3829      *  @param cdef  The tree representing the class definition.
3830      */
3831     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3832         ListBuffer<JCTree> translated = null;
3833         try {
3834             attrEnv = env;
3835             this.make = make;
3836             endPosTable = env.toplevel.endPositions;
3837             currentClass = null;
3838             currentMethodDef = null;
3839             outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3840             outermostMemberDef = null;
3841             this.translated = new ListBuffer<JCTree>();
3842             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3843             actualSymbols = new HashMap<Symbol,Symbol>();
3844             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3845             proxies = new Scope(syms.noSymbol);
3846             twrVars = new Scope(syms.noSymbol);
3847             outerThisStack = List.nil();
3848             accessNums = new HashMap<Symbol,Integer>();
3849             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3850             accessConstrs = new HashMap<Symbol,MethodSymbol>();
3851             accessConstrTags = List.nil();
3852             accessed = new ListBuffer<Symbol>();
3853             translate(cdef, (JCExpression)null);
3854             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3855                 makeAccessible(l.head);
3856             for (EnumMapping map : enumSwitchMap.values())
3857                 map.translate();
3858             checkConflicts(this.translated.toList());
3859             checkAccessConstructorTags();
3860             translated = this.translated;
3861         } finally {
3862             // note that recursive invocations of this method fail hard
3863             attrEnv = null;
3864             this.make = null;
3865             endPosTable = null;
3866             currentClass = null;
3867             currentMethodDef = null;
3868             outermostClassDef = null;
3869             outermostMemberDef = null;
3870             this.translated = null;
3871             classdefs = null;
3872             actualSymbols = null;
3873             freevarCache = null;
3874             proxies = null;
3875             outerThisStack = null;
3876             accessNums = null;
3877             accessSyms = null;
3878             accessConstrs = null;
3879             accessConstrTags = null;
3880             accessed = null;
3881             enumSwitchMap.clear();
3882         }
3883         return translated.toList();
3884     }
3885 }