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