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