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