Lower.java revision 3169:ef2011e4555a
1/*
2 * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.comp;
27
28import java.util.*;
29
30import com.sun.tools.javac.code.*;
31import com.sun.tools.javac.code.Kinds.KindSelector;
32import com.sun.tools.javac.code.Scope.WriteableScope;
33import com.sun.tools.javac.jvm.*;
34import com.sun.tools.javac.main.Option.PkgInfo;
35import com.sun.tools.javac.tree.*;
36import com.sun.tools.javac.util.*;
37import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
38import com.sun.tools.javac.util.List;
39
40import com.sun.tools.javac.code.Symbol.*;
41import com.sun.tools.javac.tree.JCTree.*;
42import com.sun.tools.javac.code.Type.*;
43
44import com.sun.tools.javac.jvm.Target;
45import com.sun.tools.javac.tree.EndPosTable;
46
47import static com.sun.tools.javac.code.Flags.*;
48import static com.sun.tools.javac.code.Flags.BLOCK;
49import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
50import static com.sun.tools.javac.code.TypeTag.*;
51import static com.sun.tools.javac.code.Kinds.Kind.*;
52import static com.sun.tools.javac.jvm.ByteCodes.*;
53import static com.sun.tools.javac.tree.JCTree.Tag.*;
54
55/** This pass translates away some syntactic sugar: inner classes,
56 *  class literals, assertions, foreach loops, etc.
57 *
58 *  <p><b>This is NOT part of any supported API.
59 *  If you write code that depends on this, you do so at your own risk.
60 *  This code and its internal interfaces are subject to change or
61 *  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        VarSymbol var =
2211            new VarSymbol(FINAL|SYNTHETIC,
2212                          names.fromString(
2213                                          target.syntheticNameChar()
2214                                          + "" + rval.hashCode()),
2215                                      type,
2216                                      currentMethodSym);
2217        rval = convert(rval,type);
2218        JCVariableDecl def = make.VarDef(var, rval); // XXX cast
2219        JCExpression built = builder.build(make.Ident(var));
2220        JCExpression res = make.LetExpr(def, built);
2221        res.type = built.type;
2222        return res;
2223    }
2224
2225    // same as above, with the type of the temporary variable computed
2226    JCExpression abstractRval(JCExpression rval, TreeBuilder builder) {
2227        return abstractRval(rval, rval.type, builder);
2228    }
2229
2230    // same as above, but for an expression that may be used as either
2231    // an rvalue or an lvalue.  This requires special handling for
2232    // Select expressions, where we place the left-hand-side of the
2233    // select in a temporary, and for Indexed expressions, where we
2234    // place both the indexed expression and the index value in temps.
2235    JCExpression abstractLval(JCExpression lval, final TreeBuilder builder) {
2236        lval = TreeInfo.skipParens(lval);
2237        switch (lval.getTag()) {
2238        case IDENT:
2239            return builder.build(lval);
2240        case SELECT: {
2241            final JCFieldAccess s = (JCFieldAccess)lval;
2242            Symbol lid = TreeInfo.symbol(s.selected);
2243            if (lid != null && lid.kind == TYP) return builder.build(lval);
2244            return abstractRval(s.selected, new TreeBuilder() {
2245                    public JCExpression build(final JCExpression selected) {
2246                        return builder.build(make.Select(selected, s.sym));
2247                    }
2248                });
2249        }
2250        case INDEXED: {
2251            final JCArrayAccess i = (JCArrayAccess)lval;
2252            return abstractRval(i.indexed, new TreeBuilder() {
2253                    public JCExpression build(final JCExpression indexed) {
2254                        return abstractRval(i.index, syms.intType, new TreeBuilder() {
2255                                public JCExpression build(final JCExpression index) {
2256                                    JCExpression newLval = make.Indexed(indexed, index);
2257                                    newLval.setType(i.type);
2258                                    return builder.build(newLval);
2259                                }
2260                            });
2261                    }
2262                });
2263        }
2264        case TYPECAST: {
2265            return abstractLval(((JCTypeCast)lval).expr, builder);
2266        }
2267        }
2268        throw new AssertionError(lval);
2269    }
2270
2271    // evaluate and discard the first expression, then evaluate the second.
2272    JCExpression makeComma(final JCExpression expr1, final JCExpression expr2) {
2273        return abstractRval(expr1, new TreeBuilder() {
2274                public JCExpression build(final JCExpression discarded) {
2275                    return expr2;
2276                }
2277            });
2278    }
2279
2280/**************************************************************************
2281 * Translation methods
2282 *************************************************************************/
2283
2284    /** Visitor argument: enclosing operator node.
2285     */
2286    private JCExpression enclOp;
2287
2288    /** Visitor method: Translate a single node.
2289     *  Attach the source position from the old tree to its replacement tree.
2290     */
2291    @Override
2292    public <T extends JCTree> T translate(T tree) {
2293        if (tree == null) {
2294            return null;
2295        } else {
2296            make_at(tree.pos());
2297            T result = super.translate(tree);
2298            if (endPosTable != null && result != tree) {
2299                endPosTable.replaceTree(tree, result);
2300            }
2301            return result;
2302        }
2303    }
2304
2305    /** Visitor method: Translate a single node, boxing or unboxing if needed.
2306     */
2307    public <T extends JCExpression> T translate(T tree, Type type) {
2308        return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2309    }
2310
2311    /** Visitor method: Translate tree.
2312     */
2313    public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2314        JCExpression prevEnclOp = this.enclOp;
2315        this.enclOp = enclOp;
2316        T res = translate(tree);
2317        this.enclOp = prevEnclOp;
2318        return res;
2319    }
2320
2321    /** Visitor method: Translate list of trees.
2322     */
2323    public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2324        JCExpression prevEnclOp = this.enclOp;
2325        this.enclOp = enclOp;
2326        List<T> res = translate(trees);
2327        this.enclOp = prevEnclOp;
2328        return res;
2329    }
2330
2331    /** Visitor method: Translate list of trees.
2332     */
2333    public <T extends JCExpression> List<T> translate(List<T> trees, Type type) {
2334        if (trees == null) return null;
2335        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2336            l.head = translate(l.head, type);
2337        return trees;
2338    }
2339
2340    public void visitPackageDef(JCPackageDecl tree) {
2341        if (!needPackageInfoClass(tree))
2342            return;
2343
2344        Name name = names.package_info;
2345        long flags = Flags.ABSTRACT | Flags.INTERFACE;
2346        // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2347        flags = flags | Flags.SYNTHETIC;
2348        JCClassDecl packageAnnotationsClass
2349            = make.ClassDef(make.Modifiers(flags, tree.getAnnotations()),
2350                            name, List.<JCTypeParameter>nil(),
2351                            null, List.<JCExpression>nil(), List.<JCTree>nil());
2352        ClassSymbol c = tree.packge.package_info;
2353        c.flags_field |= flags;
2354        c.setAttributes(tree.packge);
2355        ClassType ctype = (ClassType) c.type;
2356        ctype.supertype_field = syms.objectType;
2357        ctype.interfaces_field = List.nil();
2358        packageAnnotationsClass.sym = c;
2359
2360        translated.append(packageAnnotationsClass);
2361    }
2362    // where
2363    private boolean needPackageInfoClass(JCPackageDecl pd) {
2364        switch (pkginfoOpt) {
2365            case ALWAYS:
2366                return true;
2367            case LEGACY:
2368                return pd.getAnnotations().nonEmpty();
2369            case NONEMPTY:
2370                for (Attribute.Compound a :
2371                         pd.packge.getDeclarationAttributes()) {
2372                    Attribute.RetentionPolicy p = types.getRetention(a);
2373                    if (p != Attribute.RetentionPolicy.SOURCE)
2374                        return true;
2375                }
2376                return false;
2377        }
2378        throw new AssertionError();
2379    }
2380
2381    public void visitClassDef(JCClassDecl tree) {
2382        Env<AttrContext> prevEnv = attrEnv;
2383        ClassSymbol currentClassPrev = currentClass;
2384        MethodSymbol currentMethodSymPrev = currentMethodSym;
2385
2386        currentClass = tree.sym;
2387        currentMethodSym = null;
2388        attrEnv = typeEnvs.remove(currentClass);
2389        if (attrEnv == null)
2390            attrEnv = prevEnv;
2391
2392        classdefs.put(currentClass, tree);
2393
2394        proxies = proxies.dup(currentClass);
2395        List<VarSymbol> prevOuterThisStack = outerThisStack;
2396
2397        // If this is an enum definition
2398        if ((tree.mods.flags & ENUM) != 0 &&
2399            (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2400            visitEnumDef(tree);
2401
2402        // If this is a nested class, define a this$n field for
2403        // it and add to proxies.
2404        JCVariableDecl otdef = null;
2405        if (currentClass.hasOuterInstance())
2406            otdef = outerThisDef(tree.pos, currentClass);
2407
2408        // If this is a local class, define proxies for all its free variables.
2409        List<JCVariableDecl> fvdefs = freevarDefs(
2410            tree.pos, freevars(currentClass), currentClass);
2411
2412        // Recursively translate superclass, interfaces.
2413        tree.extending = translate(tree.extending);
2414        tree.implementing = translate(tree.implementing);
2415
2416        if (currentClass.isLocal()) {
2417            ClassSymbol encl = currentClass.owner.enclClass();
2418            if (encl.trans_local == null) {
2419                encl.trans_local = List.nil();
2420            }
2421            encl.trans_local = encl.trans_local.prepend(currentClass);
2422        }
2423
2424        // Recursively translate members, taking into account that new members
2425        // might be created during the translation and prepended to the member
2426        // list `tree.defs'.
2427        List<JCTree> seen = List.nil();
2428        while (tree.defs != seen) {
2429            List<JCTree> unseen = tree.defs;
2430            for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2431                JCTree outermostMemberDefPrev = outermostMemberDef;
2432                if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2433                l.head = translate(l.head);
2434                outermostMemberDef = outermostMemberDefPrev;
2435            }
2436            seen = unseen;
2437        }
2438
2439        // Convert a protected modifier to public, mask static modifier.
2440        if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2441        tree.mods.flags &= ClassFlags;
2442
2443        // Convert name to flat representation, replacing '.' by '$'.
2444        tree.name = Convert.shortName(currentClass.flatName());
2445
2446        // Add this$n and free variables proxy definitions to class.
2447
2448        for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2449            tree.defs = tree.defs.prepend(l.head);
2450            enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2451        }
2452        if (currentClass.hasOuterInstance()) {
2453            tree.defs = tree.defs.prepend(otdef);
2454            enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2455        }
2456
2457        proxies = proxies.leave();
2458        outerThisStack = prevOuterThisStack;
2459
2460        // Append translated tree to `translated' queue.
2461        translated.append(tree);
2462
2463        attrEnv = prevEnv;
2464        currentClass = currentClassPrev;
2465        currentMethodSym = currentMethodSymPrev;
2466
2467        // Return empty block {} as a placeholder for an inner class.
2468        result = make_at(tree.pos()).Block(SYNTHETIC, List.<JCStatement>nil());
2469    }
2470
2471    /** Translate an enum class. */
2472    private void visitEnumDef(JCClassDecl tree) {
2473        make_at(tree.pos());
2474
2475        // add the supertype, if needed
2476        if (tree.extending == null)
2477            tree.extending = make.Type(types.supertype(tree.type));
2478
2479        // classOfType adds a cache field to tree.defs
2480        JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2481            setType(types.erasure(syms.classType));
2482
2483        // process each enumeration constant, adding implicit constructor parameters
2484        int nextOrdinal = 0;
2485        ListBuffer<JCExpression> values = new ListBuffer<>();
2486        ListBuffer<JCTree> enumDefs = new ListBuffer<>();
2487        ListBuffer<JCTree> otherDefs = new ListBuffer<>();
2488        for (List<JCTree> defs = tree.defs;
2489             defs.nonEmpty();
2490             defs=defs.tail) {
2491            if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2492                JCVariableDecl var = (JCVariableDecl)defs.head;
2493                visitEnumConstantDef(var, nextOrdinal++);
2494                values.append(make.QualIdent(var.sym));
2495                enumDefs.append(var);
2496            } else {
2497                otherDefs.append(defs.head);
2498            }
2499        }
2500
2501        // private static final T[] #VALUES = { a, b, c };
2502        Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2503        while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash
2504            valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2505        Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2506        VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2507                                            valuesName,
2508                                            arrayType,
2509                                            tree.type.tsym);
2510        JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2511                                          List.<JCExpression>nil(),
2512                                          values.toList());
2513        newArray.type = arrayType;
2514        enumDefs.append(make.VarDef(valuesVar, newArray));
2515        tree.sym.members().enter(valuesVar);
2516
2517        Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2518                                        tree.type, List.<Type>nil());
2519        List<JCStatement> valuesBody;
2520        if (useClone()) {
2521            // return (T[]) $VALUES.clone();
2522            JCTypeCast valuesResult =
2523                make.TypeCast(valuesSym.type.getReturnType(),
2524                              make.App(make.Select(make.Ident(valuesVar),
2525                                                   syms.arrayCloneMethod)));
2526            valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2527        } else {
2528            // template: T[] $result = new T[$values.length];
2529            Name resultName = names.fromString(target.syntheticNameChar() + "result");
2530            while (tree.sym.members().findFirst(resultName) != null) // avoid name clash
2531                resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2532            VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2533                                                resultName,
2534                                                arrayType,
2535                                                valuesSym);
2536            JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2537                                  List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2538                                  null);
2539            resultArray.type = arrayType;
2540            JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2541
2542            // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2543            if (systemArraycopyMethod == null) {
2544                systemArraycopyMethod =
2545                    new MethodSymbol(PUBLIC | STATIC,
2546                                     names.fromString("arraycopy"),
2547                                     new MethodType(List.<Type>of(syms.objectType,
2548                                                            syms.intType,
2549                                                            syms.objectType,
2550                                                            syms.intType,
2551                                                            syms.intType),
2552                                                    syms.voidType,
2553                                                    List.<Type>nil(),
2554                                                    syms.methodClass),
2555                                     syms.systemType.tsym);
2556            }
2557            JCStatement copy =
2558                make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2559                                               systemArraycopyMethod),
2560                          List.of(make.Ident(valuesVar), make.Literal(0),
2561                                  make.Ident(resultVar), make.Literal(0),
2562                                  make.Select(make.Ident(valuesVar), syms.lengthVar))));
2563
2564            // template: return $result;
2565            JCStatement ret = make.Return(make.Ident(resultVar));
2566            valuesBody = List.<JCStatement>of(decl, copy, ret);
2567        }
2568
2569        JCMethodDecl valuesDef =
2570             make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2571
2572        enumDefs.append(valuesDef);
2573
2574        if (debugLower)
2575            System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2576
2577        /** The template for the following code is:
2578         *
2579         *     public static E valueOf(String name) {
2580         *         return (E)Enum.valueOf(E.class, name);
2581         *     }
2582         *
2583         *  where E is tree.sym
2584         */
2585        MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2586                         names.valueOf,
2587                         tree.sym.type,
2588                         List.of(syms.stringType));
2589        Assert.check((valueOfSym.flags() & STATIC) != 0);
2590        VarSymbol nameArgSym = valueOfSym.params.head;
2591        JCIdent nameVal = make.Ident(nameArgSym);
2592        JCStatement enum_ValueOf =
2593            make.Return(make.TypeCast(tree.sym.type,
2594                                      makeCall(make.Ident(syms.enumSym),
2595                                               names.valueOf,
2596                                               List.of(e_class, nameVal))));
2597        JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2598                                           make.Block(0, List.of(enum_ValueOf)));
2599        nameVal.sym = valueOf.params.head.sym;
2600        if (debugLower)
2601            System.err.println(tree.sym + ".valueOf = " + valueOf);
2602        enumDefs.append(valueOf);
2603
2604        enumDefs.appendList(otherDefs.toList());
2605        tree.defs = enumDefs.toList();
2606    }
2607        // where
2608        private MethodSymbol systemArraycopyMethod;
2609        private boolean useClone() {
2610            try {
2611                return syms.objectType.tsym.members().findFirst(names.clone) != null;
2612            }
2613            catch (CompletionFailure e) {
2614                return false;
2615            }
2616        }
2617
2618    /** Translate an enumeration constant and its initializer. */
2619    private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2620        JCNewClass varDef = (JCNewClass)var.init;
2621        varDef.args = varDef.args.
2622            prepend(makeLit(syms.intType, ordinal)).
2623            prepend(makeLit(syms.stringType, var.name.toString()));
2624    }
2625
2626    public void visitMethodDef(JCMethodDecl tree) {
2627        if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2628            // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2629            // argument list for each constructor of an enum.
2630            JCVariableDecl nameParam = make_at(tree.pos()).
2631                Param(names.fromString(target.syntheticNameChar() +
2632                                       "enum" + target.syntheticNameChar() + "name"),
2633                      syms.stringType, tree.sym);
2634            nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2635            JCVariableDecl ordParam = make.
2636                Param(names.fromString(target.syntheticNameChar() +
2637                                       "enum" + target.syntheticNameChar() +
2638                                       "ordinal"),
2639                      syms.intType, tree.sym);
2640            ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2641
2642            MethodSymbol m = tree.sym;
2643            tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2644
2645            m.extraParams = m.extraParams.prepend(ordParam.sym);
2646            m.extraParams = m.extraParams.prepend(nameParam.sym);
2647            Type olderasure = m.erasure(types);
2648            m.erasure_field = new MethodType(
2649                olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2650                olderasure.getReturnType(),
2651                olderasure.getThrownTypes(),
2652                syms.methodClass);
2653        }
2654
2655        JCMethodDecl prevMethodDef = currentMethodDef;
2656        MethodSymbol prevMethodSym = currentMethodSym;
2657        try {
2658            currentMethodDef = tree;
2659            currentMethodSym = tree.sym;
2660            visitMethodDefInternal(tree);
2661        } finally {
2662            currentMethodDef = prevMethodDef;
2663            currentMethodSym = prevMethodSym;
2664        }
2665    }
2666
2667    private void visitMethodDefInternal(JCMethodDecl tree) {
2668        if (tree.name == names.init &&
2669            (currentClass.isInner() || currentClass.isLocal())) {
2670            // We are seeing a constructor of an inner class.
2671            MethodSymbol m = tree.sym;
2672
2673            // Push a new proxy scope for constructor parameters.
2674            // and create definitions for any this$n and proxy parameters.
2675            proxies = proxies.dup(m);
2676            List<VarSymbol> prevOuterThisStack = outerThisStack;
2677            List<VarSymbol> fvs = freevars(currentClass);
2678            JCVariableDecl otdef = null;
2679            if (currentClass.hasOuterInstance())
2680                otdef = outerThisDef(tree.pos, m);
2681            List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER);
2682
2683            // Recursively translate result type, parameters and thrown list.
2684            tree.restype = translate(tree.restype);
2685            tree.params = translateVarDefs(tree.params);
2686            tree.thrown = translate(tree.thrown);
2687
2688            // when compiling stubs, don't process body
2689            if (tree.body == null) {
2690                result = tree;
2691                return;
2692            }
2693
2694            // Add this$n (if needed) in front of and free variables behind
2695            // constructor parameter list.
2696            tree.params = tree.params.appendList(fvdefs);
2697            if (currentClass.hasOuterInstance()) {
2698                tree.params = tree.params.prepend(otdef);
2699            }
2700
2701            // If this is an initial constructor, i.e., it does not start with
2702            // this(...), insert initializers for this$n and proxies
2703            // before (pre-1.4, after) the call to superclass constructor.
2704            JCStatement selfCall = translate(tree.body.stats.head);
2705
2706            List<JCStatement> added = List.nil();
2707            if (fvs.nonEmpty()) {
2708                List<Type> addedargtypes = List.nil();
2709                for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2710                    final Name pName = proxyName(l.head.name);
2711                    m.capturedLocals =
2712                        m.capturedLocals.prepend((VarSymbol)
2713                                                (proxies.findFirst(pName)));
2714                    if (TreeInfo.isInitialConstructor(tree)) {
2715                        added = added.prepend(
2716                          initField(tree.body.pos, pName));
2717                    }
2718                    addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2719                }
2720                Type olderasure = m.erasure(types);
2721                m.erasure_field = new MethodType(
2722                    olderasure.getParameterTypes().appendList(addedargtypes),
2723                    olderasure.getReturnType(),
2724                    olderasure.getThrownTypes(),
2725                    syms.methodClass);
2726            }
2727            if (currentClass.hasOuterInstance() &&
2728                TreeInfo.isInitialConstructor(tree))
2729            {
2730                added = added.prepend(initOuterThis(tree.body.pos));
2731            }
2732
2733            // pop local variables from proxy stack
2734            proxies = proxies.leave();
2735
2736            // recursively translate following local statements and
2737            // combine with this- or super-call
2738            List<JCStatement> stats = translate(tree.body.stats.tail);
2739            tree.body.stats = stats.prepend(selfCall).prependList(added);
2740            outerThisStack = prevOuterThisStack;
2741        } else {
2742            Map<Symbol, Symbol> prevLambdaTranslationMap =
2743                    lambdaTranslationMap;
2744            try {
2745                lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
2746                        tree.sym.name.startsWith(names.lambda) ?
2747                        makeTranslationMap(tree) : null;
2748                super.visitMethodDef(tree);
2749            } finally {
2750                lambdaTranslationMap = prevLambdaTranslationMap;
2751            }
2752        }
2753        result = tree;
2754    }
2755    //where
2756        private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
2757            Map<Symbol, Symbol> translationMap = new HashMap<>();
2758            for (JCVariableDecl vd : tree.params) {
2759                Symbol p = vd.sym;
2760                if (p != p.baseSymbol()) {
2761                    translationMap.put(p.baseSymbol(), p);
2762                }
2763            }
2764            return translationMap;
2765        }
2766
2767    public void visitTypeCast(JCTypeCast tree) {
2768        tree.clazz = translate(tree.clazz);
2769        if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2770            tree.expr = translate(tree.expr, tree.type);
2771        else
2772            tree.expr = translate(tree.expr);
2773        result = tree;
2774    }
2775
2776    public void visitNewClass(JCNewClass tree) {
2777        ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2778
2779        // Box arguments, if necessary
2780        boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2781        List<Type> argTypes = tree.constructor.type.getParameterTypes();
2782        if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2783        tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2784        tree.varargsElement = null;
2785
2786        // If created class is local, add free variables after
2787        // explicit constructor arguments.
2788        if (c.isLocal()) {
2789            tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2790        }
2791
2792        // If an access constructor is used, append null as a last argument.
2793        Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2794        if (constructor != tree.constructor) {
2795            tree.args = tree.args.append(makeNull());
2796            tree.constructor = constructor;
2797        }
2798
2799        // If created class has an outer instance, and new is qualified, pass
2800        // qualifier as first argument. If new is not qualified, pass the
2801        // correct outer instance as first argument.
2802        if (c.hasOuterInstance()) {
2803            JCExpression thisArg;
2804            if (tree.encl != null) {
2805                thisArg = attr.makeNullCheck(translate(tree.encl));
2806                thisArg.type = tree.encl.type;
2807            } else if (c.isLocal()) {
2808                // local class
2809                thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2810            } else {
2811                // nested class
2812                thisArg = makeOwnerThis(tree.pos(), c, false);
2813            }
2814            tree.args = tree.args.prepend(thisArg);
2815        }
2816        tree.encl = null;
2817
2818        // If we have an anonymous class, create its flat version, rather
2819        // than the class or interface following new.
2820        if (tree.def != null) {
2821            translate(tree.def);
2822            tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2823            tree.def = null;
2824        } else {
2825            tree.clazz = access(c, tree.clazz, enclOp, false);
2826        }
2827        result = tree;
2828    }
2829
2830    // Simplify conditionals with known constant controlling expressions.
2831    // This allows us to avoid generating supporting declarations for
2832    // the dead code, which will not be eliminated during code generation.
2833    // Note that Flow.isFalse and Flow.isTrue only return true
2834    // for constant expressions in the sense of JLS 15.27, which
2835    // are guaranteed to have no side-effects.  More aggressive
2836    // constant propagation would require that we take care to
2837    // preserve possible side-effects in the condition expression.
2838
2839    // One common case is equality expressions involving a constant and null.
2840    // Since null is not a constant expression (because null cannot be
2841    // represented in the constant pool), equality checks involving null are
2842    // not captured by Flow.isTrue/isFalse.
2843    // Equality checks involving a constant and null, e.g.
2844    //     "" == null
2845    // are safe to simplify as no side-effects can occur.
2846
2847    private boolean isTrue(JCTree exp) {
2848        if (exp.type.isTrue())
2849            return true;
2850        Boolean b = expValue(exp);
2851        return b == null ? false : b;
2852    }
2853    private boolean isFalse(JCTree exp) {
2854        if (exp.type.isFalse())
2855            return true;
2856        Boolean b = expValue(exp);
2857        return b == null ? false : !b;
2858    }
2859    /* look for (in)equality relations involving null.
2860     * return true - if expression is always true
2861     *       false - if expression is always false
2862     *        null - if expression cannot be eliminated
2863     */
2864    private Boolean expValue(JCTree exp) {
2865        while (exp.hasTag(PARENS))
2866            exp = ((JCParens)exp).expr;
2867
2868        boolean eq;
2869        switch (exp.getTag()) {
2870        case EQ: eq = true;  break;
2871        case NE: eq = false; break;
2872        default:
2873            return null;
2874        }
2875
2876        // we have a JCBinary(EQ|NE)
2877        // check if we have two literals (constants or null)
2878        JCBinary b = (JCBinary)exp;
2879        if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs);
2880        if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs);
2881        return null;
2882    }
2883    private Boolean expValueIsNull(boolean eq, JCTree t) {
2884        if (t.type.hasTag(BOT)) return Boolean.valueOf(eq);
2885        if (t.hasTag(LITERAL))  return Boolean.valueOf(!eq);
2886        return null;
2887    }
2888
2889    /** Visitor method for conditional expressions.
2890     */
2891    @Override
2892    public void visitConditional(JCConditional tree) {
2893        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2894        if (isTrue(cond)) {
2895            result = convert(translate(tree.truepart, tree.type), tree.type);
2896            addPrunedInfo(cond);
2897        } else if (isFalse(cond)) {
2898            result = convert(translate(tree.falsepart, tree.type), tree.type);
2899            addPrunedInfo(cond);
2900        } else {
2901            // Condition is not a compile-time constant.
2902            tree.truepart = translate(tree.truepart, tree.type);
2903            tree.falsepart = translate(tree.falsepart, tree.type);
2904            result = tree;
2905        }
2906    }
2907//where
2908    private JCExpression convert(JCExpression tree, Type pt) {
2909        if (tree.type == pt || tree.type.hasTag(BOT))
2910            return tree;
2911        JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree);
2912        result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2913                                                       : pt;
2914        return result;
2915    }
2916
2917    /** Visitor method for if statements.
2918     */
2919    public void visitIf(JCIf tree) {
2920        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2921        if (isTrue(cond)) {
2922            result = translate(tree.thenpart);
2923            addPrunedInfo(cond);
2924        } else if (isFalse(cond)) {
2925            if (tree.elsepart != null) {
2926                result = translate(tree.elsepart);
2927            } else {
2928                result = make.Skip();
2929            }
2930            addPrunedInfo(cond);
2931        } else {
2932            // Condition is not a compile-time constant.
2933            tree.thenpart = translate(tree.thenpart);
2934            tree.elsepart = translate(tree.elsepart);
2935            result = tree;
2936        }
2937    }
2938
2939    /** Visitor method for assert statements. Translate them away.
2940     */
2941    public void visitAssert(JCAssert tree) {
2942        DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2943        tree.cond = translate(tree.cond, syms.booleanType);
2944        if (!tree.cond.type.isTrue()) {
2945            JCExpression cond = assertFlagTest(tree.pos());
2946            List<JCExpression> exnArgs = (tree.detail == null) ?
2947                List.<JCExpression>nil() : List.of(translate(tree.detail));
2948            if (!tree.cond.type.isFalse()) {
2949                cond = makeBinary
2950                    (AND,
2951                     cond,
2952                     makeUnary(NOT, tree.cond));
2953            }
2954            result =
2955                make.If(cond,
2956                        make_at(tree).
2957                           Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2958                        null);
2959        } else {
2960            result = make.Skip();
2961        }
2962    }
2963
2964    public void visitApply(JCMethodInvocation tree) {
2965        Symbol meth = TreeInfo.symbol(tree.meth);
2966        List<Type> argtypes = meth.type.getParameterTypes();
2967        if (meth.name == names.init && meth.owner == syms.enumSym)
2968            argtypes = argtypes.tail.tail;
2969        tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2970        tree.varargsElement = null;
2971        Name methName = TreeInfo.name(tree.meth);
2972        if (meth.name==names.init) {
2973            // We are seeing a this(...) or super(...) constructor call.
2974            // If an access constructor is used, append null as a last argument.
2975            Symbol constructor = accessConstructor(tree.pos(), meth);
2976            if (constructor != meth) {
2977                tree.args = tree.args.append(makeNull());
2978                TreeInfo.setSymbol(tree.meth, constructor);
2979            }
2980
2981            // If we are calling a constructor of a local class, add
2982            // free variables after explicit constructor arguments.
2983            ClassSymbol c = (ClassSymbol)constructor.owner;
2984            if (c.isLocal()) {
2985                tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2986            }
2987
2988            // If we are calling a constructor of an enum class, pass
2989            // along the name and ordinal arguments
2990            if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2991                List<JCVariableDecl> params = currentMethodDef.params;
2992                if (currentMethodSym.owner.hasOuterInstance())
2993                    params = params.tail; // drop this$n
2994                tree.args = tree.args
2995                    .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2996                    .prepend(make.Ident(params.head.sym)); // name
2997            }
2998
2999            // If we are calling a constructor of a class with an outer
3000            // instance, and the call
3001            // is qualified, pass qualifier as first argument in front of
3002            // the explicit constructor arguments. If the call
3003            // is not qualified, pass the correct outer instance as
3004            // first argument.
3005            if (c.hasOuterInstance()) {
3006                JCExpression thisArg;
3007                if (tree.meth.hasTag(SELECT)) {
3008                    thisArg = attr.
3009                        makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
3010                    tree.meth = make.Ident(constructor);
3011                    ((JCIdent) tree.meth).name = methName;
3012                } else if (c.isLocal() || methName == names._this){
3013                    // local class or this() call
3014                    thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
3015                } else {
3016                    // super() call of nested class - never pick 'this'
3017                    thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
3018                }
3019                tree.args = tree.args.prepend(thisArg);
3020            }
3021        } else {
3022            // We are seeing a normal method invocation; translate this as usual.
3023            tree.meth = translate(tree.meth);
3024
3025            // If the translated method itself is an Apply tree, we are
3026            // seeing an access method invocation. In this case, append
3027            // the method arguments to the arguments of the access method.
3028            if (tree.meth.hasTag(APPLY)) {
3029                JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3030                app.args = tree.args.prependList(app.args);
3031                result = app;
3032                return;
3033            }
3034        }
3035        result = tree;
3036    }
3037
3038    List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3039        List<JCExpression> args = _args;
3040        if (parameters.isEmpty()) return args;
3041        boolean anyChanges = false;
3042        ListBuffer<JCExpression> result = new ListBuffer<>();
3043        while (parameters.tail.nonEmpty()) {
3044            JCExpression arg = translate(args.head, parameters.head);
3045            anyChanges |= (arg != args.head);
3046            result.append(arg);
3047            args = args.tail;
3048            parameters = parameters.tail;
3049        }
3050        Type parameter = parameters.head;
3051        if (varargsElement != null) {
3052            anyChanges = true;
3053            ListBuffer<JCExpression> elems = new ListBuffer<>();
3054            while (args.nonEmpty()) {
3055                JCExpression arg = translate(args.head, varargsElement);
3056                elems.append(arg);
3057                args = args.tail;
3058            }
3059            JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3060                                               List.<JCExpression>nil(),
3061                                               elems.toList());
3062            boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3063            result.append(boxedArgs);
3064        } else {
3065            if (args.length() != 1) throw new AssertionError(args);
3066            JCExpression arg = translate(args.head, parameter);
3067            anyChanges |= (arg != args.head);
3068            result.append(arg);
3069            if (!anyChanges) return _args;
3070        }
3071        return result.toList();
3072    }
3073
3074    /** Expand a boxing or unboxing conversion if needed. */
3075    @SuppressWarnings("unchecked") // XXX unchecked
3076    <T extends JCExpression> T boxIfNeeded(T tree, Type type) {
3077        boolean havePrimitive = tree.type.isPrimitive();
3078        if (havePrimitive == type.isPrimitive())
3079            return tree;
3080        if (havePrimitive) {
3081            Type unboxedTarget = types.unboxedType(type);
3082            if (!unboxedTarget.hasTag(NONE)) {
3083                if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3084                    tree.type = unboxedTarget.constType(tree.type.constValue());
3085                return (T)boxPrimitive(tree, types.erasure(type));
3086            } else {
3087                tree = (T)boxPrimitive(tree);
3088            }
3089        } else {
3090            tree = (T)unbox(tree, type);
3091        }
3092        return tree;
3093    }
3094
3095    /** Box up a single primitive expression. */
3096    JCExpression boxPrimitive(JCExpression tree) {
3097        return boxPrimitive(tree, types.boxedClass(tree.type).type);
3098    }
3099
3100    /** Box up a single primitive expression. */
3101    JCExpression boxPrimitive(JCExpression tree, Type box) {
3102        make_at(tree.pos());
3103        Symbol valueOfSym = lookupMethod(tree.pos(),
3104                                         names.valueOf,
3105                                         box,
3106                                         List.<Type>nil()
3107                                         .prepend(tree.type));
3108        return make.App(make.QualIdent(valueOfSym), List.of(tree));
3109    }
3110
3111    /** Unbox an object to a primitive value. */
3112    JCExpression unbox(JCExpression tree, Type primitive) {
3113        Type unboxedType = types.unboxedType(tree.type);
3114        if (unboxedType.hasTag(NONE)) {
3115            unboxedType = primitive;
3116            if (!unboxedType.isPrimitive())
3117                throw new AssertionError(unboxedType);
3118            make_at(tree.pos());
3119            tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3120        } else {
3121            // There must be a conversion from unboxedType to primitive.
3122            if (!types.isSubtype(unboxedType, primitive))
3123                throw new AssertionError(tree);
3124        }
3125        make_at(tree.pos());
3126        Symbol valueSym = lookupMethod(tree.pos(),
3127                                       unboxedType.tsym.name.append(names.Value), // x.intValue()
3128                                       tree.type,
3129                                       List.<Type>nil());
3130        return make.App(make.Select(tree, valueSym));
3131    }
3132
3133    /** Visitor method for parenthesized expressions.
3134     *  If the subexpression has changed, omit the parens.
3135     */
3136    public void visitParens(JCParens tree) {
3137        JCTree expr = translate(tree.expr);
3138        result = ((expr == tree.expr) ? tree : expr);
3139    }
3140
3141    public void visitIndexed(JCArrayAccess tree) {
3142        tree.indexed = translate(tree.indexed);
3143        tree.index = translate(tree.index, syms.intType);
3144        result = tree;
3145    }
3146
3147    public void visitAssign(JCAssign tree) {
3148        tree.lhs = translate(tree.lhs, tree);
3149        tree.rhs = translate(tree.rhs, tree.lhs.type);
3150
3151        // If translated left hand side is an Apply, we are
3152        // seeing an access method invocation. In this case, append
3153        // right hand side as last argument of the access method.
3154        if (tree.lhs.hasTag(APPLY)) {
3155            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3156            app.args = List.of(tree.rhs).prependList(app.args);
3157            result = app;
3158        } else {
3159            result = tree;
3160        }
3161    }
3162
3163    public void visitAssignop(final JCAssignOp tree) {
3164        JCTree lhsAccess = access(TreeInfo.skipParens(tree.lhs));
3165        final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3166            tree.operator.type.getReturnType().isPrimitive();
3167
3168        if (boxingReq || lhsAccess.hasTag(APPLY)) {
3169            // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3170            // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3171            // (but without recomputing x)
3172            JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3173                    public JCExpression build(final JCExpression lhs) {
3174                        JCTree.Tag newTag = tree.getTag().noAssignOp();
3175                        // Erasure (TransTypes) can change the type of
3176                        // tree.lhs.  However, we can still get the
3177                        // unerased type of tree.lhs as it is stored
3178                        // in tree.type in Attr.
3179                        Symbol newOperator = operators.resolveBinary(tree,
3180                                                                      newTag,
3181                                                                      tree.type,
3182                                                                      tree.rhs.type);
3183                        JCExpression expr = lhs;
3184                        if (expr.type != tree.type)
3185                            expr = make.TypeCast(tree.type, expr);
3186                        JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3187                        opResult.operator = newOperator;
3188                        opResult.type = newOperator.type.getReturnType();
3189                        JCExpression newRhs = boxingReq ?
3190                            make.TypeCast(types.unboxedType(tree.type), opResult) :
3191                            opResult;
3192                        return make.Assign(lhs, newRhs).setType(tree.type);
3193                    }
3194                });
3195            result = translate(newTree);
3196            return;
3197        }
3198        tree.lhs = translate(tree.lhs, tree);
3199        tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3200
3201        // If translated left hand side is an Apply, we are
3202        // seeing an access method invocation. In this case, append
3203        // right hand side as last argument of the access method.
3204        if (tree.lhs.hasTag(APPLY)) {
3205            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3206            // if operation is a += on strings,
3207            // make sure to convert argument to string
3208            JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
3209              ? makeString(tree.rhs)
3210              : tree.rhs;
3211            app.args = List.of(rhs).prependList(app.args);
3212            result = app;
3213        } else {
3214            result = tree;
3215        }
3216    }
3217
3218    /** Lower a tree of the form e++ or e-- where e is an object type */
3219    JCExpression lowerBoxedPostop(final JCUnary tree) {
3220        // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3221        // or
3222        // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3223        // where OP is += or -=
3224        final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3225        return abstractLval(tree.arg, new TreeBuilder() {
3226                public JCExpression build(final JCExpression tmp1) {
3227                    return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3228                            public JCExpression build(final JCExpression tmp2) {
3229                                JCTree.Tag opcode = (tree.hasTag(POSTINC))
3230                                    ? PLUS_ASG : MINUS_ASG;
3231                                JCTree lhs = cast
3232                                    ? make.TypeCast(tree.arg.type, tmp1)
3233                                    : tmp1;
3234                                JCExpression update = makeAssignop(opcode,
3235                                                             lhs,
3236                                                             make.Literal(1));
3237                                return makeComma(update, tmp2);
3238                            }
3239                        });
3240                }
3241            });
3242    }
3243
3244    public void visitUnary(JCUnary tree) {
3245        boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3246        if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3247            switch(tree.getTag()) {
3248            case PREINC:            // ++ e
3249                    // translate to e += 1
3250            case PREDEC:            // -- e
3251                    // translate to e -= 1
3252                {
3253                    JCTree.Tag opcode = (tree.hasTag(PREINC))
3254                        ? PLUS_ASG : MINUS_ASG;
3255                    JCAssignOp newTree = makeAssignop(opcode,
3256                                                    tree.arg,
3257                                                    make.Literal(1));
3258                    result = translate(newTree, tree.type);
3259                    return;
3260                }
3261            case POSTINC:           // e ++
3262            case POSTDEC:           // e --
3263                {
3264                    result = translate(lowerBoxedPostop(tree), tree.type);
3265                    return;
3266                }
3267            }
3268            throw new AssertionError(tree);
3269        }
3270
3271        tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3272
3273        if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3274            tree.type = cfolder.fold1(bool_not, tree.arg.type);
3275        }
3276
3277        // If translated left hand side is an Apply, we are
3278        // seeing an access method invocation. In this case, return
3279        // that access method invocation as result.
3280        if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3281            result = tree.arg;
3282        } else {
3283            result = tree;
3284        }
3285    }
3286
3287    public void visitBinary(JCBinary tree) {
3288        List<Type> formals = tree.operator.type.getParameterTypes();
3289        JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3290        switch (tree.getTag()) {
3291        case OR:
3292            if (isTrue(lhs)) {
3293                result = lhs;
3294                return;
3295            }
3296            if (isFalse(lhs)) {
3297                result = translate(tree.rhs, formals.tail.head);
3298                return;
3299            }
3300            break;
3301        case AND:
3302            if (isFalse(lhs)) {
3303                result = lhs;
3304                return;
3305            }
3306            if (isTrue(lhs)) {
3307                result = translate(tree.rhs, formals.tail.head);
3308                return;
3309            }
3310            break;
3311        }
3312        tree.rhs = translate(tree.rhs, formals.tail.head);
3313        result = tree;
3314    }
3315
3316    public void visitIdent(JCIdent tree) {
3317        result = access(tree.sym, tree, enclOp, false);
3318    }
3319
3320    /** Translate away the foreach loop.  */
3321    public void visitForeachLoop(JCEnhancedForLoop tree) {
3322        if (types.elemtype(tree.expr.type) == null)
3323            visitIterableForeachLoop(tree);
3324        else
3325            visitArrayForeachLoop(tree);
3326    }
3327        // where
3328        /**
3329         * A statement of the form
3330         *
3331         * <pre>
3332         *     for ( T v : arrayexpr ) stmt;
3333         * </pre>
3334         *
3335         * (where arrayexpr is of an array type) gets translated to
3336         *
3337         * <pre>{@code
3338         *     for ( { arraytype #arr = arrayexpr;
3339         *             int #len = array.length;
3340         *             int #i = 0; };
3341         *           #i < #len; i$++ ) {
3342         *         T v = arr$[#i];
3343         *         stmt;
3344         *     }
3345         * }</pre>
3346         *
3347         * where #arr, #len, and #i are freshly named synthetic local variables.
3348         */
3349        private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3350            make_at(tree.expr.pos());
3351            VarSymbol arraycache = new VarSymbol(SYNTHETIC,
3352                                                 names.fromString("arr" + target.syntheticNameChar()),
3353                                                 tree.expr.type,
3354                                                 currentMethodSym);
3355            JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3356            VarSymbol lencache = new VarSymbol(SYNTHETIC,
3357                                               names.fromString("len" + target.syntheticNameChar()),
3358                                               syms.intType,
3359                                               currentMethodSym);
3360            JCStatement lencachedef = make.
3361                VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3362            VarSymbol index = new VarSymbol(SYNTHETIC,
3363                                            names.fromString("i" + target.syntheticNameChar()),
3364                                            syms.intType,
3365                                            currentMethodSym);
3366
3367            JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3368            indexdef.init.type = indexdef.type = syms.intType.constType(0);
3369
3370            List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3371            JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3372
3373            JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3374
3375            Type elemtype = types.elemtype(tree.expr.type);
3376            JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3377                                                    make.Ident(index)).setType(elemtype);
3378            JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3379                                                  tree.var.name,
3380                                                  tree.var.vartype,
3381                                                  loopvarinit).setType(tree.var.type);
3382            loopvardef.sym = tree.var.sym;
3383            JCBlock body = make.
3384                Block(0, List.of(loopvardef, tree.body));
3385
3386            result = translate(make.
3387                               ForLoop(loopinit,
3388                                       cond,
3389                                       List.of(step),
3390                                       body));
3391            patchTargets(body, tree, result);
3392        }
3393        /** Patch up break and continue targets. */
3394        private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3395            class Patcher extends TreeScanner {
3396                public void visitBreak(JCBreak tree) {
3397                    if (tree.target == src)
3398                        tree.target = dest;
3399                }
3400                public void visitContinue(JCContinue tree) {
3401                    if (tree.target == src)
3402                        tree.target = dest;
3403                }
3404                public void visitClassDef(JCClassDecl tree) {}
3405            }
3406            new Patcher().scan(body);
3407        }
3408        /**
3409         * A statement of the form
3410         *
3411         * <pre>
3412         *     for ( T v : coll ) stmt ;
3413         * </pre>
3414         *
3415         * (where coll implements {@code Iterable<? extends T>}) gets translated to
3416         *
3417         * <pre>{@code
3418         *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3419         *         T v = (T) #i.next();
3420         *         stmt;
3421         *     }
3422         * }</pre>
3423         *
3424         * where #i is a freshly named synthetic local variable.
3425         */
3426        private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3427            make_at(tree.expr.pos());
3428            Type iteratorTarget = syms.objectType;
3429            Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type),
3430                                              syms.iterableType.tsym);
3431            if (iterableType.getTypeArguments().nonEmpty())
3432                iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3433            Type eType = types.skipTypeVars(tree.expr.type, false);
3434            tree.expr.type = types.erasure(eType);
3435            if (eType.isCompound())
3436                tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3437            Symbol iterator = lookupMethod(tree.expr.pos(),
3438                                           names.iterator,
3439                                           eType,
3440                                           List.<Type>nil());
3441            VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
3442                                            types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)),
3443                                            currentMethodSym);
3444
3445             JCStatement init = make.
3446                VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3447                     .setType(types.erasure(iterator.type))));
3448
3449            Symbol hasNext = lookupMethod(tree.expr.pos(),
3450                                          names.hasNext,
3451                                          itvar.type,
3452                                          List.<Type>nil());
3453            JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3454            Symbol next = lookupMethod(tree.expr.pos(),
3455                                       names.next,
3456                                       itvar.type,
3457                                       List.<Type>nil());
3458            JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3459            if (tree.var.type.isPrimitive())
3460                vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
3461            else
3462                vardefinit = make.TypeCast(tree.var.type, vardefinit);
3463            JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3464                                                  tree.var.name,
3465                                                  tree.var.vartype,
3466                                                  vardefinit).setType(tree.var.type);
3467            indexDef.sym = tree.var.sym;
3468            JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3469            body.endpos = TreeInfo.endPos(tree.body);
3470            result = translate(make.
3471                ForLoop(List.of(init),
3472                        cond,
3473                        List.<JCExpressionStatement>nil(),
3474                        body));
3475            patchTargets(body, tree, result);
3476        }
3477
3478    public void visitVarDef(JCVariableDecl tree) {
3479        MethodSymbol oldMethodSym = currentMethodSym;
3480        tree.mods = translate(tree.mods);
3481        tree.vartype = translate(tree.vartype);
3482        if (currentMethodSym == null) {
3483            // A class or instance field initializer.
3484            currentMethodSym =
3485                new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3486                                 names.empty, null,
3487                                 currentClass);
3488        }
3489        if (tree.init != null) tree.init = translate(tree.init, tree.type);
3490        result = tree;
3491        currentMethodSym = oldMethodSym;
3492    }
3493
3494    public void visitBlock(JCBlock tree) {
3495        MethodSymbol oldMethodSym = currentMethodSym;
3496        if (currentMethodSym == null) {
3497            // Block is a static or instance initializer.
3498            currentMethodSym =
3499                new MethodSymbol(tree.flags | BLOCK,
3500                                 names.empty, null,
3501                                 currentClass);
3502        }
3503        super.visitBlock(tree);
3504        currentMethodSym = oldMethodSym;
3505    }
3506
3507    public void visitDoLoop(JCDoWhileLoop tree) {
3508        tree.body = translate(tree.body);
3509        tree.cond = translate(tree.cond, syms.booleanType);
3510        result = tree;
3511    }
3512
3513    public void visitWhileLoop(JCWhileLoop tree) {
3514        tree.cond = translate(tree.cond, syms.booleanType);
3515        tree.body = translate(tree.body);
3516        result = tree;
3517    }
3518
3519    public void visitForLoop(JCForLoop tree) {
3520        tree.init = translate(tree.init);
3521        if (tree.cond != null)
3522            tree.cond = translate(tree.cond, syms.booleanType);
3523        tree.step = translate(tree.step);
3524        tree.body = translate(tree.body);
3525        result = tree;
3526    }
3527
3528    public void visitReturn(JCReturn tree) {
3529        if (tree.expr != null)
3530            tree.expr = translate(tree.expr,
3531                                  types.erasure(currentMethodDef
3532                                                .restype.type));
3533        result = tree;
3534    }
3535
3536    public void visitSwitch(JCSwitch tree) {
3537        Type selsuper = types.supertype(tree.selector.type);
3538        boolean enumSwitch = selsuper != null &&
3539            (tree.selector.type.tsym.flags() & ENUM) != 0;
3540        boolean stringSwitch = selsuper != null &&
3541            types.isSameType(tree.selector.type, syms.stringType);
3542        Type target = enumSwitch ? tree.selector.type :
3543            (stringSwitch? syms.stringType : syms.intType);
3544        tree.selector = translate(tree.selector, target);
3545        tree.cases = translateCases(tree.cases);
3546        if (enumSwitch) {
3547            result = visitEnumSwitch(tree);
3548        } else if (stringSwitch) {
3549            result = visitStringSwitch(tree);
3550        } else {
3551            result = tree;
3552        }
3553    }
3554
3555    public JCTree visitEnumSwitch(JCSwitch tree) {
3556        TypeSymbol enumSym = tree.selector.type.tsym;
3557        EnumMapping map = mapForEnum(tree.pos(), enumSym);
3558        make_at(tree.pos());
3559        Symbol ordinalMethod = lookupMethod(tree.pos(),
3560                                            names.ordinal,
3561                                            tree.selector.type,
3562                                            List.<Type>nil());
3563        JCArrayAccess selector = make.Indexed(map.mapVar,
3564                                        make.App(make.Select(tree.selector,
3565                                                             ordinalMethod)));
3566        ListBuffer<JCCase> cases = new ListBuffer<>();
3567        for (JCCase c : tree.cases) {
3568            if (c.pat != null) {
3569                VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3570                JCLiteral pat = map.forConstant(label);
3571                cases.append(make.Case(pat, c.stats));
3572            } else {
3573                cases.append(c);
3574            }
3575        }
3576        JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3577        patchTargets(enumSwitch, tree, enumSwitch);
3578        return enumSwitch;
3579    }
3580
3581    public JCTree visitStringSwitch(JCSwitch tree) {
3582        List<JCCase> caseList = tree.getCases();
3583        int alternatives = caseList.size();
3584
3585        if (alternatives == 0) { // Strange but legal possibility
3586            return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3587        } else {
3588            /*
3589             * The general approach used is to translate a single
3590             * string switch statement into a series of two chained
3591             * switch statements: the first a synthesized statement
3592             * switching on the argument string's hash value and
3593             * computing a string's position in the list of original
3594             * case labels, if any, followed by a second switch on the
3595             * computed integer value.  The second switch has the same
3596             * code structure as the original string switch statement
3597             * except that the string case labels are replaced with
3598             * positional integer constants starting at 0.
3599             *
3600             * The first switch statement can be thought of as an
3601             * inlined map from strings to their position in the case
3602             * label list.  An alternate implementation would use an
3603             * actual Map for this purpose, as done for enum switches.
3604             *
3605             * With some additional effort, it would be possible to
3606             * use a single switch statement on the hash code of the
3607             * argument, but care would need to be taken to preserve
3608             * the proper control flow in the presence of hash
3609             * collisions and other complications, such as
3610             * fallthroughs.  Switch statements with one or two
3611             * alternatives could also be specially translated into
3612             * if-then statements to omit the computation of the hash
3613             * code.
3614             *
3615             * The generated code assumes that the hashing algorithm
3616             * of String is the same in the compilation environment as
3617             * in the environment the code will run in.  The string
3618             * hashing algorithm in the SE JDK has been unchanged
3619             * since at least JDK 1.2.  Since the algorithm has been
3620             * specified since that release as well, it is very
3621             * unlikely to be changed in the future.
3622             *
3623             * Different hashing algorithms, such as the length of the
3624             * strings or a perfect hashing algorithm over the
3625             * particular set of case labels, could potentially be
3626             * used instead of String.hashCode.
3627             */
3628
3629            ListBuffer<JCStatement> stmtList = new ListBuffer<>();
3630
3631            // Map from String case labels to their original position in
3632            // the list of case labels.
3633            Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f);
3634
3635            // Map of hash codes to the string case labels having that hashCode.
3636            Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f);
3637
3638            int casePosition = 0;
3639            for(JCCase oneCase : caseList) {
3640                JCExpression expression = oneCase.getExpression();
3641
3642                if (expression != null) { // expression for a "default" case is null
3643                    String labelExpr = (String) expression.type.constValue();
3644                    Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3645                    Assert.checkNull(mapping);
3646                    int hashCode = labelExpr.hashCode();
3647
3648                    Set<String> stringSet = hashToString.get(hashCode);
3649                    if (stringSet == null) {
3650                        stringSet = new LinkedHashSet<>(1, 1.0f);
3651                        stringSet.add(labelExpr);
3652                        hashToString.put(hashCode, stringSet);
3653                    } else {
3654                        boolean added = stringSet.add(labelExpr);
3655                        Assert.check(added);
3656                    }
3657                }
3658                casePosition++;
3659            }
3660
3661            // Synthesize a switch statement that has the effect of
3662            // mapping from a string to the integer position of that
3663            // string in the list of case labels.  This is done by
3664            // switching on the hashCode of the string followed by an
3665            // if-then-else chain comparing the input for equality
3666            // with all the case labels having that hash value.
3667
3668            /*
3669             * s$ = top of stack;
3670             * tmp$ = -1;
3671             * switch($s.hashCode()) {
3672             *     case caseLabel.hashCode:
3673             *         if (s$.equals("caseLabel_1")
3674             *           tmp$ = caseLabelToPosition("caseLabel_1");
3675             *         else if (s$.equals("caseLabel_2"))
3676             *           tmp$ = caseLabelToPosition("caseLabel_2");
3677             *         ...
3678             *         break;
3679             * ...
3680             * }
3681             */
3682
3683            VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3684                                               names.fromString("s" + tree.pos + target.syntheticNameChar()),
3685                                               syms.stringType,
3686                                               currentMethodSym);
3687            stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3688
3689            VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3690                                                 names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3691                                                 syms.intType,
3692                                                 currentMethodSym);
3693            JCVariableDecl dollar_tmp_def =
3694                (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3695            dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3696            stmtList.append(dollar_tmp_def);
3697            ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
3698            // hashCode will trigger nullcheck on original switch expression
3699            JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3700                                                       names.hashCode,
3701                                                       List.<JCExpression>nil()).setType(syms.intType);
3702            JCSwitch switch1 = make.Switch(hashCodeCall,
3703                                        caseBuffer.toList());
3704            for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3705                int hashCode = entry.getKey();
3706                Set<String> stringsWithHashCode = entry.getValue();
3707                Assert.check(stringsWithHashCode.size() >= 1);
3708
3709                JCStatement elsepart = null;
3710                for(String caseLabel : stringsWithHashCode ) {
3711                    JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3712                                                                   names.equals,
3713                                                                   List.<JCExpression>of(make.Literal(caseLabel)));
3714                    elsepart = make.If(stringEqualsCall,
3715                                       make.Exec(make.Assign(make.Ident(dollar_tmp),
3716                                                             make.Literal(caseLabelToPosition.get(caseLabel))).
3717                                                 setType(dollar_tmp.type)),
3718                                       elsepart);
3719                }
3720
3721                ListBuffer<JCStatement> lb = new ListBuffer<>();
3722                JCBreak breakStmt = make.Break(null);
3723                breakStmt.target = switch1;
3724                lb.append(elsepart).append(breakStmt);
3725
3726                caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3727            }
3728
3729            switch1.cases = caseBuffer.toList();
3730            stmtList.append(switch1);
3731
3732            // Make isomorphic switch tree replacing string labels
3733            // with corresponding integer ones from the label to
3734            // position map.
3735
3736            ListBuffer<JCCase> lb = new ListBuffer<>();
3737            JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3738            for(JCCase oneCase : caseList ) {
3739                // Rewire up old unlabeled break statements to the
3740                // replacement switch being created.
3741                patchTargets(oneCase, tree, switch2);
3742
3743                boolean isDefault = (oneCase.getExpression() == null);
3744                JCExpression caseExpr;
3745                if (isDefault)
3746                    caseExpr = null;
3747                else {
3748                    caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3749                                                                                                getExpression()).
3750                                                                    type.constValue()));
3751                }
3752
3753                lb.append(make.Case(caseExpr,
3754                                    oneCase.getStatements()));
3755            }
3756
3757            switch2.cases = lb.toList();
3758            stmtList.append(switch2);
3759
3760            return make.Block(0L, stmtList.toList());
3761        }
3762    }
3763
3764    public void visitNewArray(JCNewArray tree) {
3765        tree.elemtype = translate(tree.elemtype);
3766        for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3767            if (t.head != null) t.head = translate(t.head, syms.intType);
3768        tree.elems = translate(tree.elems, types.elemtype(tree.type));
3769        result = tree;
3770    }
3771
3772    public void visitSelect(JCFieldAccess tree) {
3773        // need to special case-access of the form C.super.x
3774        // these will always need an access method, unless C
3775        // is a default interface subclassed by the current class.
3776        boolean qualifiedSuperAccess =
3777            tree.selected.hasTag(SELECT) &&
3778            TreeInfo.name(tree.selected) == names._super &&
3779            !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
3780        tree.selected = translate(tree.selected);
3781        if (tree.name == names._class) {
3782            result = classOf(tree.selected);
3783        }
3784        else if (tree.name == names._super &&
3785                types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
3786            //default super call!! Not a classic qualified super call
3787            TypeSymbol supSym = tree.selected.type.tsym;
3788            Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
3789            result = tree;
3790        }
3791        else if (tree.name == names._this || tree.name == names._super) {
3792            result = makeThis(tree.pos(), tree.selected.type.tsym);
3793        }
3794        else
3795            result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3796    }
3797
3798    public void visitLetExpr(LetExpr tree) {
3799        tree.defs = translateVarDefs(tree.defs);
3800        tree.expr = translate(tree.expr, tree.type);
3801        result = tree;
3802    }
3803
3804    // There ought to be nothing to rewrite here;
3805    // we don't generate code.
3806    public void visitAnnotation(JCAnnotation tree) {
3807        result = tree;
3808    }
3809
3810    @Override
3811    public void visitTry(JCTry tree) {
3812        if (tree.resources.nonEmpty()) {
3813            result = makeTwrTry(tree);
3814            return;
3815        }
3816
3817        boolean hasBody = tree.body.getStatements().nonEmpty();
3818        boolean hasCatchers = tree.catchers.nonEmpty();
3819        boolean hasFinally = tree.finalizer != null &&
3820                tree.finalizer.getStatements().nonEmpty();
3821
3822        if (!hasCatchers && !hasFinally) {
3823            result = translate(tree.body);
3824            return;
3825        }
3826
3827        if (!hasBody) {
3828            if (hasFinally) {
3829                result = translate(tree.finalizer);
3830            } else {
3831                result = translate(tree.body);
3832            }
3833            return;
3834        }
3835
3836        // no optimizations possible
3837        super.visitTry(tree);
3838    }
3839
3840/**************************************************************************
3841 * main method
3842 *************************************************************************/
3843
3844    /** Translate a toplevel class and return a list consisting of
3845     *  the translated class and translated versions of all inner classes.
3846     *  @param env   The attribution environment current at the class definition.
3847     *               We need this for resolving some additional symbols.
3848     *  @param cdef  The tree representing the class definition.
3849     */
3850    public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3851        ListBuffer<JCTree> translated = null;
3852        try {
3853            attrEnv = env;
3854            this.make = make;
3855            endPosTable = env.toplevel.endPositions;
3856            currentClass = null;
3857            currentMethodDef = null;
3858            outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3859            outermostMemberDef = null;
3860            this.translated = new ListBuffer<>();
3861            classdefs = new HashMap<>();
3862            actualSymbols = new HashMap<>();
3863            freevarCache = new HashMap<>();
3864            proxies = WriteableScope.create(syms.noSymbol);
3865            twrVars = WriteableScope.create(syms.noSymbol);
3866            outerThisStack = List.nil();
3867            accessNums = new HashMap<>();
3868            accessSyms = new HashMap<>();
3869            accessConstrs = new HashMap<>();
3870            accessConstrTags = List.nil();
3871            accessed = new ListBuffer<>();
3872            translate(cdef, (JCExpression)null);
3873            for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3874                makeAccessible(l.head);
3875            for (EnumMapping map : enumSwitchMap.values())
3876                map.translate();
3877            checkConflicts(this.translated.toList());
3878            checkAccessConstructorTags();
3879            translated = this.translated;
3880        } finally {
3881            // note that recursive invocations of this method fail hard
3882            attrEnv = null;
3883            this.make = null;
3884            endPosTable = null;
3885            currentClass = null;
3886            currentMethodDef = null;
3887            outermostClassDef = null;
3888            outermostMemberDef = null;
3889            this.translated = null;
3890            classdefs = null;
3891            actualSymbols = null;
3892            freevarCache = null;
3893            proxies = null;
3894            outerThisStack = null;
3895            accessNums = null;
3896            accessSyms = null;
3897            accessConstrs = null;
3898            accessConstrTags = null;
3899            accessed = null;
3900            enumSwitchMap.clear();
3901            assertionsDisabledClassCache = null;
3902        }
3903        return translated.toList();
3904    }
3905}
3906