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