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