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