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