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