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