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