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