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 allowPrimitiveClasses;
 105     private final boolean useMatchException;
 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         allowPrimitiveClasses = Source.Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
 135         Preview preview = Preview.instance(context);
 136         useMatchException = Feature.PATTERN_SWITCH.allowedInSource(source) &&
 137                             (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH));
 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 | IDENTITY_TYPE,
 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 (names.isInitOrVNew(sym.name) && 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 void addPrunedInfo(JCTree tree) {
1202         List<JCTree> infoList = prunedTree.get(currentClass);
1203         infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
1204         prunedTree.put(currentClass, infoList);
1205     }
1206 
1207     /** Ensure that identifier is accessible, return tree accessing the identifier.
1208      *  @param sym      The accessed symbol.
1209      *  @param tree     The tree referring to the symbol.
1210      *  @param enclOp   The closest enclosing operation node of tree,
1211      *                  null if tree is not a subtree of an operation.
1212      *  @param refSuper Is access via a (qualified) C.super?
1213      */
1214     JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
1215         // Access a free variable via its proxy, or its proxy's proxy
1216         while (sym.kind == VAR && sym.owner.kind == MTH &&
1217             sym.owner.enclClass() != currentClass) {
1218             // A constant is replaced by its constant value.
1219             Object cv = ((VarSymbol)sym).getConstValue();
1220             if (cv != null) {
1221                 make.at(tree.pos);
1222                 return makeLit(sym.type, cv);
1223             }
1224             if (lambdaTranslationMap != null && lambdaTranslationMap.get(sym) != null) {
1225                 return make.at(tree.pos).Ident(lambdaTranslationMap.get(sym));
1226             } else {
1227                 // Otherwise replace the variable by its proxy.
1228                 sym = proxies.get(sym);
1229                 Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
1230                 tree = make.at(tree.pos).Ident(sym);
1231             }
1232         }
1233         JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
1234         switch (sym.kind) {
1235         case TYP:
1236             if (sym.owner.kind != PCK) {
1237                 // Make sure not to lose type fidelity due to symbol sharing between projections
1238                 boolean requireReferenceProjection = allowPrimitiveClasses &&
1239                         tree.hasTag(SELECT) && ((JCFieldAccess) tree).name == names.ref && tree.type.isReferenceProjection();
1240                 // Convert type idents to
1241                 // <flat name> or <package name> . <flat name>
1242                 Name flatname = Convert.shortName(sym.flatName());
1243                 while (base != null &&
1244                        TreeInfo.symbol(base) != null &&
1245                        TreeInfo.symbol(base).kind != PCK) {
1246                     base = (base.hasTag(SELECT))
1247                         ? ((JCFieldAccess) base).selected
1248                         : null;
1249                 }
1250                 if (tree.hasTag(IDENT)) {
1251                     ((JCIdent) tree).name = flatname;
1252                 } else if (base == null) {
1253                     tree = make.at(tree.pos).Ident(sym);
1254                     ((JCIdent) tree).name = flatname;
1255                     if (requireReferenceProjection) {
1256                         tree.setType(tree.type.referenceProjection());
1257                     }
1258                 } else {
1259                     ((JCFieldAccess) tree).selected = base;
1260                     ((JCFieldAccess) tree).name = flatname;
1261                     if (requireReferenceProjection) {
1262                         tree.setType(tree.type.referenceProjection());
1263                     }
1264                 }
1265             }
1266             break;
1267         case MTH: case VAR:
1268             if (sym.owner.kind == TYP) {
1269 
1270                 // Access methods are required for
1271                 //  - private members,
1272                 //  - protected members in a superclass of an
1273                 //    enclosing class contained in another package.
1274                 //  - all non-private members accessed via a qualified super.
1275                 boolean protAccess = refSuper && !needsPrivateAccess(sym)
1276                     || needsProtectedAccess(sym, tree);
1277                 boolean accReq = protAccess || needsPrivateAccess(sym);
1278 
1279                 // A base has to be supplied for
1280                 //  - simple identifiers accessing variables in outer classes.
1281                 boolean baseReq =
1282                     base == null &&
1283                     sym.owner != syms.predefClass &&
1284                     !sym.isMemberOf(currentClass, types);
1285 
1286                 if (accReq || baseReq) {
1287                     make.at(tree.pos);
1288 
1289                     // Constants are replaced by their constant value.
1290                     if (sym.kind == VAR) {
1291                         Object cv = ((VarSymbol)sym).getConstValue();
1292                         if (cv != null) {
1293                             addPrunedInfo(tree);
1294                             return makeLit(sym.type, cv);
1295                         }
1296                     }
1297 
1298                     // Private variables and methods are replaced by calls
1299                     // to their access methods.
1300                     if (accReq) {
1301                         List<JCExpression> args = List.nil();
1302                         if ((sym.flags() & STATIC) == 0) {
1303                             // Instance access methods get instance
1304                             // as first parameter.
1305                             if (base == null)
1306                                 base = makeOwnerThis(tree.pos(), sym, true);
1307                             args = args.prepend(base);
1308                             base = null;   // so we don't duplicate code
1309                         }
1310                         Symbol access = accessSymbol(sym, tree,
1311                                                      enclOp, protAccess,
1312                                                      refSuper);
1313                         JCExpression receiver = make.Select(
1314                             base != null ? base : make.QualIdent(access.owner),
1315                             access);
1316                         return make.App(receiver, args);
1317 
1318                     // Other accesses to members of outer classes get a
1319                     // qualifier.
1320                     } else if (baseReq) {
1321                         return make.at(tree.pos).Select(
1322                             accessBase(tree.pos(), sym), sym).setType(tree.type);
1323                     }
1324                 }
1325             } else if (sym.owner.kind == MTH && lambdaTranslationMap != null) {
1326                 //sym is a local variable - check the lambda translation map to
1327                 //see if sym has been translated to something else in the current
1328                 //scope (by LambdaToMethod)
1329                 Symbol translatedSym = lambdaTranslationMap.get(sym.baseSymbol());
1330                 if (translatedSym != null) {
1331                     tree = make.at(tree.pos).Ident(translatedSym);
1332                 }
1333             }
1334         }
1335         return tree;
1336     }
1337 
1338     /** Ensure that identifier is accessible, return tree accessing the identifier.
1339      *  @param tree     The identifier tree.
1340      */
1341     JCExpression access(JCExpression tree) {
1342         Symbol sym = TreeInfo.symbol(tree);
1343         return sym == null ? tree : access(sym, tree, null, false);
1344     }
1345 
1346     /** Return access constructor for a private constructor,
1347      *  or the constructor itself, if no access constructor is needed.
1348      *  @param pos       The position to report diagnostics, if any.
1349      *  @param constr    The private constructor.
1350      */
1351     Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1352         if (needsPrivateAccess(constr)) {
1353             ClassSymbol accOwner = constr.owner.enclClass();
1354             MethodSymbol aconstr = accessConstrs.get(constr);
1355             if (aconstr == null) {
1356                 List<Type> argtypes = constr.type.getParameterTypes();
1357                 if ((accOwner.flags_field & ENUM) != 0)
1358                     argtypes = argtypes
1359                         .prepend(syms.intType)
1360                         .prepend(syms.stringType);
1361                 Name constructorName = accOwner.isConcreteValueClass() ? names.vnew : names.init;
1362                 aconstr = new MethodSymbol(
1363                     SYNTHETIC,
1364                     constructorName,
1365                     new MethodType(
1366                         argtypes.append(
1367                             accessConstructorTag().erasure(types)),
1368                         constr.type.getReturnType(),
1369                         constr.type.getThrownTypes(),
1370                         syms.methodClass),
1371                     accOwner);
1372                 enterSynthetic(pos, aconstr, accOwner.members());
1373                 accessConstrs.put(constr, aconstr);
1374                 accessed.append(constr);
1375             }
1376             return aconstr;
1377         } else {
1378             return constr;
1379         }
1380     }
1381 
1382     /** Return an anonymous class nested in this toplevel class.
1383      */
1384     ClassSymbol accessConstructorTag() {
1385         ClassSymbol topClass = currentClass.outermostClass();
1386         ModuleSymbol topModle = topClass.packge().modle;
1387         for (int i = 1; ; i++) {
1388             Name flatname = names.fromString("" + topClass.getQualifiedName() +
1389                                             target.syntheticNameChar() +
1390                                             i);
1391             ClassSymbol ctag = chk.getCompiled(topModle, flatname);
1392             if (ctag == null)
1393                 ctag = makeEmptyClass(STATIC | SYNTHETIC | IDENTITY_TYPE, topClass).sym;
1394             else if (!ctag.isAnonymous())
1395                 continue;
1396             // keep a record of all tags, to verify that all are generated as required
1397             accessConstrTags = accessConstrTags.prepend(ctag);
1398             return ctag;
1399         }
1400     }
1401 
1402     /** Add all required access methods for a private symbol to enclosing class.
1403      *  @param sym       The symbol.
1404      */
1405     void makeAccessible(Symbol sym) {
1406         JCClassDecl cdef = classDef(sym.owner.enclClass());
1407         if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
1408         if (names.isInitOrVNew(sym.name)) {
1409             cdef.defs = cdef.defs.prepend(
1410                 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
1411         } else {
1412             MethodSymbol[] accessors = accessSyms.get(sym);
1413             for (int i = 0; i < AccessCode.numberOfAccessCodes; i++) {
1414                 if (accessors[i] != null)
1415                     cdef.defs = cdef.defs.prepend(
1416                         accessDef(cdef.pos, sym, accessors[i], i));
1417             }
1418         }
1419     }
1420 
1421     /** Construct definition of an access method.
1422      *  @param pos        The source code position of the definition.
1423      *  @param vsym       The private or protected symbol.
1424      *  @param accessor   The access method for the symbol.
1425      *  @param acode      The access code.
1426      */
1427     JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
1428 //      System.err.println("access " + vsym + " with " + accessor);//DEBUG
1429         currentClass = vsym.owner.enclClass();
1430         make.at(pos);
1431         JCMethodDecl md = make.MethodDef(accessor, null);
1432 
1433         // Find actual symbol
1434         Symbol sym = actualSymbols.get(vsym);
1435         if (sym == null) sym = vsym;
1436 
1437         JCExpression ref;           // The tree referencing the private symbol.
1438         List<JCExpression> args;    // Any additional arguments to be passed along.
1439         if ((sym.flags() & STATIC) != 0) {
1440             ref = make.Ident(sym);
1441             args = make.Idents(md.params);
1442         } else {
1443             JCExpression site = make.Ident(md.params.head);
1444             if (acode % 2 != 0) {
1445                 //odd access codes represent qualified super accesses - need to
1446                 //emit reference to the direct superclass, even if the referred
1447                 //member is from an indirect superclass (JLS 13.1)
1448                 site.setType(types.erasure(types.supertype(vsym.owner.enclClass().type)));
1449             }
1450             ref = make.Select(site, sym);
1451             args = make.Idents(md.params.tail);
1452         }
1453         JCStatement stat;          // The statement accessing the private symbol.
1454         if (sym.kind == VAR) {
1455             // Normalize out all odd access codes by taking floor modulo 2:
1456             int acode1 = acode - (acode & 1);
1457 
1458             JCExpression expr;      // The access method's return value.
1459             AccessCode aCode = AccessCode.getFromCode(acode1);
1460             switch (aCode) {
1461             case DEREF:
1462                 expr = ref;
1463                 break;
1464             case ASSIGN:
1465                 expr = make.Assign(ref, args.head);
1466                 break;
1467             case PREINC: case POSTINC: case PREDEC: case POSTDEC:
1468                 expr = makeUnary(aCode.tag, ref);
1469                 break;
1470             default:
1471                 expr = make.Assignop(
1472                     treeTag(binaryAccessOperator(acode1, JCTree.Tag.NO_TAG)), ref, args.head);
1473                 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1, JCTree.Tag.NO_TAG);
1474             }
1475             stat = make.Return(expr.setType(sym.type));
1476         } else {
1477             stat = make.Call(make.App(ref, args));
1478         }
1479         md.body = make.Block(0, List.of(stat));
1480 
1481         // Make sure all parameters, result types and thrown exceptions
1482         // are accessible.
1483         for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
1484             l.head.vartype = access(l.head.vartype);
1485         md.restype = access(md.restype);
1486         for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
1487             l.head = access(l.head);
1488 
1489         return md;
1490     }
1491 
1492     /** Construct definition of an access constructor.
1493      *  @param pos        The source code position of the definition.
1494      *  @param constr     The private constructor.
1495      *  @param accessor   The access method for the constructor.
1496      */
1497     JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
1498         make.at(pos);
1499         JCMethodDecl md = make.MethodDef(accessor,
1500                                       accessor.externalType(types),
1501                                       null);
1502         JCIdent callee = make.Ident(names._this);
1503         callee.sym = constr;
1504         callee.type = constr.type;
1505         md.body =
1506             make.Block(0, List.of(
1507                 make.Call(
1508                     make.App(
1509                         callee,
1510                         make.Idents(md.params.reverse().tail.reverse())))));
1511         return md;
1512     }
1513 
1514 /**************************************************************************
1515  * Free variables proxies and this$n
1516  *************************************************************************/
1517 
1518     /** A map which allows to retrieve the translated proxy variable for any given symbol of an
1519      *  enclosing scope that is accessed (the accessed symbol could be the synthetic 'this$n' symbol).
1520      *  Inside a constructor, the map temporarily overrides entries corresponding to proxies and any
1521      *  'this$n' symbols, where they represent the constructor parameters.
1522      */
1523     Map<Symbol, Symbol> proxies;
1524 
1525     /** A scope containing all unnamed resource variables/saved
1526      *  exception variables for translated TWR blocks
1527      */
1528     WriteableScope twrVars;
1529 
1530     /** A stack containing the this$n field of the currently translated
1531      *  classes (if needed) in innermost first order.
1532      *  Inside a constructor, proxies and any this$n symbol are duplicated
1533      *  in an additional innermost scope, where they represent the constructor
1534      *  parameters.
1535      */
1536     List<VarSymbol> outerThisStack;
1537 
1538     /** The name of a free variable proxy.
1539      */
1540     Name proxyName(Name name, int index) {
1541         Name proxyName = names.fromString("val" + target.syntheticNameChar() + name);
1542         if (index > 0) {
1543             proxyName = proxyName.append(names.fromString("" + target.syntheticNameChar() + index));
1544         }
1545         return proxyName;
1546     }
1547 
1548     /** Proxy definitions for all free variables in given list, in reverse order.
1549      *  @param pos        The source code position of the definition.
1550      *  @param freevars   The free variables.
1551      *  @param owner      The class in which the definitions go.
1552      */
1553     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
1554         return freevarDefs(pos, freevars, owner, 0);
1555     }
1556 
1557     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner,
1558             long additionalFlags) {
1559         long flags = FINAL | SYNTHETIC | additionalFlags;
1560         List<JCVariableDecl> defs = List.nil();
1561         Set<Name> proxyNames = new HashSet<>();
1562         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
1563             VarSymbol v = l.head;
1564             int index = 0;
1565             Name proxyName;
1566             do {
1567                 proxyName = proxyName(v.name, index++);
1568             } while (!proxyNames.add(proxyName));
1569             VarSymbol proxy = new VarSymbol(
1570                 flags, proxyName, v.erasure(types), owner);
1571             proxies.put(v, proxy);
1572             JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
1573             vd.vartype = access(vd.vartype);
1574             defs = defs.prepend(vd);
1575         }
1576         return defs;
1577     }
1578 
1579     /** The name of a this$n field
1580      *  @param type   The class referenced by the this$n field
1581      */
1582     Name outerThisName(Type type, Symbol owner) {
1583         Type t = type.getEnclosingType();
1584         int nestingLevel = 0;
1585         while (t.hasTag(CLASS)) {
1586             t = t.getEnclosingType();
1587             nestingLevel++;
1588         }
1589         Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
1590         while (owner.kind == TYP && ((ClassSymbol)owner).members().findFirst(result) != null)
1591             result = names.fromString(result.toString() + target.syntheticNameChar());
1592         return result;
1593     }
1594 
1595     private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) {
1596         Type target = types.erasure(owner.enclClass().type.getEnclosingType());
1597         // Set NOOUTERTHIS for all synthetic outer instance variables, and unset
1598         // it when the variable is accessed. If the variable is never accessed,
1599         // we skip creating an outer instance field and saving the constructor
1600         // parameter to it.
1601         VarSymbol outerThis =
1602             new VarSymbol(flags | NOOUTERTHIS, outerThisName(target, owner), target, owner);
1603         outerThisStack = outerThisStack.prepend(outerThis);
1604         return outerThis;
1605     }
1606 
1607     private JCVariableDecl makeOuterThisVarDecl(int pos, VarSymbol sym) {
1608         JCVariableDecl vd = make.at(pos).VarDef(sym, null);
1609         vd.vartype = access(vd.vartype);
1610         return vd;
1611     }
1612 
1613     /** Definition for this$n field.
1614      *  @param pos        The source code position of the definition.
1615      *  @param owner      The method in which the definition goes.
1616      */
1617     JCVariableDecl outerThisDef(int pos, MethodSymbol owner) {
1618         ClassSymbol c = owner.enclClass();
1619         boolean isMandated =
1620             // Anonymous constructors
1621             (owner.isInitOrVNew() && owner.isAnonymous()) ||
1622             // Constructors of non-private inner member classes
1623             (owner.isInitOrVNew() && c.isInner() &&
1624              !c.isPrivate() && !c.isStatic());
1625         long flags =
1626             FINAL | (isMandated ? MANDATED : SYNTHETIC) | PARAMETER;
1627         VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags);
1628         owner.extraParams = owner.extraParams.prepend(outerThis);
1629         return makeOuterThisVarDecl(pos, outerThis);
1630     }
1631 
1632     /** Definition for this$n field.
1633      *  @param pos        The source code position of the definition.
1634      *  @param owner      The class in which the definition goes.
1635      */
1636     JCVariableDecl outerThisDef(int pos, ClassSymbol owner) {
1637         VarSymbol outerThis = makeOuterThisVarSymbol(owner, FINAL | SYNTHETIC);
1638         return makeOuterThisVarDecl(pos, outerThis);
1639     }
1640 
1641     /** Return a list of trees that load the free variables in given list,
1642      *  in reverse order.
1643      *  @param pos          The source code position to be used for the trees.
1644      *  @param freevars     The list of free variables.
1645      */
1646     List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
1647         List<JCExpression> args = List.nil();
1648         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
1649             args = args.prepend(loadFreevar(pos, l.head));
1650         return args;
1651     }
1652 //where
1653         JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
1654             return access(v, make.at(pos).Ident(v), null, false);
1655         }
1656 
1657     /** Construct a tree simulating the expression {@code C.this}.
1658      *  @param pos           The source code position to be used for the tree.
1659      *  @param c             The qualifier class.
1660      */
1661     JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
1662         if (currentClass == c) {
1663             // in this case, `this' works fine
1664             return make.at(pos).This(c.erasure(types));
1665         } else {
1666             // need to go via this$n
1667             return makeOuterThis(pos, c);
1668         }
1669     }
1670 
1671     /**
1672      * Optionally replace a try statement with the desugaring of a
1673      * try-with-resources statement.  The canonical desugaring of
1674      *
1675      * try ResourceSpecification
1676      *   Block
1677      *
1678      * is
1679      *
1680      * {
1681      *   final VariableModifiers_minus_final R #resource = Expression;
1682      *
1683      *   try ResourceSpecificationtail
1684      *     Block
1685      *   } body-only-finally {
1686      *     if (#resource != null) //nullcheck skipped if Expression is provably non-null
1687      *         #resource.close();
1688      *   } catch (Throwable #primaryException) {
1689      *       if (#resource != null) //nullcheck skipped if Expression is provably non-null
1690      *           try {
1691      *               #resource.close();
1692      *           } catch (Throwable #suppressedException) {
1693      *              #primaryException.addSuppressed(#suppressedException);
1694      *           }
1695      *       throw #primaryException;
1696      *   }
1697      * }
1698      *
1699      * @param tree  The try statement to inspect.
1700      * @return a desugared try-with-resources tree, or the original
1701      * try block if there are no resources to manage.
1702      */
1703     JCTree makeTwrTry(JCTry tree) {
1704         make_at(tree.pos());
1705         twrVars = twrVars.dup();
1706         JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0);
1707         if (tree.catchers.isEmpty() && tree.finalizer == null)
1708             result = translate(twrBlock);
1709         else
1710             result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
1711         twrVars = twrVars.leave();
1712         return result;
1713     }
1714 
1715     private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) {
1716         if (resources.isEmpty())
1717             return block;
1718 
1719         // Add resource declaration or expression to block statements
1720         ListBuffer<JCStatement> stats = new ListBuffer<>();
1721         JCTree resource = resources.head;
1722         JCExpression resourceUse;
1723         boolean resourceNonNull;
1724         if (resource instanceof JCVariableDecl variableDecl) {
1725             resourceUse = make.Ident(variableDecl.sym).setType(resource.type);
1726             resourceNonNull = variableDecl.init != null && TreeInfo.skipParens(variableDecl.init).hasTag(NEWCLASS);
1727             stats.add(variableDecl);
1728         } else {
1729             Assert.check(resource instanceof JCExpression);
1730             VarSymbol syntheticTwrVar =
1731             new VarSymbol(SYNTHETIC | FINAL,
1732                           makeSyntheticName(names.fromString("twrVar" +
1733                                            depth), twrVars),
1734                           (resource.type.hasTag(BOT)) ?
1735                           syms.autoCloseableType : resource.type,
1736                           currentMethodSym);
1737             twrVars.enter(syntheticTwrVar);
1738             JCVariableDecl syntheticTwrVarDecl =
1739                 make.VarDef(syntheticTwrVar, (JCExpression)resource);
1740             resourceUse = (JCExpression)make.Ident(syntheticTwrVar);
1741             resourceNonNull = false;
1742             stats.add(syntheticTwrVarDecl);
1743         }
1744 
1745         //create (semi-) finally block that will be copied into the main try body:
1746         int oldPos = make.pos;
1747         make.at(TreeInfo.endPos(block));
1748 
1749         // if (#resource != null) { #resource.close(); }
1750         JCStatement bodyCloseStatement = makeResourceCloseInvocation(resourceUse);
1751 
1752         if (!resourceNonNull) {
1753             bodyCloseStatement = make.If(makeNonNullCheck(resourceUse),
1754                                          bodyCloseStatement,
1755                                          null);
1756         }
1757 
1758         JCBlock finallyClause = make.Block(BODY_ONLY_FINALIZE, List.of(bodyCloseStatement));
1759         make.at(oldPos);
1760 
1761         // Create catch clause that saves exception, closes the resource and then rethrows the exception:
1762         VarSymbol primaryException =
1763             new VarSymbol(FINAL|SYNTHETIC,
1764                           names.fromString("t" +
1765                                            target.syntheticNameChar()),
1766                           syms.throwableType,
1767                           currentMethodSym);
1768         JCVariableDecl primaryExceptionDecl = make.VarDef(primaryException, null);
1769 
1770         // close resource:
1771         // try {
1772         //     #resource.close();
1773         // } catch (Throwable #suppressedException) {
1774         //     #primaryException.addSuppressed(#suppressedException);
1775         // }
1776         VarSymbol suppressedException =
1777             new VarSymbol(SYNTHETIC, make.paramName(2),
1778                           syms.throwableType,
1779                           currentMethodSym);
1780         JCStatement addSuppressedStatement =
1781             make.Exec(makeCall(make.Ident(primaryException),
1782                                names.addSuppressed,
1783                                List.of(make.Ident(suppressedException))));
1784         JCBlock closeResourceTryBlock =
1785             make.Block(0L, List.of(makeResourceCloseInvocation(resourceUse)));
1786         JCVariableDecl catchSuppressedDecl = make.VarDef(suppressedException, null);
1787         JCBlock catchSuppressedBlock = make.Block(0L, List.of(addSuppressedStatement));
1788         List<JCCatch> catchSuppressedClauses =
1789                 List.of(make.Catch(catchSuppressedDecl, catchSuppressedBlock));
1790         JCTry closeResourceTry = make.Try(closeResourceTryBlock, catchSuppressedClauses, null);
1791         closeResourceTry.finallyCanCompleteNormally = true;
1792 
1793         JCStatement exceptionalCloseStatement = closeResourceTry;
1794 
1795         if (!resourceNonNull) {
1796             // if (#resource != null) {  }
1797             exceptionalCloseStatement = make.If(makeNonNullCheck(resourceUse),
1798                                                 exceptionalCloseStatement,
1799                                                 null);
1800         }
1801 
1802         JCStatement exceptionalRethrow = make.Throw(make.Ident(primaryException));
1803         JCBlock exceptionalCloseBlock = make.Block(0L, List.of(exceptionalCloseStatement, exceptionalRethrow));
1804         JCCatch exceptionalCatchClause = make.Catch(primaryExceptionDecl, exceptionalCloseBlock);
1805 
1806         //create the main try statement with the close:
1807         JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1),
1808                                   List.of(exceptionalCatchClause),
1809                                   finallyClause);
1810 
1811         outerTry.finallyCanCompleteNormally = true;
1812         stats.add(outerTry);
1813 
1814         JCBlock newBlock = make.Block(0L, stats.toList());
1815         return newBlock;
1816     }
1817 
1818     private JCStatement makeResourceCloseInvocation(JCExpression resource) {
1819         // convert to AutoCloseable if needed
1820         if (types.asSuper(resource.type.referenceProjectionOrSelf(), syms.autoCloseableType.tsym) == null) {
1821             resource = convert(resource, syms.autoCloseableType);
1822         }
1823 
1824         // create resource.close() method invocation
1825         JCExpression resourceClose = makeCall(resource,
1826                                               names.close,
1827                                               List.nil());
1828         return make.Exec(resourceClose);
1829     }
1830 
1831     private JCExpression makeNonNullCheck(JCExpression expression) {
1832         return makeBinary(NE, expression, makeNull());
1833     }
1834 
1835     /** Construct a tree that represents the outer instance
1836      *  {@code C.this}. Never pick the current `this'.
1837      *  @param pos           The source code position to be used for the tree.
1838      *  @param c             The qualifier class.
1839      */
1840     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1841         List<VarSymbol> ots = outerThisStack;
1842         if (ots.isEmpty()) {
1843             log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1844             Assert.error();
1845             return makeNull();
1846         }
1847         VarSymbol ot = ots.head;
1848         JCExpression tree = access(make.at(pos).Ident(ot));
1849         ot.flags_field &= ~NOOUTERTHIS;
1850         TypeSymbol otc = ot.type.tsym;
1851         while (otc != c) {
1852             do {
1853                 ots = ots.tail;
1854                 if (ots.isEmpty()) {
1855                     log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1856                     Assert.error(); // should have been caught in Attr
1857                     return tree;
1858                 }
1859                 ot = ots.head;
1860             } while (ot.owner != otc);
1861             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1862                 chk.earlyRefError(pos, c);
1863                 Assert.error(); // should have been caught in Attr
1864                 return makeNull();
1865             }
1866             tree = access(make.at(pos).Select(tree, ot));
1867             ot.flags_field &= ~NOOUTERTHIS;
1868             otc = ot.type.tsym;
1869         }
1870         return tree;
1871     }
1872 
1873     /** Construct a tree that represents the closest outer instance
1874      *  {@code C.this} such that the given symbol is a member of C.
1875      *  @param pos           The source code position to be used for the tree.
1876      *  @param sym           The accessed symbol.
1877      *  @param preciseMatch  should we accept a type that is a subtype of
1878      *                       sym's owner, even if it doesn't contain sym
1879      *                       due to hiding, overriding, or non-inheritance
1880      *                       due to protection?
1881      */
1882     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1883         Symbol c = sym.owner;
1884         if (preciseMatch ? sym.isMemberOf(currentClass, types)
1885                          : currentClass.isSubClass(sym.owner, types)) {
1886             // in this case, `this' works fine
1887             return make.at(pos).This(c.erasure(types));
1888         } else {
1889             // need to go via this$n
1890             return makeOwnerThisN(pos, sym, preciseMatch);
1891         }
1892     }
1893 
1894     /**
1895      * Similar to makeOwnerThis but will never pick "this".
1896      */
1897     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1898         Symbol c = sym.owner;
1899         List<VarSymbol> ots = outerThisStack;
1900         if (ots.isEmpty()) {
1901             log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1902             Assert.error();
1903             return makeNull();
1904         }
1905         VarSymbol ot = ots.head;
1906         JCExpression tree = access(make.at(pos).Ident(ot));
1907         ot.flags_field &= ~NOOUTERTHIS;
1908         TypeSymbol otc = ot.type.tsym;
1909         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1910             do {
1911                 ots = ots.tail;
1912                 if (ots.isEmpty()) {
1913                     log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1914                     Assert.error();
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 | IDENTITY_TYPE, 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 | IDENTITY_TYPE, 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 :
2205                 applyPrimitiveConversionsAsNeeded(boxIfNeeded(translate(tree), type), type);
2206     }
2207 
2208     /** Visitor method: Translate tree.
2209      */
2210     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2211         JCExpression prevEnclOp = this.enclOp;
2212         this.enclOp = enclOp;
2213         T res = translate(tree);
2214         this.enclOp = prevEnclOp;
2215         return res;
2216     }
2217 
2218     /** Visitor method: Translate list of trees.
2219      */
2220     public <T extends JCExpression> List<T> translate(List<T> trees, Type type) {
2221         if (trees == null) return null;
2222         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2223             l.head = translate(l.head, type);
2224         return trees;
2225     }
2226 
2227     public void visitPackageDef(JCPackageDecl tree) {
2228         if (!needPackageInfoClass(tree))
2229                         return;
2230 
2231         long flags = Flags.ABSTRACT | Flags.INTERFACE;
2232         // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2233         flags = flags | Flags.SYNTHETIC;
2234         ClassSymbol c = tree.packge.package_info;
2235         c.setAttributes(tree.packge);
2236         c.flags_field |= flags;
2237         ClassType ctype = (ClassType) c.type;
2238         ctype.supertype_field = syms.objectType;
2239         ctype.interfaces_field = List.nil();
2240         createInfoClass(tree.annotations, c);
2241     }
2242     // where
2243     private boolean needPackageInfoClass(JCPackageDecl pd) {
2244         switch (pkginfoOpt) {
2245             case ALWAYS:
2246                 return true;
2247             case LEGACY:
2248                 return pd.getAnnotations().nonEmpty();
2249             case NONEMPTY:
2250                 for (Attribute.Compound a :
2251                          pd.packge.getDeclarationAttributes()) {
2252                     Attribute.RetentionPolicy p = types.getRetention(a);
2253                     if (p != Attribute.RetentionPolicy.SOURCE)
2254                         return true;
2255                 }
2256                 return false;
2257         }
2258         throw new AssertionError();
2259     }
2260 
2261     public void visitModuleDef(JCModuleDecl tree) {
2262         ModuleSymbol msym = tree.sym;
2263         ClassSymbol c = msym.module_info;
2264         c.setAttributes(msym);
2265         c.flags_field |= Flags.MODULE;
2266         createInfoClass(List.nil(), tree.sym.module_info);
2267     }
2268 
2269     private void createInfoClass(List<JCAnnotation> annots, ClassSymbol c) {
2270         long flags = Flags.ABSTRACT | Flags.INTERFACE;
2271         JCClassDecl infoClass =
2272                 make.ClassDef(make.Modifiers(flags, annots),
2273                     c.name, List.nil(),
2274                     null, List.nil(), List.nil());
2275         infoClass.sym = c;
2276         translated.append(infoClass);
2277     }
2278 
2279     public void visitClassDef(JCClassDecl tree) {
2280         Env<AttrContext> prevEnv = attrEnv;
2281         ClassSymbol currentClassPrev = currentClass;
2282         MethodSymbol currentMethodSymPrev = currentMethodSym;
2283 
2284         currentClass = tree.sym;
2285         currentMethodSym = null;
2286         attrEnv = typeEnvs.remove(currentClass);
2287         if (attrEnv == null)
2288             attrEnv = prevEnv;
2289 
2290         classdefs.put(currentClass, tree);
2291 
2292         Map<Symbol, Symbol> prevProxies = proxies;
2293         proxies = new HashMap<>(proxies);
2294         List<VarSymbol> prevOuterThisStack = outerThisStack;
2295 
2296         // If this is an enum definition
2297         if ((tree.mods.flags & ENUM) != 0 &&
2298             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2299             visitEnumDef(tree);
2300 
2301         if ((tree.mods.flags & RECORD) != 0) {
2302             visitRecordDef(tree);
2303         }
2304 
2305         // If this is a nested class, define a this$n field for
2306         // it and add to proxies.
2307         JCVariableDecl otdef = null;
2308         if (currentClass.hasOuterInstance())
2309             otdef = outerThisDef(tree.pos, currentClass);
2310 
2311         // If this is a local class, define proxies for all its free variables.
2312         List<JCVariableDecl> fvdefs = freevarDefs(
2313             tree.pos, freevars(currentClass), currentClass);
2314 
2315         // Recursively translate superclass, interfaces.
2316         tree.extending = translate(tree.extending);
2317         tree.implementing = translate(tree.implementing);
2318 
2319         if (currentClass.isDirectlyOrIndirectlyLocal()) {
2320             ClassSymbol encl = currentClass.owner.enclClass();
2321             if (encl.trans_local == null) {
2322                 encl.trans_local = List.nil();
2323             }
2324             encl.trans_local = encl.trans_local.prepend(currentClass);
2325         }
2326 
2327         // Recursively translate members, taking into account that new members
2328         // might be created during the translation and prepended to the member
2329         // list `tree.defs'.
2330         List<JCTree> seen = List.nil();
2331         while (tree.defs != seen) {
2332             List<JCTree> unseen = tree.defs;
2333             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2334                 JCTree outermostMemberDefPrev = outermostMemberDef;
2335                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2336                 l.head = translate(l.head);
2337                 outermostMemberDef = outermostMemberDefPrev;
2338             }
2339             seen = unseen;
2340         }
2341 
2342         // Convert a protected modifier to public, mask static modifier.
2343         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2344         tree.mods.flags &= AdjustedClassFlags;
2345 
2346         // Convert name to flat representation, replacing '.' by '$'.
2347         tree.name = Convert.shortName(currentClass.flatName());
2348 
2349         // Add free variables proxy definitions to class.
2350 
2351         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2352             tree.defs = tree.defs.prepend(l.head);
2353             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2354         }
2355         // If this$n was accessed, add the field definition and
2356         // update initial constructors to initialize it
2357         if (currentClass.hasOuterInstance() && shouldEmitOuterThis(currentClass)) {
2358             tree.defs = tree.defs.prepend(otdef);
2359             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2360 
2361            for (JCTree def : tree.defs) {
2362                 if (TreeInfo.isInitialConstructor(def)) {
2363                   JCMethodDecl mdef = (JCMethodDecl) def;
2364                   mdef.body.stats = mdef.body.stats.prepend(
2365                       initOuterThis(mdef.body.pos, mdef.params.head.sym));
2366                 }
2367             }
2368         }
2369 
2370         proxies = prevProxies;
2371         outerThisStack = prevOuterThisStack;
2372 
2373         // Append translated tree to `translated' queue.
2374         translated.append(tree);
2375 
2376         attrEnv = prevEnv;
2377         currentClass = currentClassPrev;
2378         currentMethodSym = currentMethodSymPrev;
2379 
2380         // Return empty block {} as a placeholder for an inner class.
2381         result = make_at(tree.pos()).Block(SYNTHETIC, List.nil());
2382     }
2383 
2384     private boolean shouldEmitOuterThis(ClassSymbol sym) {
2385       if (!optimizeOuterThis) {
2386         // Optimization is disabled
2387         return true;
2388       }
2389       if ((outerThisStack.head.flags_field & NOOUTERTHIS) == 0)  {
2390         // Enclosing instance field is used
2391         return true;
2392       }
2393       if (rs.isSerializable(sym.type)) {
2394         // Class is serializable
2395         return true;
2396       }
2397       return false;
2398     }
2399 
2400     List<JCTree> generateMandatedAccessors(JCClassDecl tree) {
2401         List<JCVariableDecl> fields = TreeInfo.recordFields(tree);
2402         return tree.sym.getRecordComponents().stream()
2403                 .filter(rc -> (rc.accessor.flags() & Flags.GENERATED_MEMBER) != 0)
2404                 .map(rc -> {
2405                     // we need to return the field not the record component
2406                     JCVariableDecl field = fields.stream().filter(f -> f.name == rc.name).findAny().get();
2407                     make_at(tree.pos());
2408                     return make.MethodDef(rc.accessor, make.Block(0,
2409                             List.of(make.Return(make.Ident(field)))));
2410                 }).collect(List.collector());
2411     }
2412 
2413     /** Translate an enum class. */
2414     private void visitEnumDef(JCClassDecl tree) {
2415         make_at(tree.pos());
2416 
2417         // add the supertype, if needed
2418         if (tree.extending == null)
2419             tree.extending = make.Type(types.supertype(tree.type));
2420 
2421         // classOfType adds a cache field to tree.defs
2422         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2423             setType(types.erasure(syms.classType));
2424 
2425         // process each enumeration constant, adding implicit constructor parameters
2426         int nextOrdinal = 0;
2427         ListBuffer<JCExpression> values = new ListBuffer<>();
2428         ListBuffer<JCTree> enumDefs = new ListBuffer<>();
2429         ListBuffer<JCTree> otherDefs = new ListBuffer<>();
2430         for (List<JCTree> defs = tree.defs;
2431              defs.nonEmpty();
2432              defs=defs.tail) {
2433             if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2434                 JCVariableDecl var = (JCVariableDecl)defs.head;
2435                 visitEnumConstantDef(var, nextOrdinal++);
2436                 values.append(make.QualIdent(var.sym));
2437                 enumDefs.append(var);
2438             } else {
2439                 otherDefs.append(defs.head);
2440             }
2441         }
2442 
2443         // synthetic private static T[] $values() { return new T[] { a, b, c }; }
2444         // synthetic private static final T[] $VALUES = $values();
2445         Name valuesName = syntheticName(tree, "VALUES");
2446         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2447         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2448                                             valuesName,
2449                                             arrayType,
2450                                             tree.type.tsym);
2451         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2452                                           List.nil(),
2453                                           values.toList());
2454         newArray.type = arrayType;
2455 
2456         MethodSymbol valuesMethod = new MethodSymbol(PRIVATE|STATIC|SYNTHETIC,
2457                 syntheticName(tree, "values"),
2458                 new MethodType(List.nil(), arrayType, List.nil(), tree.type.tsym),
2459                 tree.type.tsym);
2460         enumDefs.append(make.MethodDef(valuesMethod, make.Block(0, List.of(make.Return(newArray)))));
2461         tree.sym.members().enter(valuesMethod);
2462 
2463         enumDefs.append(make.VarDef(valuesVar, make.App(make.QualIdent(valuesMethod))));
2464         tree.sym.members().enter(valuesVar);
2465 
2466         MethodSymbol valuesSym = lookupMethod(tree.pos(), names.values,
2467                                         tree.type, List.nil());
2468         List<JCStatement> valuesBody;
2469         if (useClone()) {
2470             // return (T[]) $VALUES.clone();
2471             JCTypeCast valuesResult =
2472                 make.TypeCast(valuesSym.type.getReturnType(),
2473                               make.App(make.Select(make.Ident(valuesVar),
2474                                                    syms.arrayCloneMethod)));
2475             valuesBody = List.of(make.Return(valuesResult));
2476         } else {
2477             // template: T[] $result = new T[$values.length];
2478             Name resultName = syntheticName(tree, "result");
2479             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2480                                                 resultName,
2481                                                 arrayType,
2482                                                 valuesSym);
2483             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2484                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2485                                   null);
2486             resultArray.type = arrayType;
2487             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2488 
2489             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2490             if (systemArraycopyMethod == null) {
2491                 systemArraycopyMethod =
2492                     new MethodSymbol(PUBLIC | STATIC,
2493                                      names.fromString("arraycopy"),
2494                                      new MethodType(List.of(syms.objectType,
2495                                                             syms.intType,
2496                                                             syms.objectType,
2497                                                             syms.intType,
2498                                                             syms.intType),
2499                                                     syms.voidType,
2500                                                     List.nil(),
2501                                                     syms.methodClass),
2502                                      syms.systemType.tsym);
2503             }
2504             JCStatement copy =
2505                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2506                                                systemArraycopyMethod),
2507                           List.of(make.Ident(valuesVar), make.Literal(0),
2508                                   make.Ident(resultVar), make.Literal(0),
2509                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
2510 
2511             // template: return $result;
2512             JCStatement ret = make.Return(make.Ident(resultVar));
2513             valuesBody = List.of(decl, copy, ret);
2514         }
2515 
2516         JCMethodDecl valuesDef =
2517              make.MethodDef(valuesSym, make.Block(0, valuesBody));
2518 
2519         enumDefs.append(valuesDef);
2520 
2521         if (debugLower)
2522             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2523 
2524         /** The template for the following code is:
2525          *
2526          *     public static E valueOf(String name) {
2527          *         return (E)Enum.valueOf(E.class, name);
2528          *     }
2529          *
2530          *  where E is tree.sym
2531          */
2532         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2533                          names.valueOf,
2534                          tree.sym.type,
2535                          List.of(syms.stringType));
2536         Assert.check((valueOfSym.flags() & STATIC) != 0);
2537         VarSymbol nameArgSym = valueOfSym.params.head;
2538         JCIdent nameVal = make.Ident(nameArgSym);
2539         JCStatement enum_ValueOf =
2540             make.Return(make.TypeCast(tree.sym.type,
2541                                       makeCall(make.Ident(syms.enumSym),
2542                                                names.valueOf,
2543                                                List.of(e_class, nameVal))));
2544         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2545                                            make.Block(0, List.of(enum_ValueOf)));
2546         nameVal.sym = valueOf.params.head.sym;
2547         if (debugLower)
2548             System.err.println(tree.sym + ".valueOf = " + valueOf);
2549         enumDefs.append(valueOf);
2550 
2551         enumDefs.appendList(otherDefs.toList());
2552         tree.defs = enumDefs.toList();
2553     }
2554         // where
2555         private MethodSymbol systemArraycopyMethod;
2556         private boolean useClone() {
2557             try {
2558                 return syms.objectType.tsym.members().findFirst(names.clone) != null;
2559             }
2560             catch (CompletionFailure e) {
2561                 return false;
2562             }
2563         }
2564 
2565         private Name syntheticName(JCClassDecl tree, String baseName) {
2566             Name valuesName = names.fromString(target.syntheticNameChar() + baseName);
2567             while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash
2568                 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2569             return valuesName;
2570         }
2571 
2572     /** Translate an enumeration constant and its initializer. */
2573     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2574         JCNewClass varDef = (JCNewClass)var.init;
2575         varDef.args = varDef.args.
2576             prepend(makeLit(syms.intType, ordinal)).
2577             prepend(makeLit(syms.stringType, var.name.toString()));
2578     }
2579 
2580     private List<VarSymbol> recordVars(Type t) {
2581         List<VarSymbol> vars = List.nil();
2582         while (!t.hasTag(NONE)) {
2583             if (t.hasTag(CLASS)) {
2584                 for (Symbol s : t.tsym.members().getSymbols(s -> s.kind == VAR && (s.flags() & RECORD) != 0)) {
2585                     vars = vars.prepend((VarSymbol)s);
2586                 }
2587             }
2588             t = types.supertype(t);
2589         }
2590         return vars;
2591     }
2592 
2593     /** Translate a record. */
2594     private void visitRecordDef(JCClassDecl tree) {
2595         make_at(tree.pos());
2596         List<VarSymbol> vars = recordVars(tree.type);
2597         MethodHandleSymbol[] getterMethHandles = new MethodHandleSymbol[vars.size()];
2598         int index = 0;
2599         for (VarSymbol var : vars) {
2600             if (var.owner != tree.sym) {
2601                 var = new VarSymbol(var.flags_field, var.name, var.type, tree.sym);
2602             }
2603             getterMethHandles[index] = var.asMethodHandle(true);
2604             index++;
2605         }
2606 
2607         tree.defs = tree.defs.appendList(generateMandatedAccessors(tree));
2608         tree.defs = tree.defs.appendList(List.of(
2609                 generateRecordMethod(tree, names.toString, vars, getterMethHandles),
2610                 generateRecordMethod(tree, names.hashCode, vars, getterMethHandles),
2611                 generateRecordMethod(tree, names.equals, vars, getterMethHandles)
2612         ));
2613     }
2614 
2615     JCTree generateRecordMethod(JCClassDecl tree, Name name, List<VarSymbol> vars, MethodHandleSymbol[] getterMethHandles) {
2616         make_at(tree.pos());
2617         boolean isEquals = name == names.equals;
2618         MethodSymbol msym = lookupMethod(tree.pos(),
2619                 name,
2620                 tree.sym.type,
2621                 isEquals ? List.of(syms.objectType) : List.nil());
2622         // compiler generated methods have the record flag set, user defined ones dont
2623         if ((msym.flags() & RECORD) != 0) {
2624             /* class java.lang.runtime.ObjectMethods provides a common bootstrap that provides a customized implementation
2625              * for methods: toString, hashCode and equals. Here we just need to generate and indy call to:
2626              * java.lang.runtime.ObjectMethods::bootstrap and provide: the record class, the record component names and
2627              * the accessors.
2628              */
2629             Name bootstrapName = names.bootstrap;
2630             LoadableConstant[] staticArgsValues = new LoadableConstant[2 + getterMethHandles.length];
2631             staticArgsValues[0] = (ClassType)tree.sym.type;
2632             String concatNames = vars.stream()
2633                     .map(v -> v.name)
2634                     .collect(Collectors.joining(";", "", ""));
2635             staticArgsValues[1] = LoadableConstant.String(concatNames);
2636             int index = 2;
2637             for (MethodHandleSymbol mho : getterMethHandles) {
2638                 staticArgsValues[index] = mho;
2639                 index++;
2640             }
2641 
2642             List<Type> staticArgTypes = List.of(syms.classType,
2643                     syms.stringType,
2644                     new ArrayType(syms.methodHandleType, syms.arrayClass));
2645 
2646             JCFieldAccess qualifier = makeIndyQualifier(syms.objectMethodsType, tree, msym,
2647                     List.of(syms.methodHandleLookupType,
2648                             syms.stringType,
2649                             syms.typeDescriptorType).appendList(staticArgTypes),
2650                     staticArgsValues, bootstrapName, name, false);
2651 
2652             VarSymbol _this = new VarSymbol(SYNTHETIC, names._this, tree.sym.type, tree.sym);
2653 
2654             JCMethodInvocation proxyCall;
2655             if (!isEquals) {
2656                 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this)));
2657             } else {
2658                 VarSymbol o = msym.params.head;
2659                 o.adr = 0;
2660                 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this), make.Ident(o)));
2661             }
2662             proxyCall.type = qualifier.type;
2663             return make.MethodDef(msym, make.Block(0, List.of(make.Return(proxyCall))));
2664         } else {
2665             return make.Block(SYNTHETIC, List.nil());
2666         }
2667     }
2668 
2669     private String argsTypeSig(List<Type> typeList) {
2670         LowerSignatureGenerator sg = new LowerSignatureGenerator();
2671         sg.assembleSig(typeList);
2672         return sg.toString();
2673     }
2674 
2675     /**
2676      * Signature Generation
2677      */
2678     private class LowerSignatureGenerator extends Types.SignatureGenerator {
2679 
2680         /**
2681          * An output buffer for type signatures.
2682          */
2683         StringBuilder sb = new StringBuilder();
2684 
2685         LowerSignatureGenerator() {
2686             super(types);
2687         }
2688 
2689         @Override
2690         protected void append(char ch) {
2691             sb.append(ch);
2692         }
2693 
2694         @Override
2695         protected void append(byte[] ba) {
2696             sb.append(new String(ba));
2697         }
2698 
2699         @Override
2700         protected void append(Name name) {
2701             sb.append(name.toString());
2702         }
2703 
2704         @Override
2705         public String toString() {
2706             return sb.toString();
2707         }
2708     }
2709 
2710     /**
2711      * Creates an indy qualifier, helpful to be part of an indy invocation
2712      * @param site                the site
2713      * @param tree                a class declaration tree
2714      * @param msym                the method symbol
2715      * @param staticArgTypes      the static argument types
2716      * @param staticArgValues     the static argument values
2717      * @param bootstrapName       the bootstrap name to look for
2718      * @param argName             normally bootstraps receives a method name as second argument, if you want that name
2719      *                            to be different to that of the bootstrap name pass a different name here
2720      * @param isStatic            is it static or not
2721      * @return                    a field access tree
2722      */
2723     JCFieldAccess makeIndyQualifier(
2724             Type site,
2725             JCClassDecl tree,
2726             MethodSymbol msym,
2727             List<Type> staticArgTypes,
2728             LoadableConstant[] staticArgValues,
2729             Name bootstrapName,
2730             Name argName,
2731             boolean isStatic) {
2732         MethodSymbol bsm = rs.resolveInternalMethod(tree.pos(), attrEnv, site,
2733                 bootstrapName, staticArgTypes, List.nil());
2734 
2735         MethodType indyType = msym.type.asMethodType();
2736         indyType = new MethodType(
2737                 isStatic ? List.nil() : indyType.argtypes.prepend(tree.sym.type),
2738                 indyType.restype,
2739                 indyType.thrown,
2740                 syms.methodClass
2741         );
2742         DynamicMethodSymbol dynSym = new DynamicMethodSymbol(argName,
2743                 syms.noSymbol,
2744                 bsm.asHandle(),
2745                 indyType,
2746                 staticArgValues);
2747         JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), argName);
2748         qualifier.sym = dynSym;
2749         qualifier.type = msym.type.asMethodType().restype;
2750         return qualifier;
2751     }
2752 
2753     public void visitMethodDef(JCMethodDecl tree) {
2754         // TODO - enum so is always <init>
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 (names.isInitOrVNew(tree.name) &&
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             // If this is an initial constructor, i.e., it does not start with
2832             // this(...), insert initializers for this$n and proxies
2833             // before (pre-1.4, after) the call to superclass constructor.
2834             JCStatement selfCall = translate(tree.body.stats.head);
2835 
2836             List<JCStatement> added = List.nil();
2837             if (fvs.nonEmpty()) {
2838                 List<Type> addedargtypes = List.nil();
2839                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2840                     m.capturedLocals =
2841                         m.capturedLocals.prepend((VarSymbol)
2842                                                 (proxies.get(l.head)));
2843                     if (TreeInfo.isInitialConstructor(tree)) {
2844                         added = added.prepend(
2845                           initField(tree.body.pos, proxies.get(l.head), prevProxies.get(l.head)));
2846                     }
2847                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2848                 }
2849                 Type olderasure = m.erasure(types);
2850                 m.erasure_field = new MethodType(
2851                     olderasure.getParameterTypes().appendList(addedargtypes),
2852                     olderasure.getReturnType(),
2853                     olderasure.getThrownTypes(),
2854                     syms.methodClass);
2855             }
2856 
2857             // pop local variables from proxy stack
2858             proxies = prevProxies;
2859 
2860             // recursively translate following local statements and
2861             // combine with this- or super-call
2862             List<JCStatement> stats = translate(tree.body.stats.tail);
2863             tree.body.stats = stats.prepend(selfCall).prependList(added);
2864             outerThisStack = prevOuterThisStack;
2865         } else {
2866             Map<Symbol, Symbol> prevLambdaTranslationMap =
2867                     lambdaTranslationMap;
2868             try {
2869                 lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
2870                         tree.sym.name.startsWith(names.lambda) ?
2871                         makeTranslationMap(tree) : null;
2872                 super.visitMethodDef(tree);
2873             } finally {
2874                 lambdaTranslationMap = prevLambdaTranslationMap;
2875             }
2876         }
2877         if (names.isInitOrVNew(tree.name) && ((tree.sym.flags_field & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0 ||
2878                 (tree.sym.flags_field & (GENERATEDCONSTR | RECORD)) == (GENERATEDCONSTR | RECORD))) {
2879             // lets find out if there is any field waiting to be initialized
2880             ListBuffer<VarSymbol> fields = new ListBuffer<>();
2881             for (Symbol sym : currentClass.getEnclosedElements()) {
2882                 if (sym.kind == Kinds.Kind.VAR && ((sym.flags() & RECORD) != 0))
2883                     fields.append((VarSymbol) sym);
2884             }
2885             for (VarSymbol field: fields) {
2886                 if ((field.flags_field & Flags.UNINITIALIZED_FIELD) != 0) {
2887                     VarSymbol param = tree.params.stream().filter(p -> p.name == field.name).findFirst().get().sym;
2888                     make.at(tree.pos);
2889                     tree.body.stats = tree.body.stats.append(
2890                             make.Exec(
2891                                     make.Assign(
2892                                             make.Select(make.This(field.owner.erasure(types)), field),
2893                                             make.Ident(param)).setType(field.erasure(types))));
2894                     // we don't need the flag at the field anymore
2895                     field.flags_field &= ~Flags.UNINITIALIZED_FIELD;
2896                 }
2897             }
2898         }
2899         result = tree;
2900     }
2901     //where
2902         private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
2903             Map<Symbol, Symbol> translationMap = new HashMap<>();
2904             for (JCVariableDecl vd : tree.params) {
2905                 Symbol p = vd.sym;
2906                 if (p != p.baseSymbol()) {
2907                     translationMap.put(p.baseSymbol(), p);
2908                 }
2909             }
2910             return translationMap;
2911         }
2912 
2913     public void visitTypeCast(JCTypeCast tree) {
2914         tree.clazz = translate(tree.clazz);
2915         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2916             tree.expr = translate(tree.expr, tree.type);
2917         else
2918             tree.expr = translate(tree.expr);
2919         result = tree;
2920     }
2921 
2922     public void visitNewClass(JCNewClass tree) {
2923         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2924 
2925         // Box arguments, if necessary
2926         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2927         List<Type> argTypes = tree.constructor.type.getParameterTypes();
2928         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2929         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2930         tree.varargsElement = null;
2931 
2932         // If created class is local, add free variables after
2933         // explicit constructor arguments.
2934         if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) {
2935             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2936         }
2937 
2938         // If an access constructor is used, append null as a last argument.
2939         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2940         if (constructor != tree.constructor) {
2941             tree.args = tree.args.append(makeNull());
2942             tree.constructor = constructor;
2943         }
2944 
2945         // If created class has an outer instance, and new is qualified, pass
2946         // qualifier as first argument. If new is not qualified, pass the
2947         // correct outer instance as first argument.
2948         if (c.hasOuterInstance()) {
2949             JCExpression thisArg;
2950             if (tree.encl != null) {
2951                 thisArg = attr.makeNullCheck(translate(tree.encl));
2952                 thisArg.type = tree.encl.type;
2953             } else if (c.isDirectlyOrIndirectlyLocal()) {
2954                 // local class
2955                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2956             } else {
2957                 // nested class
2958                 thisArg = makeOwnerThis(tree.pos(), c, false);
2959             }
2960             tree.args = tree.args.prepend(thisArg);
2961         }
2962         tree.encl = null;
2963 
2964         // If we have an anonymous class, create its flat version, rather
2965         // than the class or interface following new.
2966         if (tree.def != null) {
2967             Map<Symbol, Symbol> prevLambdaTranslationMap = lambdaTranslationMap;
2968             try {
2969                 lambdaTranslationMap = null;
2970                 translate(tree.def);
2971             } finally {
2972                 lambdaTranslationMap = prevLambdaTranslationMap;
2973             }
2974 
2975             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2976             tree.def = null;
2977         } else {
2978             tree.clazz = access(c, tree.clazz, enclOp, false);
2979         }
2980         result = tree;
2981     }
2982 
2983     // Simplify conditionals with known constant controlling expressions.
2984     // This allows us to avoid generating supporting declarations for
2985     // the dead code, which will not be eliminated during code generation.
2986     // Note that Flow.isFalse and Flow.isTrue only return true
2987     // for constant expressions in the sense of JLS 15.27, which
2988     // are guaranteed to have no side-effects.  More aggressive
2989     // constant propagation would require that we take care to
2990     // preserve possible side-effects in the condition expression.
2991 
2992     // One common case is equality expressions involving a constant and null.
2993     // Since null is not a constant expression (because null cannot be
2994     // represented in the constant pool), equality checks involving null are
2995     // not captured by Flow.isTrue/isFalse.
2996     // Equality checks involving a constant and null, e.g.
2997     //     "" == null
2998     // are safe to simplify as no side-effects can occur.
2999 
3000     private boolean isTrue(JCTree exp) {
3001         if (exp.type.isTrue())
3002             return true;
3003         Boolean b = expValue(exp);
3004         return b == null ? false : b;
3005     }
3006     private boolean isFalse(JCTree exp) {
3007         if (exp.type.isFalse())
3008             return true;
3009         Boolean b = expValue(exp);
3010         return b == null ? false : !b;
3011     }
3012     /* look for (in)equality relations involving null.
3013      * return true - if expression is always true
3014      *       false - if expression is always false
3015      *        null - if expression cannot be eliminated
3016      */
3017     private Boolean expValue(JCTree exp) {
3018         while (exp.hasTag(PARENS))
3019             exp = ((JCParens)exp).expr;
3020 
3021         boolean eq;
3022         switch (exp.getTag()) {
3023         case EQ: eq = true;  break;
3024         case NE: eq = false; break;
3025         default:
3026             return null;
3027         }
3028 
3029         // we have a JCBinary(EQ|NE)
3030         // check if we have two literals (constants or null)
3031         JCBinary b = (JCBinary)exp;
3032         if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs);
3033         if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs);
3034         return null;
3035     }
3036     private Boolean expValueIsNull(boolean eq, JCTree t) {
3037         if (t.type.hasTag(BOT)) return Boolean.valueOf(eq);
3038         if (t.hasTag(LITERAL))  return Boolean.valueOf(!eq);
3039         return null;
3040     }
3041 
3042     /** Visitor method for conditional expressions.
3043      */
3044     @Override
3045     public void visitConditional(JCConditional tree) {
3046         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
3047         if (isTrue(cond)) {
3048             result = convert(translate(tree.truepart, tree.type), tree.type);
3049             addPrunedInfo(cond);
3050         } else if (isFalse(cond)) {
3051             result = convert(translate(tree.falsepart, tree.type), tree.type);
3052             addPrunedInfo(cond);
3053         } else {
3054             // Condition is not a compile-time constant.
3055             tree.truepart = translate(tree.truepart, tree.type);
3056             tree.falsepart = translate(tree.falsepart, tree.type);
3057             result = tree;
3058         }
3059     }
3060 //where
3061     private JCExpression convert(JCExpression tree, Type pt) {
3062         if (tree.type == pt || tree.type.hasTag(BOT))
3063             return tree;
3064         JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree);
3065         result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
3066                                                        : pt;
3067         return result;
3068     }
3069 
3070     /** Visitor method for if statements.
3071      */
3072     public void visitIf(JCIf tree) {
3073         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
3074         if (isTrue(cond)) {
3075             result = translate(tree.thenpart);
3076             addPrunedInfo(cond);
3077         } else if (isFalse(cond)) {
3078             if (tree.elsepart != null) {
3079                 result = translate(tree.elsepart);
3080             } else {
3081                 result = make.Skip();
3082             }
3083             addPrunedInfo(cond);
3084         } else {
3085             // Condition is not a compile-time constant.
3086             tree.thenpart = translate(tree.thenpart);
3087             tree.elsepart = translate(tree.elsepart);
3088             result = tree;
3089         }
3090     }
3091 
3092     /** Visitor method for assert statements. Translate them away.
3093      */
3094     public void visitAssert(JCAssert tree) {
3095         tree.cond = translate(tree.cond, syms.booleanType);
3096         if (!tree.cond.type.isTrue()) {
3097             JCExpression cond = assertFlagTest(tree.pos());
3098             List<JCExpression> exnArgs = (tree.detail == null) ?
3099                 List.nil() : List.of(translate(tree.detail));
3100             if (!tree.cond.type.isFalse()) {
3101                 cond = makeBinary
3102                     (AND,
3103                      cond,
3104                      makeUnary(NOT, tree.cond));
3105             }
3106             result =
3107                 make.If(cond,
3108                         make_at(tree).
3109                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
3110                         null);
3111         } else {
3112             result = make.Skip();
3113         }
3114     }
3115 
3116     public void visitApply(JCMethodInvocation tree) {
3117         Symbol meth = TreeInfo.symbol(tree.meth);
3118         List<Type> argtypes = meth.type.getParameterTypes();
3119         // TODO - is enum so always <init>.
3120         if (names.isInitOrVNew(meth.name) && meth.owner == syms.enumSym)
3121             argtypes = argtypes.tail.tail;
3122         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
3123         tree.varargsElement = null;
3124         Name methName = TreeInfo.name(tree.meth);
3125         if (names.isInitOrVNew(meth.name)) {
3126             // We are seeing a this(...) or super(...) constructor call.
3127             // If an access constructor is used, append null as a last argument.
3128             Symbol constructor = accessConstructor(tree.pos(), meth);
3129             if (constructor != meth) {
3130                 tree.args = tree.args.append(makeNull());
3131                 TreeInfo.setSymbol(tree.meth, constructor);
3132             }
3133 
3134             // If we are calling a constructor of a local class, add
3135             // free variables after explicit constructor arguments.
3136             ClassSymbol c = (ClassSymbol)constructor.owner;
3137             if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) {
3138                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
3139             }
3140 
3141             // If we are calling a constructor of an enum class, pass
3142             // along the name and ordinal arguments
3143             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
3144                 List<JCVariableDecl> params = currentMethodDef.params;
3145                 if (currentMethodSym.owner.hasOuterInstance())
3146                     params = params.tail; // drop this$n
3147                 tree.args = tree.args
3148                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
3149                     .prepend(make.Ident(params.head.sym)); // name
3150             }
3151 
3152             // If we are calling a constructor of a class with an outer
3153             // instance, and the call
3154             // is qualified, pass qualifier as first argument in front of
3155             // the explicit constructor arguments. If the call
3156             // is not qualified, pass the correct outer instance as
3157             // first argument. If we are a static class, there is no
3158             // such outer instance, so generate an error.
3159             if (c.hasOuterInstance()) {
3160                 JCExpression thisArg;
3161                 if (tree.meth.hasTag(SELECT)) {
3162                     thisArg = attr.
3163                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
3164                     tree.meth = make.Ident(constructor);
3165                     ((JCIdent) tree.meth).name = methName;
3166                 } else if (c.isDirectlyOrIndirectlyLocal() || methName == names._this){
3167                     // local class or this() call
3168                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
3169                 } else if (currentClass.isStatic()) {
3170                     // super() call from static nested class - invalid
3171                     log.error(tree.pos(),
3172                         Errors.NoEnclInstanceOfTypeInScope(c.type.getEnclosingType().tsym));
3173                     thisArg = make.Literal(BOT, null).setType(syms.botType);
3174                 } else {
3175                     // super() call of nested class - never pick 'this'
3176                     thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
3177                 }
3178                 tree.args = tree.args.prepend(thisArg);
3179             }
3180         } else {
3181             // We are seeing a normal method invocation; translate this as usual.
3182             tree.meth = translate(tree.meth);
3183 
3184             // If the translated method itself is an Apply tree, we are
3185             // seeing an access method invocation. In this case, append
3186             // the method arguments to the arguments of the access method.
3187             if (tree.meth.hasTag(APPLY)) {
3188                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3189                 app.args = tree.args.prependList(app.args);
3190                 result = app;
3191                 return;
3192             }
3193         }
3194         result = tree;
3195     }
3196 
3197     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3198         List<JCExpression> args = _args;
3199         if (parameters.isEmpty()) return args;
3200         boolean anyChanges = false;
3201         ListBuffer<JCExpression> result = new ListBuffer<>();
3202         while (parameters.tail.nonEmpty()) {
3203             JCExpression arg = translate(args.head, parameters.head);
3204             anyChanges |= (arg != args.head);
3205             result.append(arg);
3206             args = args.tail;
3207             parameters = parameters.tail;
3208         }
3209         Type parameter = parameters.head;
3210         if (varargsElement != null) {
3211             anyChanges = true;
3212             ListBuffer<JCExpression> elems = new ListBuffer<>();
3213             while (args.nonEmpty()) {
3214                 JCExpression arg = translate(args.head, varargsElement);
3215                 elems.append(arg);
3216                 args = args.tail;
3217             }
3218             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3219                                                List.nil(),
3220                                                elems.toList());
3221             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3222             result.append(boxedArgs);
3223         } else {
3224             if (args.length() != 1) throw new AssertionError(args);
3225             JCExpression arg = translate(args.head, parameter);
3226             anyChanges |= (arg != args.head);
3227             result.append(arg);
3228             if (!anyChanges) return _args;
3229         }
3230         return result.toList();
3231     }
3232 
3233     /** Apply primitive value/reference conversions as needed */
3234     @SuppressWarnings("unchecked")
3235     <T extends JCExpression> T applyPrimitiveConversionsAsNeeded(T tree, Type type) {
3236         boolean haveValue = tree.type.isPrimitiveClass();
3237         if (haveValue == type.isPrimitiveClass())
3238             return tree;
3239         // For narrowing conversion, insert a cast which should trigger a null check
3240         // For widening conversions, insert a cast if emitting a unified class file.
3241         return (T) make.TypeCast(type, tree);
3242     }
3243 
3244     /** Expand a boxing or unboxing conversion if needed. */
3245     @SuppressWarnings("unchecked") // XXX unchecked
3246     <T extends JCExpression> T boxIfNeeded(T tree, Type type) {
3247         boolean havePrimitive = tree.type.isPrimitive();
3248         if (havePrimitive == type.isPrimitive())
3249             return tree;
3250         if (havePrimitive) {
3251             Type unboxedTarget = types.unboxedType(type);
3252             if (!unboxedTarget.hasTag(NONE)) {
3253                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3254                     tree.type = unboxedTarget.constType(tree.type.constValue());
3255                 return (T)boxPrimitive(tree, types.erasure(type));
3256             } else {
3257                 tree = (T)boxPrimitive(tree);
3258             }
3259         } else {
3260             tree = (T)unbox(tree, type);
3261         }
3262         return tree;
3263     }
3264 
3265     /** Box up a single primitive expression. */
3266     JCExpression boxPrimitive(JCExpression tree) {
3267         return boxPrimitive(tree, types.boxedClass(tree.type).type);
3268     }
3269 
3270     /** Box up a single primitive expression. */
3271     JCExpression boxPrimitive(JCExpression tree, Type box) {
3272         make_at(tree.pos());
3273         Symbol valueOfSym = lookupMethod(tree.pos(),
3274                                          names.valueOf,
3275                                          box,
3276                                          List.<Type>nil()
3277                                          .prepend(tree.type));
3278         return make.App(make.QualIdent(valueOfSym), List.of(tree));
3279     }
3280 
3281     /** Unbox an object to a primitive value. */
3282     JCExpression unbox(JCExpression tree, Type primitive) {
3283         Type unboxedType = types.unboxedType(tree.type);
3284         if (unboxedType.hasTag(NONE)) {
3285             unboxedType = primitive;
3286             if (!unboxedType.isPrimitive())
3287                 throw new AssertionError(unboxedType);
3288             make_at(tree.pos());
3289             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3290         } else {
3291             // There must be a conversion from unboxedType to primitive.
3292             if (!types.isSubtype(unboxedType, primitive))
3293                 throw new AssertionError(tree);
3294         }
3295         make_at(tree.pos());
3296         Symbol valueSym = lookupMethod(tree.pos(),
3297                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
3298                                        tree.type,
3299                                        List.nil());
3300         return make.App(make.Select(tree, valueSym));
3301     }
3302 
3303     /** Visitor method for parenthesized expressions.
3304      *  If the subexpression has changed, omit the parens.
3305      */
3306     public void visitParens(JCParens tree) {
3307         JCTree expr = translate(tree.expr);
3308         result = ((expr == tree.expr) ? tree : expr);
3309     }
3310 
3311     public void visitIndexed(JCArrayAccess tree) {
3312         tree.indexed = translate(tree.indexed);
3313         tree.index = translate(tree.index, syms.intType);
3314         result = tree;
3315     }
3316 
3317     public void visitAssign(JCAssign tree) {
3318         tree.lhs = translate(tree.lhs, tree);
3319         tree.rhs = translate(tree.rhs, tree.lhs.type);
3320 
3321         // If translated left hand side is an Apply, we are
3322         // seeing an access method invocation. In this case, append
3323         // right hand side as last argument of the access method.
3324         if (tree.lhs.hasTag(APPLY)) {
3325             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3326             app.args = List.of(tree.rhs).prependList(app.args);
3327             result = app;
3328         } else {
3329             result = tree;
3330         }
3331     }
3332 
3333     public void visitAssignop(final JCAssignOp tree) {
3334         final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3335             tree.operator.type.getReturnType().isPrimitive();
3336 
3337         AssignopDependencyScanner depScanner = new AssignopDependencyScanner(tree);
3338         depScanner.scan(tree.rhs);
3339 
3340         if (boxingReq || depScanner.dependencyFound) {
3341             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3342             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3343             // (but without recomputing x)
3344             JCTree newTree = abstractLval(tree.lhs, lhs -> {
3345                 Tag newTag = tree.getTag().noAssignOp();
3346                 // Erasure (TransTypes) can change the type of
3347                 // tree.lhs.  However, we can still get the
3348                 // unerased type of tree.lhs as it is stored
3349                 // in tree.type in Attr.
3350                 OperatorSymbol newOperator = operators.resolveBinary(tree,
3351                                                               newTag,
3352                                                               tree.type,
3353                                                               tree.rhs.type);
3354                 //Need to use the "lhs" at two places, once on the future left hand side
3355                 //and once in the future binary operator. But further processing may change
3356                 //the components of the tree in place (see visitSelect for e.g. <Class>.super.<ident>),
3357                 //so cloning the tree to avoid interference between the uses:
3358                 JCExpression expr = (JCExpression) lhs.clone();
3359                 if (expr.type != tree.type)
3360                     expr = make.TypeCast(tree.type, expr);
3361                 JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3362                 opResult.operator = newOperator;
3363                 opResult.type = newOperator.type.getReturnType();
3364                 JCExpression newRhs = boxingReq ?
3365                     make.TypeCast(types.unboxedType(tree.type), opResult) :
3366                     opResult;
3367                 return make.Assign(lhs, newRhs).setType(tree.type);
3368             });
3369             result = translate(newTree);
3370             return;
3371         }
3372         tree.lhs = translate(tree.lhs, tree);
3373         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3374 
3375         // If translated left hand side is an Apply, we are
3376         // seeing an access method invocation. In this case, append
3377         // right hand side as last argument of the access method.
3378         if (tree.lhs.hasTag(APPLY)) {
3379             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3380             // if operation is a += on strings,
3381             // make sure to convert argument to string
3382             JCExpression rhs = tree.operator.opcode == string_add
3383               ? makeString(tree.rhs)
3384               : tree.rhs;
3385             app.args = List.of(rhs).prependList(app.args);
3386             result = app;
3387         } else {
3388             result = tree;
3389         }
3390     }
3391 
3392     class AssignopDependencyScanner extends TreeScanner {
3393 
3394         Symbol sym;
3395         boolean dependencyFound = false;
3396 
3397         AssignopDependencyScanner(JCAssignOp tree) {
3398             this.sym = TreeInfo.symbol(tree.lhs);
3399         }
3400 
3401         @Override
3402         public void scan(JCTree tree) {
3403             if (tree != null && sym != null) {
3404                 tree.accept(this);
3405             }
3406         }
3407 
3408         @Override
3409         public void visitAssignop(JCAssignOp tree) {
3410             if (TreeInfo.symbol(tree.lhs) == sym) {
3411                 dependencyFound = true;
3412                 return;
3413             }
3414             super.visitAssignop(tree);
3415         }
3416 
3417         @Override
3418         public void visitUnary(JCUnary tree) {
3419             if (TreeInfo.symbol(tree.arg) == sym) {
3420                 dependencyFound = true;
3421                 return;
3422             }
3423             super.visitUnary(tree);
3424         }
3425     }
3426 
3427     /** Lower a tree of the form e++ or e-- where e is an object type */
3428     JCExpression lowerBoxedPostop(final JCUnary tree) {
3429         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3430         // or
3431         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3432         // where OP is += or -=
3433         final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3434         return abstractLval(tree.arg, tmp1 -> abstractRval(tmp1, tree.arg.type, tmp2 -> {
3435             Tag opcode = (tree.hasTag(POSTINC))
3436                 ? PLUS_ASG : MINUS_ASG;
3437             //"tmp1" and "tmp2" may refer to the same instance
3438             //(for e.g. <Class>.super.<ident>). But further processing may
3439             //change the components of the tree in place (see visitSelect),
3440             //so cloning the tree to avoid interference between the two uses:
3441             JCExpression lhs = (JCExpression)tmp1.clone();
3442             lhs = cast
3443                 ? make.TypeCast(tree.arg.type, lhs)
3444                 : lhs;
3445             JCExpression update = makeAssignop(opcode,
3446                                          lhs,
3447                                          make.Literal(1));
3448             return makeComma(update, tmp2);
3449         }));
3450     }
3451 
3452     public void visitUnary(JCUnary tree) {
3453         boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3454         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3455             switch(tree.getTag()) {
3456             case PREINC:            // ++ e
3457                     // translate to e += 1
3458             case PREDEC:            // -- e
3459                     // translate to e -= 1
3460                 {
3461                     JCTree.Tag opcode = (tree.hasTag(PREINC))
3462                         ? PLUS_ASG : MINUS_ASG;
3463                     JCAssignOp newTree = makeAssignop(opcode,
3464                                                     tree.arg,
3465                                                     make.Literal(1));
3466                     result = translate(newTree, tree.type);
3467                     return;
3468                 }
3469             case POSTINC:           // e ++
3470             case POSTDEC:           // e --
3471                 {
3472                     result = translate(lowerBoxedPostop(tree), tree.type);
3473                     return;
3474                 }
3475             }
3476             throw new AssertionError(tree);
3477         }
3478 
3479         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3480 
3481         if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3482             tree.type = cfolder.fold1(bool_not, tree.arg.type);
3483         }
3484 
3485         // If translated left hand side is an Apply, we are
3486         // seeing an access method invocation. In this case, return
3487         // that access method invocation as result.
3488         if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3489             result = tree.arg;
3490         } else {
3491             result = tree;
3492         }
3493     }
3494 
3495     public void visitBinary(JCBinary tree) {
3496         List<Type> formals = tree.operator.type.getParameterTypes();
3497         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3498         switch (tree.getTag()) {
3499         case OR:
3500             if (isTrue(lhs)) {
3501                 result = lhs;
3502                 return;
3503             }
3504             if (isFalse(lhs)) {
3505                 result = translate(tree.rhs, formals.tail.head);
3506                 return;
3507             }
3508             break;
3509         case AND:
3510             if (isFalse(lhs)) {
3511                 result = lhs;
3512                 return;
3513             }
3514             if (isTrue(lhs)) {
3515                 result = translate(tree.rhs, formals.tail.head);
3516                 return;
3517             }
3518             break;
3519         }
3520         tree.rhs = translate(tree.rhs, formals.tail.head);
3521         result = tree;
3522     }
3523 
3524     public void visitIdent(JCIdent tree) {
3525         result = access(tree.sym, tree, enclOp, false);
3526     }
3527 
3528     /** Translate away the foreach loop.  */
3529     public void visitForeachLoop(JCEnhancedForLoop tree) {
3530         if (types.elemtype(tree.expr.type) == null)
3531             visitIterableForeachLoop(tree);
3532         else
3533             visitArrayForeachLoop(tree);
3534     }
3535         // where
3536         /**
3537          * A statement of the form
3538          *
3539          * <pre>
3540          *     for ( T v : arrayexpr ) stmt;
3541          * </pre>
3542          *
3543          * (where arrayexpr is of an array type) gets translated to
3544          *
3545          * <pre>{@code
3546          *     for ( { arraytype #arr = arrayexpr;
3547          *             int #len = array.length;
3548          *             int #i = 0; };
3549          *           #i < #len; i$++ ) {
3550          *         T v = arr$[#i];
3551          *         stmt;
3552          *     }
3553          * }</pre>
3554          *
3555          * where #arr, #len, and #i are freshly named synthetic local variables.
3556          */
3557         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3558             make_at(tree.expr.pos());
3559             VarSymbol arraycache = new VarSymbol(SYNTHETIC,
3560                                                  names.fromString("arr" + target.syntheticNameChar()),
3561                                                  tree.expr.type,
3562                                                  currentMethodSym);
3563             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3564             VarSymbol lencache = new VarSymbol(SYNTHETIC,
3565                                                names.fromString("len" + target.syntheticNameChar()),
3566                                                syms.intType,
3567                                                currentMethodSym);
3568             JCStatement lencachedef = make.
3569                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3570             VarSymbol index = new VarSymbol(SYNTHETIC,
3571                                             names.fromString("i" + target.syntheticNameChar()),
3572                                             syms.intType,
3573                                             currentMethodSym);
3574 
3575             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3576             indexdef.init.type = indexdef.type = syms.intType.constType(0);
3577 
3578             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3579             JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3580 
3581             JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3582 
3583             Type elemtype = types.elemtype(tree.expr.type);
3584             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3585                                                     make.Ident(index)).setType(elemtype);
3586             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3587                                                   tree.var.name,
3588                                                   tree.var.vartype,
3589                                                   loopvarinit).setType(tree.var.type);
3590             loopvardef.sym = tree.var.sym;
3591             JCBlock body = make.
3592                 Block(0, List.of(loopvardef, tree.body));
3593 
3594             result = translate(make.
3595                                ForLoop(loopinit,
3596                                        cond,
3597                                        List.of(step),
3598                                        body));
3599             patchTargets(body, tree, result);
3600         }
3601         /** Patch up break and continue targets. */
3602         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3603             class Patcher extends TreeScanner {
3604                 public void visitBreak(JCBreak tree) {
3605                     if (tree.target == src)
3606                         tree.target = dest;
3607                 }
3608                 public void visitYield(JCYield tree) {
3609                     if (tree.target == src)
3610                         tree.target = dest;
3611                     scan(tree.value);
3612                 }
3613                 public void visitContinue(JCContinue tree) {
3614                     if (tree.target == src)
3615                         tree.target = dest;
3616                 }
3617                 public void visitClassDef(JCClassDecl tree) {}
3618             }
3619             new Patcher().scan(body);
3620         }
3621         /**
3622          * A statement of the form
3623          *
3624          * <pre>
3625          *     for ( T v : coll ) stmt ;
3626          * </pre>
3627          *
3628          * (where coll implements {@code Iterable<? extends T>}) gets translated to
3629          *
3630          * <pre>{@code
3631          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3632          *         T v = (T) #i.next();
3633          *         stmt;
3634          *     }
3635          * }</pre>
3636          *
3637          * where #i is a freshly named synthetic local variable.
3638          */
3639         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3640             make_at(tree.expr.pos());
3641             Type iteratorTarget = syms.objectType;
3642             Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type.referenceProjectionOrSelf()),
3643                                               syms.iterableType.tsym);
3644             if (iterableType.getTypeArguments().nonEmpty())
3645                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3646             tree.expr.type = types.erasure(types.skipTypeVars(tree.expr.type, false));
3647             tree.expr = transTypes.coerce(attrEnv, tree.expr, types.erasure(iterableType));
3648             Symbol iterator = lookupMethod(tree.expr.pos(),
3649                                            names.iterator,
3650                                            tree.expr.type,
3651                                            List.nil());
3652             Assert.check(types.isSameType(types.erasure(types.asSuper(iterator.type.getReturnType().referenceProjectionOrSelf(), syms.iteratorType.tsym)), types.erasure(syms.iteratorType)));
3653             VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
3654                                             types.erasure(syms.iteratorType),
3655                                             currentMethodSym);
3656 
3657              JCStatement init = make.
3658                 VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3659                      .setType(types.erasure(iterator.type))));
3660 
3661             Symbol hasNext = lookupMethod(tree.expr.pos(),
3662                                           names.hasNext,
3663                                           itvar.type,
3664                                           List.nil());
3665             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3666             Symbol next = lookupMethod(tree.expr.pos(),
3667                                        names.next,
3668                                        itvar.type,
3669                                        List.nil());
3670             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3671             if (tree.var.type.isPrimitive())
3672                 vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
3673             else
3674                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3675             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3676                                                   tree.var.name,
3677                                                   tree.var.vartype,
3678                                                   vardefinit).setType(tree.var.type);
3679             indexDef.sym = tree.var.sym;
3680             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3681             body.endpos = TreeInfo.endPos(tree.body);
3682             result = translate(make.
3683                 ForLoop(List.of(init),
3684                         cond,
3685                         List.nil(),
3686                         body));
3687             patchTargets(body, tree, result);
3688         }
3689 
3690     public void visitVarDef(JCVariableDecl tree) {
3691         MethodSymbol oldMethodSym = currentMethodSym;
3692         tree.mods = translate(tree.mods);
3693         tree.vartype = translate(tree.vartype);
3694         if (currentMethodSym == null) {
3695             // A class or instance field initializer.
3696             currentMethodSym =
3697                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3698                                  names.empty, null,
3699                                  currentClass);
3700         }
3701         if (tree.init != null) tree.init = translate(tree.init, tree.type);
3702         result = tree;
3703         currentMethodSym = oldMethodSym;
3704     }
3705 
3706     public void visitBlock(JCBlock tree) {
3707         MethodSymbol oldMethodSym = currentMethodSym;
3708         if (currentMethodSym == null) {
3709             // Block is a static or instance initializer.
3710             currentMethodSym =
3711                 new MethodSymbol(tree.flags | BLOCK,
3712                                  names.empty, null,
3713                                  currentClass);
3714         }
3715         super.visitBlock(tree);
3716         currentMethodSym = oldMethodSym;
3717     }
3718 
3719     public void visitDoLoop(JCDoWhileLoop tree) {
3720         tree.body = translate(tree.body);
3721         tree.cond = translate(tree.cond, syms.booleanType);
3722         result = tree;
3723     }
3724 
3725     public void visitWhileLoop(JCWhileLoop tree) {
3726         tree.cond = translate(tree.cond, syms.booleanType);
3727         tree.body = translate(tree.body);
3728         result = tree;
3729     }
3730 
3731     public void visitWithField(JCWithField tree) {
3732         Type fieldType = tree.field.type;
3733         tree.field = translate(tree.field, tree);
3734         tree.value = translate(tree.value, fieldType); // important to use pre-translation type.
3735 
3736         // If translated field is an Apply, we are
3737         // seeing an access method invocation. In this case, append
3738         // right hand side as last argument of the access method.
3739         if (tree.field.hasTag(APPLY)) {
3740             JCMethodInvocation app = (JCMethodInvocation) tree.field;
3741             app.args = List.of(tree.value).prependList(app.args);
3742             result = app;
3743         } else {
3744             result = tree;
3745         }
3746     }
3747 
3748     public void visitForLoop(JCForLoop tree) {
3749         tree.init = translate(tree.init);
3750         if (tree.cond != null)
3751             tree.cond = translate(tree.cond, syms.booleanType);
3752         tree.step = translate(tree.step);
3753         tree.body = translate(tree.body);
3754         result = tree;
3755     }
3756 
3757     public void visitReturn(JCReturn tree) {
3758         if (tree.expr != null)
3759             tree.expr = translate(tree.expr,
3760                                   types.erasure(currentMethodDef
3761                                                 .restype.type));
3762         result = tree;
3763     }
3764 
3765     public void visitSwitch(JCSwitch tree) {
3766         List<JCCase> cases = tree.patternSwitch ? addDefaultIfNeeded(tree.patternSwitch,
3767                                                                      tree.wasEnumSelector,
3768                                                                      tree.cases)
3769                                                 : tree.cases;
3770         handleSwitch(tree, tree.selector, cases);
3771     }
3772 
3773     @Override
3774     public void visitSwitchExpression(JCSwitchExpression tree) {
3775         List<JCCase> cases = addDefaultIfNeeded(tree.patternSwitch, tree.wasEnumSelector, tree.cases);
3776         handleSwitch(tree, tree.selector, cases);
3777     }
3778 
3779     private List<JCCase> addDefaultIfNeeded(boolean patternSwitch, boolean wasEnumSelector,
3780                                             List<JCCase> cases) {
3781         if (cases.stream().flatMap(c -> c.labels.stream()).noneMatch(p -> p.hasTag(Tag.DEFAULTCASELABEL))) {
3782             boolean matchException = useMatchException;
3783             matchException |= patternSwitch && !wasEnumSelector;
3784             Type exception = matchException ? syms.matchExceptionType
3785                                             : syms.incompatibleClassChangeErrorType;
3786             List<JCExpression> params = matchException ? List.of(makeNull(), makeNull())
3787                                                        : List.nil();
3788             JCThrow thr = make.Throw(makeNewClass(exception, params));
3789             JCCase c = make.Case(JCCase.STATEMENT, List.of(make.DefaultCaseLabel()), null, List.of(thr), null);
3790             cases = cases.prepend(c);
3791         }
3792 
3793         return cases;
3794     }
3795 
3796     private void handleSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
3797         //expand multiple label cases:
3798         ListBuffer<JCCase> convertedCases = new ListBuffer<>();
3799 
3800         for (JCCase c : cases) {
3801             switch (c.labels.size()) {
3802                 case 0: //default
3803                 case 1: //single label
3804                     convertedCases.append(c);
3805                     break;
3806                 default: //multiple labels, expand:
3807                     //case C1, C2, C3: ...
3808                     //=>
3809                     //case C1:
3810                     //case C2:
3811                     //case C3: ...
3812                     List<JCCaseLabel> patterns = c.labels;
3813                     while (patterns.tail.nonEmpty()) {
3814                         convertedCases.append(make_at(c.pos()).Case(JCCase.STATEMENT,
3815                                                            List.of(patterns.head),
3816                                                            null,
3817                                                            List.nil(),
3818                                                            null));
3819                         patterns = patterns.tail;
3820                     }
3821                     c.labels = patterns;
3822                     convertedCases.append(c);
3823                     break;
3824             }
3825         }
3826 
3827         for (JCCase c : convertedCases) {
3828             if (c.caseKind == JCCase.RULE && c.completesNormally) {
3829                 JCBreak b = make.at(TreeInfo.endPos(c.stats.last())).Break(null);
3830                 b.target = tree;
3831                 c.stats = c.stats.append(b);
3832             }
3833         }
3834 
3835         cases = convertedCases.toList();
3836 
3837         Type selsuper = types.supertype(selector.type);
3838         boolean enumSwitch = selsuper != null &&
3839             (selector.type.tsym.flags() & ENUM) != 0;
3840         boolean stringSwitch = selsuper != null &&
3841             types.isSameType(selector.type, syms.stringType);
3842         boolean boxedSwitch = !enumSwitch && !stringSwitch && !selector.type.isPrimitive();
3843         selector = translate(selector, selector.type);
3844         cases = translateCases(cases);
3845         if (tree.hasTag(SWITCH)) {
3846             ((JCSwitch) tree).selector = selector;
3847             ((JCSwitch) tree).cases = cases;
3848         } else if (tree.hasTag(SWITCH_EXPRESSION)) {
3849             ((JCSwitchExpression) tree).selector = selector;
3850             ((JCSwitchExpression) tree).cases = cases;
3851         } else {
3852             Assert.error();
3853         }
3854         if (enumSwitch) {
3855             result = visitEnumSwitch(tree, selector, cases);
3856         } else if (stringSwitch) {
3857             result = visitStringSwitch(tree, selector, cases);
3858         } else if (boxedSwitch) {
3859             //An switch over boxed primitive. Pattern matching switches are already translated
3860             //by TransPatterns, so all non-primitive types are only boxed primitives:
3861             result = visitBoxedPrimitiveSwitch(tree, selector, cases);
3862         } else {
3863             result = tree;
3864         }
3865     }
3866 
3867     public JCTree visitEnumSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
3868         TypeSymbol enumSym = selector.type.tsym;
3869         EnumMapping map = mapForEnum(tree.pos(), enumSym);
3870         make_at(tree.pos());
3871         Symbol ordinalMethod = lookupMethod(tree.pos(),
3872                                             names.ordinal,
3873                                             selector.type,
3874                                             List.nil());
3875         JCExpression newSelector;
3876 
3877         if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) {
3878             //for enum switches with case null, do:
3879             //switch ($selector != null ? $mapVar[$selector.ordinal()] : -1) {...}
3880             //replacing case null with case -1:
3881             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3882                                                names.fromString("s" + tree.pos + this.target.syntheticNameChar()),
3883                                                selector.type,
3884                                                currentMethodSym);
3885             JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type);
3886             newSelector = map.switchValue(
3887                     make.App(make.Select(make.Ident(dollar_s),
3888                             ordinalMethod)));
3889             newSelector =
3890                     make.LetExpr(List.of(var),
3891                                  make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()),
3892                                                   newSelector,
3893                                                   makeLit(syms.intType, -1))
3894                                      .setType(newSelector.type))
3895                         .setType(newSelector.type);
3896         } else {
3897             newSelector = map.switchValue(
3898                     make.App(make.Select(selector,
3899                             ordinalMethod)));
3900         }
3901         ListBuffer<JCCase> newCases = new ListBuffer<>();
3902         for (JCCase c : cases) {
3903             if (c.labels.head.hasTag(CONSTANTCASELABEL)) {
3904                 JCExpression pat;
3905                 if (TreeInfo.isNullCaseLabel(c.labels.head)) {
3906                     pat = makeLit(syms.intType, -1);
3907                 } else {
3908                     VarSymbol label = (VarSymbol)TreeInfo.symbol(((JCConstantCaseLabel) c.labels.head).expr);
3909                     pat = map.caseValue(label);
3910                 }
3911                 newCases.append(make.Case(JCCase.STATEMENT, List.of(make.ConstantCaseLabel(pat)), null, c.stats, null));
3912             } else {
3913                 newCases.append(c);
3914             }
3915         }
3916         JCTree enumSwitch;
3917         if (tree.hasTag(SWITCH)) {
3918             enumSwitch = make.Switch(newSelector, newCases.toList());
3919         } else if (tree.hasTag(SWITCH_EXPRESSION)) {
3920             enumSwitch = make.SwitchExpression(newSelector, newCases.toList());
3921             enumSwitch.setType(tree.type);
3922         } else {
3923             Assert.error();
3924             throw new AssertionError();
3925         }
3926         patchTargets(enumSwitch, tree, enumSwitch);
3927         return enumSwitch;
3928     }
3929 
3930     public JCTree visitStringSwitch(JCTree tree, JCExpression selector, List<JCCase> caseList) {
3931         int alternatives = caseList.size();
3932 
3933         if (alternatives == 0) { // Strange but legal possibility (only legal for switch statement)
3934             return make.at(tree.pos()).Exec(attr.makeNullCheck(selector));
3935         } else {
3936             /*
3937              * The general approach used is to translate a single
3938              * string switch statement into a series of two chained
3939              * switch statements: the first a synthesized statement
3940              * switching on the argument string's hash value and
3941              * computing a string's position in the list of original
3942              * case labels, if any, followed by a second switch on the
3943              * computed integer value.  The second switch has the same
3944              * code structure as the original string switch statement
3945              * except that the string case labels are replaced with
3946              * positional integer constants starting at 0.
3947              *
3948              * The first switch statement can be thought of as an
3949              * inlined map from strings to their position in the case
3950              * label list.  An alternate implementation would use an
3951              * actual Map for this purpose, as done for enum switches.
3952              *
3953              * With some additional effort, it would be possible to
3954              * use a single switch statement on the hash code of the
3955              * argument, but care would need to be taken to preserve
3956              * the proper control flow in the presence of hash
3957              * collisions and other complications, such as
3958              * fallthroughs.  Switch statements with one or two
3959              * alternatives could also be specially translated into
3960              * if-then statements to omit the computation of the hash
3961              * code.
3962              *
3963              * The generated code assumes that the hashing algorithm
3964              * of String is the same in the compilation environment as
3965              * in the environment the code will run in.  The string
3966              * hashing algorithm in the SE JDK has been unchanged
3967              * since at least JDK 1.2.  Since the algorithm has been
3968              * specified since that release as well, it is very
3969              * unlikely to be changed in the future.
3970              *
3971              * Different hashing algorithms, such as the length of the
3972              * strings or a perfect hashing algorithm over the
3973              * particular set of case labels, could potentially be
3974              * used instead of String.hashCode.
3975              */
3976 
3977             ListBuffer<JCStatement> stmtList = new ListBuffer<>();
3978 
3979             // Map from String case labels to their original position in
3980             // the list of case labels.
3981             Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f);
3982 
3983             // Map of hash codes to the string case labels having that hashCode.
3984             Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f);
3985 
3986             int casePosition = 0;
3987             JCCase nullCase = null;
3988             int nullCaseLabel = -1;
3989 
3990             for(JCCase oneCase : caseList) {
3991                 if (oneCase.labels.head.hasTag(CONSTANTCASELABEL)) {
3992                     if (TreeInfo.isNullCaseLabel(oneCase.labels.head)) {
3993                         nullCase = oneCase;
3994                         nullCaseLabel = casePosition;
3995                     } else {
3996                         JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr;
3997                         String labelExpr = (String) expression.type.constValue();
3998                         Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3999                         Assert.checkNull(mapping);
4000                         int hashCode = labelExpr.hashCode();
4001 
4002                         Set<String> stringSet = hashToString.get(hashCode);
4003                         if (stringSet == null) {
4004                             stringSet = new LinkedHashSet<>(1, 1.0f);
4005                             stringSet.add(labelExpr);
4006                             hashToString.put(hashCode, stringSet);
4007                         } else {
4008                             boolean added = stringSet.add(labelExpr);
4009                             Assert.check(added);
4010                         }
4011                     }
4012                 }
4013                 casePosition++;
4014             }
4015 
4016             // Synthesize a switch statement that has the effect of
4017             // mapping from a string to the integer position of that
4018             // string in the list of case labels.  This is done by
4019             // switching on the hashCode of the string followed by an
4020             // if-then-else chain comparing the input for equality
4021             // with all the case labels having that hash value.
4022 
4023             /*
4024              * s$ = top of stack;
4025              * tmp$ = -1;
4026              * switch($s.hashCode()) {
4027              *     case caseLabel.hashCode:
4028              *         if (s$.equals("caseLabel_1")
4029              *           tmp$ = caseLabelToPosition("caseLabel_1");
4030              *         else if (s$.equals("caseLabel_2"))
4031              *           tmp$ = caseLabelToPosition("caseLabel_2");
4032              *         ...
4033              *         break;
4034              * ...
4035              * }
4036              */
4037 
4038             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
4039                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
4040                                                syms.stringType,
4041                                                currentMethodSym);
4042             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type));
4043 
4044             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
4045                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
4046                                                  syms.intType,
4047                                                  currentMethodSym);
4048             JCVariableDecl dollar_tmp_def =
4049                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
4050             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
4051             stmtList.append(dollar_tmp_def);
4052             ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
4053             // hashCode will trigger nullcheck on original switch expression
4054             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
4055                                                        names.hashCode,
4056                                                        List.nil()).setType(syms.intType);
4057             JCSwitch switch1 = make.Switch(hashCodeCall,
4058                                         caseBuffer.toList());
4059             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
4060                 int hashCode = entry.getKey();
4061                 Set<String> stringsWithHashCode = entry.getValue();
4062                 Assert.check(stringsWithHashCode.size() >= 1);
4063 
4064                 JCStatement elsepart = null;
4065                 for(String caseLabel : stringsWithHashCode ) {
4066                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
4067                                                                    names.equals,
4068                                                                    List.of(make.Literal(caseLabel)));
4069                     elsepart = make.If(stringEqualsCall,
4070                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
4071                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
4072                                                  setType(dollar_tmp.type)),
4073                                        elsepart);
4074                 }
4075 
4076                 ListBuffer<JCStatement> lb = new ListBuffer<>();
4077                 JCBreak breakStmt = make.Break(null);
4078                 breakStmt.target = switch1;
4079                 lb.append(elsepart).append(breakStmt);
4080 
4081                 caseBuffer.append(make.Case(JCCase.STATEMENT,
4082                                             List.of(make.ConstantCaseLabel(make.Literal(hashCode))),
4083                                             null,
4084                                             lb.toList(),
4085                                             null));
4086             }
4087 
4088             switch1.cases = caseBuffer.toList();
4089 
4090             if (nullCase != null) {
4091                 stmtList.append(make.If(makeBinary(NE, make.Ident(dollar_s), makeNull()), switch1, make.Exec(make.Assign(make.Ident(dollar_tmp),
4092                                                              make.Literal(nullCaseLabel)).
4093                                                  setType(dollar_tmp.type))).setType(syms.intType));
4094             } else {
4095                 stmtList.append(switch1);
4096             }
4097 
4098             // Make isomorphic switch tree replacing string labels
4099             // with corresponding integer ones from the label to
4100             // position map.
4101 
4102             ListBuffer<JCCase> lb = new ListBuffer<>();
4103             for(JCCase oneCase : caseList ) {
4104                 boolean isDefault = !oneCase.labels.head.hasTag(CONSTANTCASELABEL);
4105                 JCExpression caseExpr;
4106                 if (isDefault)
4107                     caseExpr = null;
4108                 else if (oneCase == nullCase) {
4109                     caseExpr = make.Literal(nullCaseLabel);
4110                 } else {
4111                     JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr;
4112                     String name = (String) TreeInfo.skipParens(expression)
4113                                                    .type.constValue();
4114                     caseExpr = make.Literal(caseLabelToPosition.get(name));
4115                 }
4116 
4117                 lb.append(make.Case(JCCase.STATEMENT, caseExpr == null ? List.of(make.DefaultCaseLabel())
4118                                                                        : List.of(make.ConstantCaseLabel(caseExpr)),
4119                                     null,
4120                                     oneCase.stats, null));
4121             }
4122 
4123             if (tree.hasTag(SWITCH)) {
4124                 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
4125                 // Rewire up old unlabeled break statements to the
4126                 // replacement switch being created.
4127                 patchTargets(switch2, tree, switch2);
4128 
4129                 stmtList.append(switch2);
4130 
4131                 JCBlock res = make.Block(0L, stmtList.toList());
4132                 res.endpos = TreeInfo.endPos(tree);
4133                 return res;
4134             } else {
4135                 JCSwitchExpression switch2 = make.SwitchExpression(make.Ident(dollar_tmp), lb.toList());
4136 
4137                 // Rewire up old unlabeled break statements to the
4138                 // replacement switch being created.
4139                 patchTargets(switch2, tree, switch2);
4140 
4141                 switch2.setType(tree.type);
4142 
4143                 LetExpr res = make.LetExpr(stmtList.toList(), switch2);
4144 
4145                 res.needsCond = true;
4146                 res.setType(tree.type);
4147 
4148                 return res;
4149             }
4150         }
4151     }
4152 
4153     private JCTree visitBoxedPrimitiveSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
4154         JCExpression newSelector;
4155 
4156         if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) {
4157             //a switch over a boxed primitive, with a null case. Pick two constants that are
4158             //not used by any branch in the case (c1 and c2), close to other constants that are
4159             //used in the switch. Then do:
4160             //switch ($selector != null ? $selector != c1 ? $selector : c2 : c1) {...}
4161             //replacing case null with case c1
4162             Set<Integer> constants = new LinkedHashSet<>();
4163             JCCase nullCase = null;
4164 
4165             for (JCCase c : cases) {
4166                 if (TreeInfo.isNullCaseLabel(c.labels.head)) {
4167                     nullCase = c;
4168                 } else if (!c.labels.head.hasTag(DEFAULTCASELABEL)) {
4169                     constants.add((int) ((JCConstantCaseLabel) c.labels.head).expr.type.constValue());
4170                 }
4171             }
4172 
4173             Assert.checkNonNull(nullCase);
4174 
4175             int nullValue = constants.isEmpty() ? 0 : constants.iterator().next();
4176 
4177             while (constants.contains(nullValue)) nullValue++;
4178 
4179             constants.add(nullValue);
4180             nullCase.labels.head = make.ConstantCaseLabel(makeLit(syms.intType, nullValue));
4181 
4182             int replacementValue = nullValue;
4183 
4184             while (constants.contains(replacementValue)) replacementValue++;
4185 
4186             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
4187                                                names.fromString("s" + tree.pos + this.target.syntheticNameChar()),
4188                                                selector.type,
4189                                                currentMethodSym);
4190             JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type);
4191             JCExpression nullValueReplacement =
4192                     make.Conditional(makeBinary(NE,
4193                                                  unbox(make.Ident(dollar_s), syms.intType),
4194                                                  makeLit(syms.intType, nullValue)),
4195                                      unbox(make.Ident(dollar_s), syms.intType),
4196                                      makeLit(syms.intType, replacementValue))
4197                         .setType(syms.intType);
4198             JCExpression nullCheck =
4199                     make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()),
4200                                      nullValueReplacement,
4201                                      makeLit(syms.intType, nullValue))
4202                         .setType(syms.intType);
4203             newSelector = make.LetExpr(List.of(var), nullCheck).setType(syms.intType);
4204         } else {
4205             newSelector = unbox(selector, syms.intType);
4206         }
4207 
4208         if (tree.hasTag(SWITCH)) {
4209             ((JCSwitch) tree).selector = newSelector;
4210         } else {
4211             ((JCSwitchExpression) tree).selector = newSelector;
4212         }
4213 
4214         return tree;
4215     }
4216 
4217     @Override
4218     public void visitBreak(JCBreak tree) {
4219         result = tree;
4220     }
4221 
4222     @Override
4223     public void visitYield(JCYield tree) {
4224         tree.value = translate(tree.value, tree.target.type);
4225         result = tree;
4226     }
4227 
4228     public void visitNewArray(JCNewArray tree) {
4229         tree.elemtype = translate(tree.elemtype);
4230         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
4231             if (t.head != null) t.head = translate(t.head, syms.intType);
4232         tree.elems = translate(tree.elems, types.elemtype(tree.type));
4233         result = tree;
4234     }
4235 
4236     public void visitSelect(JCFieldAccess tree) {
4237         // need to special case-access of the form C.super.x
4238         // these will always need an access method, unless C
4239         // is a default interface subclassed by the current class.
4240         boolean qualifiedSuperAccess =
4241             tree.selected.hasTag(SELECT) &&
4242             TreeInfo.name(tree.selected) == names._super &&
4243             !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
4244         /* JDK-8269956: Where a reflective (class) literal is needed, the unqualified Point.class is
4245          * always the "primary" mirror - representing the primitive reference runtime type - thereby
4246          * always matching the behavior of Object::getClass
4247          */
4248         boolean needPrimaryMirror = tree.name == names._class && tree.selected.type.isReferenceProjection();
4249         tree.selected = translate(tree.selected);
4250         if (needPrimaryMirror && allowPrimitiveClasses && tree.selected.type.isPrimitiveClass()) {
4251             tree.selected.setType(tree.selected.type.referenceProjection());
4252         }
4253         if (tree.name == names._class) {
4254             result = classOf(tree.selected);
4255         }
4256         else if (tree.name == names._super &&
4257                 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
4258             //default super call!! Not a classic qualified super call
4259             TypeSymbol supSym = tree.selected.type.tsym;
4260             Assert.checkNonNull(types.asSuper(currentClass.type.referenceProjectionOrSelf(), supSym));
4261             result = tree;
4262         }
4263         else if (tree.name == names._this || tree.name == names._super) {
4264             result = makeThis(tree.pos(), tree.selected.type.tsym);
4265         }
4266         else
4267             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
4268     }
4269 
4270     public void visitLetExpr(LetExpr tree) {
4271         tree.defs = translate(tree.defs);
4272         tree.expr = translate(tree.expr, tree.type);
4273         result = tree;
4274     }
4275 
4276     // There ought to be nothing to rewrite here;
4277     // we don't generate code.
4278     public void visitAnnotation(JCAnnotation tree) {
4279         result = tree;
4280     }
4281 
4282     @Override
4283     public void visitTry(JCTry tree) {
4284         if (tree.resources.nonEmpty()) {
4285             result = makeTwrTry(tree);
4286             return;
4287         }
4288 
4289         boolean hasBody = tree.body.getStatements().nonEmpty();
4290         boolean hasCatchers = tree.catchers.nonEmpty();
4291         boolean hasFinally = tree.finalizer != null &&
4292                 tree.finalizer.getStatements().nonEmpty();
4293 
4294         if (!hasCatchers && !hasFinally) {
4295             result = translate(tree.body);
4296             return;
4297         }
4298 
4299         if (!hasBody) {
4300             if (hasFinally) {
4301                 result = translate(tree.finalizer);
4302             } else {
4303                 result = translate(tree.body);
4304             }
4305             return;
4306         }
4307 
4308         // no optimizations possible
4309         super.visitTry(tree);
4310     }
4311 
4312 /**************************************************************************
4313  * main method
4314  *************************************************************************/
4315 
4316     /** Translate a toplevel class and return a list consisting of
4317      *  the translated class and translated versions of all inner classes.
4318      *  @param env   The attribution environment current at the class definition.
4319      *               We need this for resolving some additional symbols.
4320      *  @param cdef  The tree representing the class definition.
4321      */
4322     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
4323         ListBuffer<JCTree> translated = null;
4324         try {
4325             attrEnv = env;
4326             this.make = make;
4327             endPosTable = env.toplevel.endPositions;
4328             currentClass = null;
4329             currentMethodDef = null;
4330             outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
4331             outermostMemberDef = null;
4332             this.translated = new ListBuffer<>();
4333             classdefs = new HashMap<>();
4334             actualSymbols = new HashMap<>();
4335             freevarCache = new HashMap<>();
4336             proxies = new HashMap<>();
4337             twrVars = WriteableScope.create(syms.noSymbol);
4338             outerThisStack = List.nil();
4339             accessNums = new HashMap<>();
4340             accessSyms = new HashMap<>();
4341             accessConstrs = new HashMap<>();
4342             accessConstrTags = List.nil();
4343             accessed = new ListBuffer<>();
4344             translate(cdef, (JCExpression)null);
4345             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
4346                 makeAccessible(l.head);
4347             for (EnumMapping map : enumSwitchMap.values())
4348                 map.translate();
4349             checkConflicts(this.translated.toList());
4350             checkAccessConstructorTags();
4351             translated = this.translated;
4352         } finally {
4353             // note that recursive invocations of this method fail hard
4354             attrEnv = null;
4355             this.make = null;
4356             endPosTable = null;
4357             currentClass = null;
4358             currentMethodDef = null;
4359             outermostClassDef = null;
4360             outermostMemberDef = null;
4361             this.translated = null;
4362             classdefs = null;
4363             actualSymbols = null;
4364             freevarCache = null;
4365             proxies = null;
4366             outerThisStack = null;
4367             accessNums = null;
4368             accessSyms = null;
4369             accessConstrs = null;
4370             accessConstrTags = null;
4371             accessed = null;
4372             enumSwitchMap.clear();
4373             assertionsDisabledClassCache = null;
4374         }
4375         return translated.toList();
4376     }
4377 }