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