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