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