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