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