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