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