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