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