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