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