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