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