Lower.java revision 3294:9adfb22ff08f
1230557Sjimharris/*
2230557Sjimharris * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
3230557Sjimharris * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4230557Sjimharris *
5230557Sjimharris * This code is free software; you can redistribute it and/or modify it
6230557Sjimharris * under the terms of the GNU General Public License version 2 only, as
7230557Sjimharris * published by the Free Software Foundation.  Oracle designates this
8230557Sjimharris * particular file as subject to the "Classpath" exception as provided
9230557Sjimharris * by Oracle in the LICENSE file that accompanied this code.
10230557Sjimharris *
11230557Sjimharris * This code is distributed in the hope that it will be useful, but WITHOUT
12230557Sjimharris * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13230557Sjimharris * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14230557Sjimharris * version 2 for more details (a copy is included in the LICENSE file that
15230557Sjimharris * accompanied this code).
16230557Sjimharris *
17230557Sjimharris * You should have received a copy of the GNU General Public License version
18230557Sjimharris * 2 along with this work; if not, write to the Free Software Foundation,
19230557Sjimharris * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20230557Sjimharris *
21230557Sjimharris * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22230557Sjimharris * or visit www.oracle.com if you need additional information or have any
23230557Sjimharris * questions.
24230557Sjimharris */
25230557Sjimharris
26230557Sjimharrispackage com.sun.tools.javac.comp;
27230557Sjimharris
28230557Sjimharrisimport java.util.*;
29230557Sjimharris
30230557Sjimharrisimport com.sun.tools.javac.code.*;
31230557Sjimharrisimport com.sun.tools.javac.code.Kinds.KindSelector;
32230557Sjimharrisimport com.sun.tools.javac.code.Scope.WriteableScope;
33230557Sjimharrisimport com.sun.tools.javac.jvm.*;
34230557Sjimharrisimport com.sun.tools.javac.main.Option.PkgInfo;
35230557Sjimharrisimport com.sun.tools.javac.tree.*;
36230557Sjimharrisimport com.sun.tools.javac.util.*;
37230557Sjimharrisimport com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
38230557Sjimharrisimport com.sun.tools.javac.util.List;
39230557Sjimharris
40230557Sjimharrisimport com.sun.tools.javac.code.Symbol.*;
41230557Sjimharrisimport com.sun.tools.javac.tree.JCTree.*;
42230557Sjimharrisimport com.sun.tools.javac.code.Type.*;
43230557Sjimharris
44230557Sjimharrisimport com.sun.tools.javac.jvm.Target;
45230557Sjimharrisimport com.sun.tools.javac.tree.EndPosTable;
46230557Sjimharris
47230557Sjimharrisimport static com.sun.tools.javac.code.Flags.*;
48230557Sjimharrisimport static com.sun.tools.javac.code.Flags.BLOCK;
49230557Sjimharrisimport static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
50230557Sjimharrisimport static com.sun.tools.javac.code.TypeTag.*;
51230557Sjimharrisimport static com.sun.tools.javac.code.Kinds.Kind.*;
52230557Sjimharrisimport static com.sun.tools.javac.jvm.ByteCodes.*;
53230557Sjimharrisimport static com.sun.tools.javac.tree.JCTree.Tag.*;
54230557Sjimharris
55230557Sjimharris/** This pass translates away some syntactic sugar: inner classes,
56230557Sjimharris *  class literals, assertions, foreach loops, etc.
57230557Sjimharris *
58230557Sjimharris *  <p><b>This is NOT part of any supported API.
59230557Sjimharris *  If you write code that depends on this, you do so at your own risk.
60230557Sjimharris *  This code and its internal interfaces are subject to change or
61230557Sjimharris *  deletion without notice.</b>
62230557Sjimharris */
63230557Sjimharrispublic class Lower extends TreeTranslator {
64230557Sjimharris    protected static final Context.Key<Lower> lowerKey = new Context.Key<>();
65230557Sjimharris
66230557Sjimharris    public static Lower instance(Context context) {
67230557Sjimharris        Lower instance = context.get(lowerKey);
68230557Sjimharris        if (instance == null)
69230557Sjimharris            instance = new Lower(context);
70230557Sjimharris        return instance;
71230557Sjimharris    }
72230557Sjimharris
73230557Sjimharris    private final Names names;
74230557Sjimharris    private final Log log;
75230557Sjimharris    private final Symtab syms;
76230557Sjimharris    private final Resolve rs;
77230557Sjimharris    private final Operators operators;
78230557Sjimharris    private final Check chk;
79230557Sjimharris    private final Attr attr;
80230557Sjimharris    private TreeMaker make;
81230557Sjimharris    private DiagnosticPosition make_pos;
82230557Sjimharris    private final ClassWriter writer;
83230557Sjimharris    private final ConstFold cfolder;
84230557Sjimharris    private final Target target;
85230557Sjimharris    private final Source source;
86230557Sjimharris    private final TypeEnvs typeEnvs;
87230557Sjimharris    private final Name dollarAssertionsDisabled;
88230557Sjimharris    private final Name classDollar;
89230557Sjimharris    private final Types types;
90230557Sjimharris    private final boolean debugLower;
91230557Sjimharris    private final PkgInfo pkginfoOpt;
92230557Sjimharris
93230557Sjimharris    protected Lower(Context context) {
94230557Sjimharris        context.put(lowerKey, this);
95230557Sjimharris        names = Names.instance(context);
96230557Sjimharris        log = Log.instance(context);
97230557Sjimharris        syms = Symtab.instance(context);
98230557Sjimharris        rs = Resolve.instance(context);
99230557Sjimharris        operators = Operators.instance(context);
100230557Sjimharris        chk = Check.instance(context);
101230557Sjimharris        attr = Attr.instance(context);
102230557Sjimharris        make = TreeMaker.instance(context);
103230557Sjimharris        writer = ClassWriter.instance(context);
104230557Sjimharris        cfolder = ConstFold.instance(context);
105230557Sjimharris        target = Target.instance(context);
106230557Sjimharris        source = Source.instance(context);
107230557Sjimharris        typeEnvs = TypeEnvs.instance(context);
108230557Sjimharris        dollarAssertionsDisabled = names.
109230557Sjimharris            fromString(target.syntheticNameChar() + "assertionsDisabled");
110230557Sjimharris        classDollar = names.
111230557Sjimharris            fromString("class" + target.syntheticNameChar());
112230557Sjimharris
113230557Sjimharris        types = Types.instance(context);
114230557Sjimharris        Options options = Options.instance(context);
115230557Sjimharris        debugLower = options.isSet("debuglower");
116230557Sjimharris        pkginfoOpt = PkgInfo.get(options);
117230557Sjimharris    }
118230557Sjimharris
119230557Sjimharris    /** The currently enclosing class.
120230557Sjimharris     */
121230557Sjimharris    ClassSymbol currentClass;
122230557Sjimharris
123230557Sjimharris    /** A queue of all translated classes.
124230557Sjimharris     */
125230557Sjimharris    ListBuffer<JCTree> translated;
126230557Sjimharris
127230557Sjimharris    /** Environment for symbol lookup, set by translateTopLevelClass.
128230557Sjimharris     */
129230557Sjimharris    Env<AttrContext> attrEnv;
130230557Sjimharris
131230557Sjimharris    /** A hash table mapping syntax trees to their ending source positions.
132230557Sjimharris     */
133230557Sjimharris    EndPosTable endPosTable;
134230557Sjimharris
135230557Sjimharris/**************************************************************************
136230557Sjimharris * Global mappings
137230557Sjimharris *************************************************************************/
138
139    /** A hash table mapping local classes to their definitions.
140     */
141    Map<ClassSymbol, JCClassDecl> classdefs;
142
143    /** A hash table mapping local classes to a list of pruned trees.
144     */
145    public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<>();
146
147    /** A hash table mapping virtual accessed symbols in outer subclasses
148     *  to the actually referred symbol in superclasses.
149     */
150    Map<Symbol,Symbol> actualSymbols;
151
152    /** The current method definition.
153     */
154    JCMethodDecl currentMethodDef;
155
156    /** The current method symbol.
157     */
158    MethodSymbol currentMethodSym;
159
160    /** The currently enclosing outermost class definition.
161     */
162    JCClassDecl outermostClassDef;
163
164    /** The currently enclosing outermost member definition.
165     */
166    JCTree outermostMemberDef;
167
168    /** A map from local variable symbols to their translation (as per LambdaToMethod).
169     * This is required when a capturing local class is created from a lambda (in which
170     * case the captured symbols should be replaced with the translated lambda symbols).
171     */
172    Map<Symbol, Symbol> lambdaTranslationMap = null;
173
174    /** A navigator class for assembling a mapping from local class symbols
175     *  to class definition trees.
176     *  There is only one case; all other cases simply traverse down the tree.
177     */
178    class ClassMap extends TreeScanner {
179
180        /** All encountered class defs are entered into classdefs table.
181         */
182        public void visitClassDef(JCClassDecl tree) {
183            classdefs.put(tree.sym, tree);
184            super.visitClassDef(tree);
185        }
186    }
187    ClassMap classMap = new ClassMap();
188
189    /** Map a class symbol to its definition.
190     *  @param c    The class symbol of which we want to determine the definition.
191     */
192    JCClassDecl classDef(ClassSymbol c) {
193        // First lookup the class in the classdefs table.
194        JCClassDecl def = classdefs.get(c);
195        if (def == null && outermostMemberDef != null) {
196            // If this fails, traverse outermost member definition, entering all
197            // local classes into classdefs, and try again.
198            classMap.scan(outermostMemberDef);
199            def = classdefs.get(c);
200        }
201        if (def == null) {
202            // If this fails, traverse outermost class definition, entering all
203            // local classes into classdefs, and try again.
204            classMap.scan(outermostClassDef);
205            def = classdefs.get(c);
206        }
207        return def;
208    }
209
210    /** A hash table mapping class symbols to lists of free variables.
211     *  accessed by them. Only free variables of the method immediately containing
212     *  a class are associated with that class.
213     */
214    Map<ClassSymbol,List<VarSymbol>> freevarCache;
215
216    /** A navigator class for collecting the free variables accessed
217     *  from a local class. There is only one case; all other cases simply
218     *  traverse down the tree. This class doesn't deal with the specific
219     *  of Lower - it's an abstract visitor that is meant to be reused in
220     *  order to share the local variable capture logic.
221     */
222    abstract class BasicFreeVarCollector extends TreeScanner {
223
224        /** Add all free variables of class c to fvs list
225         *  unless they are already there.
226         */
227        abstract void addFreeVars(ClassSymbol c);
228
229        /** If tree refers to a variable in owner of local class, add it to
230         *  free variables list.
231         */
232        public void visitIdent(JCIdent tree) {
233            visitSymbol(tree.sym);
234        }
235        // where
236        abstract void visitSymbol(Symbol _sym);
237
238        /** If tree refers to a class instance creation expression
239         *  add all free variables of the freshly created class.
240         */
241        public void visitNewClass(JCNewClass tree) {
242            ClassSymbol c = (ClassSymbol)tree.constructor.owner;
243            addFreeVars(c);
244            super.visitNewClass(tree);
245        }
246
247        /** If tree refers to a superclass constructor call,
248         *  add all free variables of the superclass.
249         */
250        public void visitApply(JCMethodInvocation tree) {
251            if (TreeInfo.name(tree.meth) == names._super) {
252                addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
253            }
254            super.visitApply(tree);
255        }
256    }
257
258    /**
259     * Lower-specific subclass of {@code BasicFreeVarCollector}.
260     */
261    class FreeVarCollector extends BasicFreeVarCollector {
262
263        /** The owner of the local class.
264         */
265        Symbol owner;
266
267        /** The local class.
268         */
269        ClassSymbol clazz;
270
271        /** The list of owner's variables accessed from within the local class,
272         *  without any duplicates.
273         */
274        List<VarSymbol> fvs;
275
276        FreeVarCollector(ClassSymbol clazz) {
277            this.clazz = clazz;
278            this.owner = clazz.owner;
279            this.fvs = List.nil();
280        }
281
282        /** Add free variable to fvs list unless it is already there.
283         */
284        private void addFreeVar(VarSymbol v) {
285            for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
286                if (l.head == v) return;
287            fvs = fvs.prepend(v);
288        }
289
290        @Override
291        void addFreeVars(ClassSymbol c) {
292            List<VarSymbol> fvs = freevarCache.get(c);
293            if (fvs != null) {
294                for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
295                    addFreeVar(l.head);
296                }
297            }
298        }
299
300        @Override
301        void visitSymbol(Symbol _sym) {
302            Symbol sym = _sym;
303            if (sym.kind == VAR || sym.kind == MTH) {
304                while (sym != null && sym.owner != owner)
305                    sym = proxies.findFirst(proxyName(sym.name));
306                if (sym != null && sym.owner == owner) {
307                    VarSymbol v = (VarSymbol)sym;
308                    if (v.getConstValue() == null) {
309                        addFreeVar(v);
310                    }
311                } else {
312                    if (outerThisStack.head != null &&
313                        outerThisStack.head != _sym)
314                        visitSymbol(outerThisStack.head);
315                }
316            }
317        }
318
319        /** If tree refers to a class instance creation expression
320         *  add all free variables of the freshly created class.
321         */
322        public void visitNewClass(JCNewClass tree) {
323            ClassSymbol c = (ClassSymbol)tree.constructor.owner;
324            if (tree.encl == null &&
325                c.hasOuterInstance() &&
326                outerThisStack.head != null)
327                visitSymbol(outerThisStack.head);
328            super.visitNewClass(tree);
329        }
330
331        /** If tree refers to a qualified this or super expression
332         *  for anything but the current class, add the outer this
333         *  stack as a free variable.
334         */
335        public void visitSelect(JCFieldAccess tree) {
336            if ((tree.name == names._this || tree.name == names._super) &&
337                tree.selected.type.tsym != clazz &&
338                outerThisStack.head != null)
339                visitSymbol(outerThisStack.head);
340            super.visitSelect(tree);
341        }
342
343        /** If tree refers to a superclass constructor call,
344         *  add all free variables of the superclass.
345         */
346        public void visitApply(JCMethodInvocation tree) {
347            if (TreeInfo.name(tree.meth) == names._super) {
348                Symbol constructor = TreeInfo.symbol(tree.meth);
349                ClassSymbol c = (ClassSymbol)constructor.owner;
350                if (c.hasOuterInstance() &&
351                    !tree.meth.hasTag(SELECT) &&
352                    outerThisStack.head != null)
353                    visitSymbol(outerThisStack.head);
354            }
355            super.visitApply(tree);
356        }
357    }
358
359    ClassSymbol ownerToCopyFreeVarsFrom(ClassSymbol c) {
360        if (!c.isLocal()) {
361            return null;
362        }
363        Symbol currentOwner = c.owner;
364        while (currentOwner.owner.kind.matches(KindSelector.TYP) && currentOwner.isLocal()) {
365            currentOwner = currentOwner.owner;
366        }
367        if (currentOwner.owner.kind.matches(KindSelector.VAL_MTH) && c.isSubClass(currentOwner, types)) {
368            return (ClassSymbol)currentOwner;
369        }
370        return null;
371    }
372
373    /** Return the variables accessed from within a local class, which
374     *  are declared in the local class' owner.
375     *  (in reverse order of first access).
376     */
377    List<VarSymbol> freevars(ClassSymbol c)  {
378        List<VarSymbol> fvs = freevarCache.get(c);
379        if (fvs != null) {
380            return fvs;
381        }
382        if (c.owner.kind.matches(KindSelector.VAL_MTH)) {
383            FreeVarCollector collector = new FreeVarCollector(c);
384            collector.scan(classDef(c));
385            fvs = collector.fvs;
386            freevarCache.put(c, fvs);
387            return fvs;
388        } else {
389            ClassSymbol owner = ownerToCopyFreeVarsFrom(c);
390            if (owner != null) {
391                fvs = freevarCache.get(owner);
392                freevarCache.put(c, fvs);
393                return fvs;
394            } else {
395                return List.nil();
396            }
397        }
398    }
399
400    Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<>();
401
402    EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
403        EnumMapping map = enumSwitchMap.get(enumClass);
404        if (map == null)
405            enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
406        return map;
407    }
408
409    /** This map gives a translation table to be used for enum
410     *  switches.
411     *
412     *  <p>For each enum that appears as the type of a switch
413     *  expression, we maintain an EnumMapping to assist in the
414     *  translation, as exemplified by the following example:
415     *
416     *  <p>we translate
417     *  <pre>
418     *          switch(colorExpression) {
419     *          case red: stmt1;
420     *          case green: stmt2;
421     *          }
422     *  </pre>
423     *  into
424     *  <pre>
425     *          switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
426     *          case 1: stmt1;
427     *          case 2: stmt2
428     *          }
429     *  </pre>
430     *  with the auxiliary table initialized as follows:
431     *  <pre>
432     *          class Outer$0 {
433     *              synthetic final int[] $EnumMap$Color = new int[Color.values().length];
434     *              static {
435     *                  try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
436     *                  try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
437     *              }
438     *          }
439     *  </pre>
440     *  class EnumMapping provides mapping data and support methods for this translation.
441     */
442    class EnumMapping {
443        EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
444            this.forEnum = forEnum;
445            this.values = new LinkedHashMap<>();
446            this.pos = pos;
447            Name varName = names
448                .fromString(target.syntheticNameChar() +
449                            "SwitchMap" +
450                            target.syntheticNameChar() +
451                            writer.xClassName(forEnum.type).toString()
452                            .replace('/', '.')
453                            .replace('.', target.syntheticNameChar()));
454            ClassSymbol outerCacheClass = outerCacheClass();
455            this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
456                                        varName,
457                                        new ArrayType(syms.intType, syms.arrayClass),
458                                        outerCacheClass);
459            enterSynthetic(pos, mapVar, outerCacheClass.members());
460        }
461
462        DiagnosticPosition pos = null;
463
464        // the next value to use
465        int next = 1; // 0 (unused map elements) go to the default label
466
467        // the enum for which this is a map
468        final TypeSymbol forEnum;
469
470        // the field containing the map
471        final VarSymbol mapVar;
472
473        // the mapped values
474        final Map<VarSymbol,Integer> values;
475
476        JCLiteral forConstant(VarSymbol v) {
477            Integer result = values.get(v);
478            if (result == null)
479                values.put(v, result = next++);
480            return make.Literal(result);
481        }
482
483        // generate the field initializer for the map
484        void translate() {
485            make.at(pos.getStartPosition());
486            JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
487
488            // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
489            MethodSymbol valuesMethod = lookupMethod(pos,
490                                                     names.values,
491                                                     forEnum.type,
492                                                     List.<Type>nil());
493            JCExpression size = make // Color.values().length
494                .Select(make.App(make.QualIdent(valuesMethod)),
495                        syms.lengthVar);
496            JCExpression mapVarInit = make
497                .NewArray(make.Type(syms.intType), List.of(size), null)
498                .setType(new ArrayType(syms.intType, syms.arrayClass));
499
500            // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
501            ListBuffer<JCStatement> stmts = new ListBuffer<>();
502            Symbol ordinalMethod = lookupMethod(pos,
503                                                names.ordinal,
504                                                forEnum.type,
505                                                List.<Type>nil());
506            List<JCCatch> catcher = List.<JCCatch>nil()
507                .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
508                                                              syms.noSuchFieldErrorType,
509                                                              syms.noSymbol),
510                                                null),
511                                    make.Block(0, List.<JCStatement>nil())));
512            for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
513                VarSymbol enumerator = e.getKey();
514                Integer mappedValue = e.getValue();
515                JCExpression assign = make
516                    .Assign(make.Indexed(mapVar,
517                                         make.App(make.Select(make.QualIdent(enumerator),
518                                                              ordinalMethod))),
519                            make.Literal(mappedValue))
520                    .setType(syms.intType);
521                JCStatement exec = make.Exec(assign);
522                JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
523                stmts.append(_try);
524            }
525
526            owner.defs = owner.defs
527                .prepend(make.Block(STATIC, stmts.toList()))
528                .prepend(make.VarDef(mapVar, mapVarInit));
529        }
530    }
531
532
533/**************************************************************************
534 * Tree building blocks
535 *************************************************************************/
536
537    /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
538     *  pos as make_pos, for use in diagnostics.
539     **/
540    TreeMaker make_at(DiagnosticPosition pos) {
541        make_pos = pos;
542        return make.at(pos);
543    }
544
545    /** Make an attributed tree representing a literal. This will be an
546     *  Ident node in the case of boolean literals, a Literal node in all
547     *  other cases.
548     *  @param type       The literal's type.
549     *  @param value      The literal's value.
550     */
551    JCExpression makeLit(Type type, Object value) {
552        return make.Literal(type.getTag(), value).setType(type.constType(value));
553    }
554
555    /** Make an attributed tree representing null.
556     */
557    JCExpression makeNull() {
558        return makeLit(syms.botType, null);
559    }
560
561    /** Make an attributed class instance creation expression.
562     *  @param ctype    The class type.
563     *  @param args     The constructor arguments.
564     */
565    JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
566        JCNewClass tree = make.NewClass(null,
567            null, make.QualIdent(ctype.tsym), args, null);
568        tree.constructor = rs.resolveConstructor(
569            make_pos, attrEnv, ctype, TreeInfo.types(args), List.<Type>nil());
570        tree.type = ctype;
571        return tree;
572    }
573
574    /** Make an attributed unary expression.
575     *  @param optag    The operators tree tag.
576     *  @param arg      The operator's argument.
577     */
578    JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) {
579        JCUnary tree = make.Unary(optag, arg);
580        tree.operator = operators.resolveUnary(tree, optag, arg.type);
581        tree.type = tree.operator.type.getReturnType();
582        return tree;
583    }
584
585    /** Make an attributed binary expression.
586     *  @param optag    The operators tree tag.
587     *  @param lhs      The operator's left argument.
588     *  @param rhs      The operator's right argument.
589     */
590    JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
591        JCBinary tree = make.Binary(optag, lhs, rhs);
592        tree.operator = operators.resolveBinary(tree, optag, lhs.type, rhs.type);
593        tree.type = tree.operator.type.getReturnType();
594        return tree;
595    }
596
597    /** Make an attributed assignop expression.
598     *  @param optag    The operators tree tag.
599     *  @param lhs      The operator's left argument.
600     *  @param rhs      The operator's right argument.
601     */
602    JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) {
603        JCAssignOp tree = make.Assignop(optag, lhs, rhs);
604        tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), lhs.type, rhs.type);
605        tree.type = lhs.type;
606        return tree;
607    }
608
609    /** Convert tree into string object, unless it has already a
610     *  reference type..
611     */
612    JCExpression makeString(JCExpression tree) {
613        if (!tree.type.isPrimitiveOrVoid()) {
614            return tree;
615        } else {
616            Symbol valueOfSym = lookupMethod(tree.pos(),
617                                             names.valueOf,
618                                             syms.stringType,
619                                             List.of(tree.type));
620            return make.App(make.QualIdent(valueOfSym), List.of(tree));
621        }
622    }
623
624    /** Create an empty anonymous class definition and enter and complete
625     *  its symbol. Return the class definition's symbol.
626     *  and create
627     *  @param flags    The class symbol's flags
628     *  @param owner    The class symbol's owner
629     */
630    JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
631        return makeEmptyClass(flags, owner, null, true);
632    }
633
634    JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
635            boolean addToDefs) {
636        // Create class symbol.
637        ClassSymbol c = syms.defineClass(names.empty, owner);
638        if (flatname != null) {
639            c.flatname = flatname;
640        } else {
641            c.flatname = chk.localClassName(c);
642        }
643        c.sourcefile = owner.sourcefile;
644        c.completer = Completer.NULL_COMPLETER;
645        c.members_field = WriteableScope.create(c);
646        c.flags_field = flags;
647        ClassType ctype = (ClassType) c.type;
648        ctype.supertype_field = syms.objectType;
649        ctype.interfaces_field = List.nil();
650
651        JCClassDecl odef = classDef(owner);
652
653        // Enter class symbol in owner scope and compiled table.
654        enterSynthetic(odef.pos(), c, owner.members());
655        chk.putCompiled(c);
656
657        // Create class definition tree.
658        JCClassDecl cdef = make.ClassDef(
659            make.Modifiers(flags), names.empty,
660            List.<JCTypeParameter>nil(),
661            null, List.<JCExpression>nil(), List.<JCTree>nil());
662        cdef.sym = c;
663        cdef.type = c.type;
664
665        // Append class definition tree to owner's definitions.
666        if (addToDefs) odef.defs = odef.defs.prepend(cdef);
667        return cdef;
668    }
669
670/**************************************************************************
671 * Symbol manipulation utilities
672 *************************************************************************/
673
674    /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
675     *  @param pos           Position for error reporting.
676     *  @param sym           The symbol.
677     *  @param s             The scope.
678     */
679    private void enterSynthetic(DiagnosticPosition pos, Symbol sym, WriteableScope s) {
680        s.enter(sym);
681    }
682
683    /** Create a fresh synthetic name within a given scope - the unique name is
684     *  obtained by appending '$' chars at the end of the name until no match
685     *  is found.
686     *
687     * @param name base name
688     * @param s scope in which the name has to be unique
689     * @return fresh synthetic name
690     */
691    private Name makeSyntheticName(Name name, Scope s) {
692        do {
693            name = name.append(
694                    target.syntheticNameChar(),
695                    names.empty);
696        } while (lookupSynthetic(name, s) != null);
697        return name;
698    }
699
700    /** Check whether synthetic symbols generated during lowering conflict
701     *  with user-defined symbols.
702     *
703     *  @param translatedTrees lowered class trees
704     */
705    void checkConflicts(List<JCTree> translatedTrees) {
706        for (JCTree t : translatedTrees) {
707            t.accept(conflictsChecker);
708        }
709    }
710
711    JCTree.Visitor conflictsChecker = new TreeScanner() {
712
713        TypeSymbol currentClass;
714
715        @Override
716        public void visitMethodDef(JCMethodDecl that) {
717            chk.checkConflicts(that.pos(), that.sym, currentClass);
718            super.visitMethodDef(that);
719        }
720
721        @Override
722        public void visitVarDef(JCVariableDecl that) {
723            if (that.sym.owner.kind == TYP) {
724                chk.checkConflicts(that.pos(), that.sym, currentClass);
725            }
726            super.visitVarDef(that);
727        }
728
729        @Override
730        public void visitClassDef(JCClassDecl that) {
731            TypeSymbol prevCurrentClass = currentClass;
732            currentClass = that.sym;
733            try {
734                super.visitClassDef(that);
735            }
736            finally {
737                currentClass = prevCurrentClass;
738            }
739        }
740    };
741
742    /** Look up a synthetic name in a given scope.
743     *  @param s            The scope.
744     *  @param name         The name.
745     */
746    private Symbol lookupSynthetic(Name name, Scope s) {
747        Symbol sym = s.findFirst(name);
748        return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
749    }
750
751    /** Look up a method in a given scope.
752     */
753    private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
754        return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.<Type>nil());
755    }
756
757    /** Look up a constructor.
758     */
759    private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
760        return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
761    }
762
763    /** Look up a field.
764     */
765    private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
766        return rs.resolveInternalField(pos, attrEnv, qual, name);
767    }
768
769    /** Anon inner classes are used as access constructor tags.
770     * accessConstructorTag will use an existing anon class if one is available,
771     * and synthethise a class (with makeEmptyClass) if one is not available.
772     * However, there is a small possibility that an existing class will not
773     * be generated as expected if it is inside a conditional with a constant
774     * expression. If that is found to be the case, create an empty class tree here.
775     */
776    private void checkAccessConstructorTags() {
777        for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
778            ClassSymbol c = l.head;
779            if (isTranslatedClassAvailable(c))
780                continue;
781            // Create class definition tree.
782            JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC,
783                    c.outermostClass(), c.flatname, false);
784            swapAccessConstructorTag(c, cdec.sym);
785            translated.append(cdec);
786        }
787    }
788    // where
789    private boolean isTranslatedClassAvailable(ClassSymbol c) {
790        for (JCTree tree: translated) {
791            if (tree.hasTag(CLASSDEF)
792                    && ((JCClassDecl) tree).sym == c) {
793                return true;
794            }
795        }
796        return false;
797    }
798
799    void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
800        for (MethodSymbol methodSymbol : accessConstrs.values()) {
801            Assert.check(methodSymbol.type.hasTag(METHOD));
802            MethodType oldMethodType =
803                    (MethodType)methodSymbol.type;
804            if (oldMethodType.argtypes.head.tsym == oldCTag)
805                methodSymbol.type =
806                    types.createMethodTypeWithParameters(oldMethodType,
807                        oldMethodType.getParameterTypes().tail
808                            .prepend(newCTag.erasure(types)));
809        }
810    }
811
812/**************************************************************************
813 * Access methods
814 *************************************************************************/
815
816    /** Access codes for dereferencing, assignment,
817     *  and pre/post increment/decrement.
818     *  Access codes for assignment operations are determined by method accessCode
819     *  below.
820     *
821     *  All access codes for accesses to the current class are even.
822     *  If a member of the superclass should be accessed instead (because
823     *  access was via a qualified super), add one to the corresponding code
824     *  for the current class, making the number odd.
825     *  This numbering scheme is used by the backend to decide whether
826     *  to issue an invokevirtual or invokespecial call.
827     *
828     *  @see Gen#visitSelect(JCFieldAccess tree)
829     */
830    private static final int
831        DEREFcode = 0,
832        ASSIGNcode = 2,
833        PREINCcode = 4,
834        PREDECcode = 6,
835        POSTINCcode = 8,
836        POSTDECcode = 10,
837        FIRSTASGOPcode = 12;
838
839    /** Number of access codes
840     */
841    private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
842
843    /** A mapping from symbols to their access numbers.
844     */
845    private Map<Symbol,Integer> accessNums;
846
847    /** A mapping from symbols to an array of access symbols, indexed by
848     *  access code.
849     */
850    private Map<Symbol,MethodSymbol[]> accessSyms;
851
852    /** A mapping from (constructor) symbols to access constructor symbols.
853     */
854    private Map<Symbol,MethodSymbol> accessConstrs;
855
856    /** A list of all class symbols used for access constructor tags.
857     */
858    private List<ClassSymbol> accessConstrTags;
859
860    /** A queue for all accessed symbols.
861     */
862    private ListBuffer<Symbol> accessed;
863
864    /** Map bytecode of binary operation to access code of corresponding
865     *  assignment operation. This is always an even number.
866     */
867    private static int accessCode(int bytecode) {
868        if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
869            return (bytecode - iadd) * 2 + FIRSTASGOPcode;
870        else if (bytecode == ByteCodes.string_add)
871            return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
872        else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
873            return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
874        else
875            return -1;
876    }
877
878    /** return access code for identifier,
879     *  @param tree     The tree representing the identifier use.
880     *  @param enclOp   The closest enclosing operation node of tree,
881     *                  null if tree is not a subtree of an operation.
882     */
883    private static int accessCode(JCTree tree, JCTree enclOp) {
884        if (enclOp == null)
885            return DEREFcode;
886        else if (enclOp.hasTag(ASSIGN) &&
887                 tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
888            return ASSIGNcode;
889        else if (enclOp.getTag().isIncOrDecUnaryOp() &&
890                 tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
891            return mapTagToUnaryOpCode(enclOp.getTag());
892        else if (enclOp.getTag().isAssignop() &&
893                 tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
894            return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
895        else
896            return DEREFcode;
897    }
898
899    /** Return binary operator that corresponds to given access code.
900     */
901    private OperatorSymbol binaryAccessOperator(int acode) {
902        for (Symbol sym : syms.predefClass.members().getSymbols(NON_RECURSIVE)) {
903            if (sym instanceof OperatorSymbol) {
904                OperatorSymbol op = (OperatorSymbol)sym;
905                if (accessCode(op.opcode) == acode) return op;
906            }
907        }
908        return null;
909    }
910
911    /** Return tree tag for assignment operation corresponding
912     *  to given binary operator.
913     */
914    private static JCTree.Tag treeTag(OperatorSymbol operator) {
915        switch (operator.opcode) {
916        case ByteCodes.ior: case ByteCodes.lor:
917            return BITOR_ASG;
918        case ByteCodes.ixor: case ByteCodes.lxor:
919            return BITXOR_ASG;
920        case ByteCodes.iand: case ByteCodes.land:
921            return BITAND_ASG;
922        case ByteCodes.ishl: case ByteCodes.lshl:
923        case ByteCodes.ishll: case ByteCodes.lshll:
924            return SL_ASG;
925        case ByteCodes.ishr: case ByteCodes.lshr:
926        case ByteCodes.ishrl: case ByteCodes.lshrl:
927            return SR_ASG;
928        case ByteCodes.iushr: case ByteCodes.lushr:
929        case ByteCodes.iushrl: case ByteCodes.lushrl:
930            return USR_ASG;
931        case ByteCodes.iadd: case ByteCodes.ladd:
932        case ByteCodes.fadd: case ByteCodes.dadd:
933        case ByteCodes.string_add:
934            return PLUS_ASG;
935        case ByteCodes.isub: case ByteCodes.lsub:
936        case ByteCodes.fsub: case ByteCodes.dsub:
937            return MINUS_ASG;
938        case ByteCodes.imul: case ByteCodes.lmul:
939        case ByteCodes.fmul: case ByteCodes.dmul:
940            return MUL_ASG;
941        case ByteCodes.idiv: case ByteCodes.ldiv:
942        case ByteCodes.fdiv: case ByteCodes.ddiv:
943            return DIV_ASG;
944        case ByteCodes.imod: case ByteCodes.lmod:
945        case ByteCodes.fmod: case ByteCodes.dmod:
946            return MOD_ASG;
947        default:
948            throw new AssertionError();
949        }
950    }
951
952    /** The name of the access method with number `anum' and access code `acode'.
953     */
954    Name accessName(int anum, int acode) {
955        return names.fromString(
956            "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
957    }
958
959    /** Return access symbol for a private or protected symbol from an inner class.
960     *  @param sym        The accessed private symbol.
961     *  @param tree       The accessing tree.
962     *  @param enclOp     The closest enclosing operation node of tree,
963     *                    null if tree is not a subtree of an operation.
964     *  @param protAccess Is access to a protected symbol in another
965     *                    package?
966     *  @param refSuper   Is access via a (qualified) C.super?
967     */
968    MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
969                              boolean protAccess, boolean refSuper) {
970        ClassSymbol accOwner = refSuper && protAccess
971            // For access via qualified super (T.super.x), place the
972            // access symbol on T.
973            ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
974            // Otherwise pretend that the owner of an accessed
975            // protected symbol is the enclosing class of the current
976            // class which is a subclass of the symbol's owner.
977            : accessClass(sym, protAccess, tree);
978
979        Symbol vsym = sym;
980        if (sym.owner != accOwner) {
981            vsym = sym.clone(accOwner);
982            actualSymbols.put(vsym, sym);
983        }
984
985        Integer anum              // The access number of the access method.
986            = accessNums.get(vsym);
987        if (anum == null) {
988            anum = accessed.length();
989            accessNums.put(vsym, anum);
990            accessSyms.put(vsym, new MethodSymbol[NCODES]);
991            accessed.append(vsym);
992            // System.out.println("accessing " + vsym + " in " + vsym.location());
993        }
994
995        int acode;                // The access code of the access method.
996        List<Type> argtypes;      // The argument types of the access method.
997        Type restype;             // The result type of the access method.
998        List<Type> thrown;        // The thrown exceptions of the access method.
999        switch (vsym.kind) {
1000        case VAR:
1001            acode = accessCode(tree, enclOp);
1002            if (acode >= FIRSTASGOPcode) {
1003                OperatorSymbol operator = binaryAccessOperator(acode);
1004                if (operator.opcode == string_add)
1005                    argtypes = List.of(syms.objectType);
1006                else
1007                    argtypes = operator.type.getParameterTypes().tail;
1008            } else if (acode == ASSIGNcode)
1009                argtypes = List.of(vsym.erasure(types));
1010            else
1011                argtypes = List.nil();
1012            restype = vsym.erasure(types);
1013            thrown = List.nil();
1014            break;
1015        case MTH:
1016            acode = DEREFcode;
1017            argtypes = vsym.erasure(types).getParameterTypes();
1018            restype = vsym.erasure(types).getReturnType();
1019            thrown = vsym.type.getThrownTypes();
1020            break;
1021        default:
1022            throw new AssertionError();
1023        }
1024
1025        // For references via qualified super, increment acode by one,
1026        // making it odd.
1027        if (protAccess && refSuper) acode++;
1028
1029        // Instance access methods get instance as first parameter.
1030        // For protected symbols this needs to be the instance as a member
1031        // of the type containing the accessed symbol, not the class
1032        // containing the access method.
1033        if ((vsym.flags() & STATIC) == 0) {
1034            argtypes = argtypes.prepend(vsym.owner.erasure(types));
1035        }
1036        MethodSymbol[] accessors = accessSyms.get(vsym);
1037        MethodSymbol accessor = accessors[acode];
1038        if (accessor == null) {
1039            accessor = new MethodSymbol(
1040                STATIC | SYNTHETIC | (accOwner.isInterface() ? PUBLIC : 0),
1041                accessName(anum.intValue(), acode),
1042                new MethodType(argtypes, restype, thrown, syms.methodClass),
1043                accOwner);
1044            enterSynthetic(tree.pos(), accessor, accOwner.members());
1045            accessors[acode] = accessor;
1046        }
1047        return accessor;
1048    }
1049
1050    /** The qualifier to be used for accessing a symbol in an outer class.
1051     *  This is either C.sym or C.this.sym, depending on whether or not
1052     *  sym is static.
1053     *  @param sym   The accessed symbol.
1054     */
1055    JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
1056        return (sym.flags() & STATIC) != 0
1057            ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
1058            : makeOwnerThis(pos, sym, true);
1059    }
1060
1061    /** Do we need an access method to reference private symbol?
1062     */
1063    boolean needsPrivateAccess(Symbol sym) {
1064        if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
1065            return false;
1066        } else if (sym.name == names.init && sym.owner.isLocal()) {
1067            // private constructor in local class: relax protection
1068            sym.flags_field &= ~PRIVATE;
1069            return false;
1070        } else {
1071            return true;
1072        }
1073    }
1074
1075    /** Do we need an access method to reference symbol in other package?
1076     */
1077    boolean needsProtectedAccess(Symbol sym, JCTree tree) {
1078        if ((sym.flags() & PROTECTED) == 0 ||
1079            sym.owner.owner == currentClass.owner || // fast special case
1080            sym.packge() == currentClass.packge())
1081            return false;
1082        if (!currentClass.isSubClass(sym.owner, types))
1083            return true;
1084        if ((sym.flags() & STATIC) != 0 ||
1085            !tree.hasTag(SELECT) ||
1086            TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
1087            return false;
1088        return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
1089    }
1090
1091    /** The class in which an access method for given symbol goes.
1092     *  @param sym        The access symbol
1093     *  @param protAccess Is access to a protected symbol in another
1094     *                    package?
1095     */
1096    ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
1097        if (protAccess) {
1098            Symbol qualifier = null;
1099            ClassSymbol c = currentClass;
1100            if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
1101                qualifier = ((JCFieldAccess) tree).selected.type.tsym;
1102                while (!qualifier.isSubClass(c, types)) {
1103                    c = c.owner.enclClass();
1104                }
1105                return c;
1106            } else {
1107                while (!c.isSubClass(sym.owner, types)) {
1108                    c = c.owner.enclClass();
1109                }
1110            }
1111            return c;
1112        } else {
1113            // the symbol is private
1114            return sym.owner.enclClass();
1115        }
1116    }
1117
1118    private void addPrunedInfo(JCTree tree) {
1119        List<JCTree> infoList = prunedTree.get(currentClass);
1120        infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
1121        prunedTree.put(currentClass, infoList);
1122    }
1123
1124    /** Ensure that identifier is accessible, return tree accessing the identifier.
1125     *  @param sym      The accessed symbol.
1126     *  @param tree     The tree referring to the symbol.
1127     *  @param enclOp   The closest enclosing operation node of tree,
1128     *                  null if tree is not a subtree of an operation.
1129     *  @param refSuper Is access via a (qualified) C.super?
1130     */
1131    JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
1132        // Access a free variable via its proxy, or its proxy's proxy
1133        while (sym.kind == VAR && sym.owner.kind == MTH &&
1134            sym.owner.enclClass() != currentClass) {
1135            // A constant is replaced by its constant value.
1136            Object cv = ((VarSymbol)sym).getConstValue();
1137            if (cv != null) {
1138                make.at(tree.pos);
1139                return makeLit(sym.type, cv);
1140            }
1141            // Otherwise replace the variable by its proxy.
1142            sym = proxies.findFirst(proxyName(sym.name));
1143            Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
1144            tree = make.at(tree.pos).Ident(sym);
1145        }
1146        JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
1147        switch (sym.kind) {
1148        case TYP:
1149            if (sym.owner.kind != PCK) {
1150                // Convert type idents to
1151                // <flat name> or <package name> . <flat name>
1152                Name flatname = Convert.shortName(sym.flatName());
1153                while (base != null &&
1154                       TreeInfo.symbol(base) != null &&
1155                       TreeInfo.symbol(base).kind != PCK) {
1156                    base = (base.hasTag(SELECT))
1157                        ? ((JCFieldAccess) base).selected
1158                        : null;
1159                }
1160                if (tree.hasTag(IDENT)) {
1161                    ((JCIdent) tree).name = flatname;
1162                } else if (base == null) {
1163                    tree = make.at(tree.pos).Ident(sym);
1164                    ((JCIdent) tree).name = flatname;
1165                } else {
1166                    ((JCFieldAccess) tree).selected = base;
1167                    ((JCFieldAccess) tree).name = flatname;
1168                }
1169            }
1170            break;
1171        case MTH: case VAR:
1172            if (sym.owner.kind == TYP) {
1173
1174                // Access methods are required for
1175                //  - private members,
1176                //  - protected members in a superclass of an
1177                //    enclosing class contained in another package.
1178                //  - all non-private members accessed via a qualified super.
1179                boolean protAccess = refSuper && !needsPrivateAccess(sym)
1180                    || needsProtectedAccess(sym, tree);
1181                boolean accReq = protAccess || needsPrivateAccess(sym);
1182
1183                // A base has to be supplied for
1184                //  - simple identifiers accessing variables in outer classes.
1185                boolean baseReq =
1186                    base == null &&
1187                    sym.owner != syms.predefClass &&
1188                    !sym.isMemberOf(currentClass, types);
1189
1190                if (accReq || baseReq) {
1191                    make.at(tree.pos);
1192
1193                    // Constants are replaced by their constant value.
1194                    if (sym.kind == VAR) {
1195                        Object cv = ((VarSymbol)sym).getConstValue();
1196                        if (cv != null) {
1197                            addPrunedInfo(tree);
1198                            return makeLit(sym.type, cv);
1199                        }
1200                    }
1201
1202                    // Private variables and methods are replaced by calls
1203                    // to their access methods.
1204                    if (accReq) {
1205                        List<JCExpression> args = List.nil();
1206                        if ((sym.flags() & STATIC) == 0) {
1207                            // Instance access methods get instance
1208                            // as first parameter.
1209                            if (base == null)
1210                                base = makeOwnerThis(tree.pos(), sym, true);
1211                            args = args.prepend(base);
1212                            base = null;   // so we don't duplicate code
1213                        }
1214                        Symbol access = accessSymbol(sym, tree,
1215                                                     enclOp, protAccess,
1216                                                     refSuper);
1217                        JCExpression receiver = make.Select(
1218                            base != null ? base : make.QualIdent(access.owner),
1219                            access);
1220                        return make.App(receiver, args);
1221
1222                    // Other accesses to members of outer classes get a
1223                    // qualifier.
1224                    } else if (baseReq) {
1225                        return make.at(tree.pos).Select(
1226                            accessBase(tree.pos(), sym), sym).setType(tree.type);
1227                    }
1228                }
1229            } else if (sym.owner.kind == MTH && lambdaTranslationMap != null) {
1230                //sym is a local variable - check the lambda translation map to
1231                //see if sym has been translated to something else in the current
1232                //scope (by LambdaToMethod)
1233                Symbol translatedSym = lambdaTranslationMap.get(sym);
1234                if (translatedSym != null) {
1235                    tree = make.at(tree.pos).Ident(translatedSym);
1236                }
1237            }
1238        }
1239        return tree;
1240    }
1241
1242    /** Ensure that identifier is accessible, return tree accessing the identifier.
1243     *  @param tree     The identifier tree.
1244     */
1245    JCExpression access(JCExpression tree) {
1246        Symbol sym = TreeInfo.symbol(tree);
1247        return sym == null ? tree : access(sym, tree, null, false);
1248    }
1249
1250    /** Return access constructor for a private constructor,
1251     *  or the constructor itself, if no access constructor is needed.
1252     *  @param pos       The position to report diagnostics, if any.
1253     *  @param constr    The private constructor.
1254     */
1255    Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1256        if (needsPrivateAccess(constr)) {
1257            ClassSymbol accOwner = constr.owner.enclClass();
1258            MethodSymbol aconstr = accessConstrs.get(constr);
1259            if (aconstr == null) {
1260                List<Type> argtypes = constr.type.getParameterTypes();
1261                if ((accOwner.flags_field & ENUM) != 0)
1262                    argtypes = argtypes
1263                        .prepend(syms.intType)
1264                        .prepend(syms.stringType);
1265                aconstr = new MethodSymbol(
1266                    SYNTHETIC,
1267                    names.init,
1268                    new MethodType(
1269                        argtypes.append(
1270                            accessConstructorTag().erasure(types)),
1271                        constr.type.getReturnType(),
1272                        constr.type.getThrownTypes(),
1273                        syms.methodClass),
1274                    accOwner);
1275                enterSynthetic(pos, aconstr, accOwner.members());
1276                accessConstrs.put(constr, aconstr);
1277                accessed.append(constr);
1278            }
1279            return aconstr;
1280        } else {
1281            return constr;
1282        }
1283    }
1284
1285    /** Return an anonymous class nested in this toplevel class.
1286     */
1287    ClassSymbol accessConstructorTag() {
1288        ClassSymbol topClass = currentClass.outermostClass();
1289        ModuleSymbol topModle = topClass.packge().modle;
1290        Name flatname = names.fromString("" + topClass.getQualifiedName() +
1291                                         target.syntheticNameChar() +
1292                                         "1");
1293        ClassSymbol ctag = chk.getCompiled(topModle, 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 = 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        JCExpression build(JCExpression 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    JCExpression abstractRval(JCExpression 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        Name name = TreeInfo.name(rval);
2212        if (name == names._super)
2213            return builder.build(rval);
2214        VarSymbol var =
2215            new VarSymbol(FINAL|SYNTHETIC,
2216                          names.fromString(
2217                                          target.syntheticNameChar()
2218                                          + "" + rval.hashCode()),
2219                                      type,
2220                                      currentMethodSym);
2221        rval = convert(rval,type);
2222        JCVariableDecl def = make.VarDef(var, rval); // XXX cast
2223        JCExpression built = builder.build(make.Ident(var));
2224        JCExpression res = make.LetExpr(def, built);
2225        res.type = built.type;
2226        return res;
2227    }
2228
2229    // same as above, with the type of the temporary variable computed
2230    JCExpression abstractRval(JCExpression rval, TreeBuilder builder) {
2231        return abstractRval(rval, rval.type, builder);
2232    }
2233
2234    // same as above, but for an expression that may be used as either
2235    // an rvalue or an lvalue.  This requires special handling for
2236    // Select expressions, where we place the left-hand-side of the
2237    // select in a temporary, and for Indexed expressions, where we
2238    // place both the indexed expression and the index value in temps.
2239    JCExpression abstractLval(JCExpression lval, final TreeBuilder builder) {
2240        lval = TreeInfo.skipParens(lval);
2241        switch (lval.getTag()) {
2242        case IDENT:
2243            return builder.build(lval);
2244        case SELECT: {
2245            final JCFieldAccess s = (JCFieldAccess)lval;
2246            Symbol lid = TreeInfo.symbol(s.selected);
2247            if (lid != null && lid.kind == TYP) return builder.build(lval);
2248            return abstractRval(s.selected, new TreeBuilder() {
2249                    public JCExpression build(final JCExpression selected) {
2250                        return builder.build(make.Select(selected, s.sym));
2251                    }
2252                });
2253        }
2254        case INDEXED: {
2255            final JCArrayAccess i = (JCArrayAccess)lval;
2256            return abstractRval(i.indexed, new TreeBuilder() {
2257                    public JCExpression build(final JCExpression indexed) {
2258                        return abstractRval(i.index, syms.intType, new TreeBuilder() {
2259                                public JCExpression build(final JCExpression index) {
2260                                    JCExpression newLval = make.Indexed(indexed, index);
2261                                    newLval.setType(i.type);
2262                                    return builder.build(newLval);
2263                                }
2264                            });
2265                    }
2266                });
2267        }
2268        case TYPECAST: {
2269            return abstractLval(((JCTypeCast)lval).expr, builder);
2270        }
2271        }
2272        throw new AssertionError(lval);
2273    }
2274
2275    // evaluate and discard the first expression, then evaluate the second.
2276    JCExpression makeComma(final JCExpression expr1, final JCExpression expr2) {
2277        return abstractRval(expr1, new TreeBuilder() {
2278                public JCExpression build(final JCExpression discarded) {
2279                    return expr2;
2280                }
2281            });
2282    }
2283
2284/**************************************************************************
2285 * Translation methods
2286 *************************************************************************/
2287
2288    /** Visitor argument: enclosing operator node.
2289     */
2290    private JCExpression enclOp;
2291
2292    /** Visitor method: Translate a single node.
2293     *  Attach the source position from the old tree to its replacement tree.
2294     */
2295    @Override
2296    public <T extends JCTree> T translate(T tree) {
2297        if (tree == null) {
2298            return null;
2299        } else {
2300            make_at(tree.pos());
2301            T result = super.translate(tree);
2302            if (endPosTable != null && result != tree) {
2303                endPosTable.replaceTree(tree, result);
2304            }
2305            return result;
2306        }
2307    }
2308
2309    /** Visitor method: Translate a single node, boxing or unboxing if needed.
2310     */
2311    public <T extends JCExpression> T translate(T tree, Type type) {
2312        return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2313    }
2314
2315    /** Visitor method: Translate tree.
2316     */
2317    public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2318        JCExpression prevEnclOp = this.enclOp;
2319        this.enclOp = enclOp;
2320        T res = translate(tree);
2321        this.enclOp = prevEnclOp;
2322        return res;
2323    }
2324
2325    /** Visitor method: Translate list of trees.
2326     */
2327    public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2328        JCExpression prevEnclOp = this.enclOp;
2329        this.enclOp = enclOp;
2330        List<T> res = translate(trees);
2331        this.enclOp = prevEnclOp;
2332        return res;
2333    }
2334
2335    /** Visitor method: Translate list of trees.
2336     */
2337    public <T extends JCExpression> List<T> translate(List<T> trees, Type type) {
2338        if (trees == null) return null;
2339        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2340            l.head = translate(l.head, type);
2341        return trees;
2342    }
2343
2344    public void visitPackageDef(JCPackageDecl tree) {
2345        if (!needPackageInfoClass(tree))
2346                        return;
2347
2348        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        ClassSymbol c = tree.packge.package_info;
2352        c.setAttributes(tree.packge);
2353        c.flags_field |= flags;
2354        ClassType ctype = (ClassType) c.type;
2355        ctype.supertype_field = syms.objectType;
2356        ctype.interfaces_field = List.nil();
2357        createInfoClass(tree.annotations, c);
2358    }
2359    // where
2360    private boolean needPackageInfoClass(JCPackageDecl pd) {
2361        switch (pkginfoOpt) {
2362            case ALWAYS:
2363                return true;
2364            case LEGACY:
2365                return pd.getAnnotations().nonEmpty();
2366            case NONEMPTY:
2367                for (Attribute.Compound a :
2368                         pd.packge.getDeclarationAttributes()) {
2369                    Attribute.RetentionPolicy p = types.getRetention(a);
2370                    if (p != Attribute.RetentionPolicy.SOURCE)
2371                        return true;
2372                }
2373                return false;
2374        }
2375        throw new AssertionError();
2376    }
2377
2378    public void visitModuleDef(JCModuleDecl tree) {
2379        ModuleSymbol msym = tree.sym;
2380        ClassSymbol c = msym.module_info;
2381        c.flags_field |= Flags.MODULE;
2382        createInfoClass(List.<JCAnnotation>nil(), tree.sym.module_info);
2383    }
2384
2385    private void createInfoClass(List<JCAnnotation> annots, ClassSymbol c) {
2386        long flags = Flags.ABSTRACT | Flags.INTERFACE;
2387        JCClassDecl infoClass =
2388                make.ClassDef(make.Modifiers(flags, annots),
2389                    c.name, List.<JCTypeParameter>nil(),
2390                    null, List.<JCExpression>nil(), List.<JCTree>nil());
2391        infoClass.sym = c;
2392        translated.append(infoClass);
2393    }
2394
2395    public void visitClassDef(JCClassDecl tree) {
2396        Env<AttrContext> prevEnv = attrEnv;
2397        ClassSymbol currentClassPrev = currentClass;
2398        MethodSymbol currentMethodSymPrev = currentMethodSym;
2399
2400        currentClass = tree.sym;
2401        currentMethodSym = null;
2402        attrEnv = typeEnvs.remove(currentClass);
2403        if (attrEnv == null)
2404            attrEnv = prevEnv;
2405
2406        classdefs.put(currentClass, tree);
2407
2408        proxies = proxies.dup(currentClass);
2409        List<VarSymbol> prevOuterThisStack = outerThisStack;
2410
2411        // If this is an enum definition
2412        if ((tree.mods.flags & ENUM) != 0 &&
2413            (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2414            visitEnumDef(tree);
2415
2416        // If this is a nested class, define a this$n field for
2417        // it and add to proxies.
2418        JCVariableDecl otdef = null;
2419        if (currentClass.hasOuterInstance())
2420            otdef = outerThisDef(tree.pos, currentClass);
2421
2422        // If this is a local class, define proxies for all its free variables.
2423        List<JCVariableDecl> fvdefs = freevarDefs(
2424            tree.pos, freevars(currentClass), currentClass);
2425
2426        // Recursively translate superclass, interfaces.
2427        tree.extending = translate(tree.extending);
2428        tree.implementing = translate(tree.implementing);
2429
2430        if (currentClass.isLocal()) {
2431            ClassSymbol encl = currentClass.owner.enclClass();
2432            if (encl.trans_local == null) {
2433                encl.trans_local = List.nil();
2434            }
2435            encl.trans_local = encl.trans_local.prepend(currentClass);
2436        }
2437
2438        // Recursively translate members, taking into account that new members
2439        // might be created during the translation and prepended to the member
2440        // list `tree.defs'.
2441        List<JCTree> seen = List.nil();
2442        while (tree.defs != seen) {
2443            List<JCTree> unseen = tree.defs;
2444            for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2445                JCTree outermostMemberDefPrev = outermostMemberDef;
2446                if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2447                l.head = translate(l.head);
2448                outermostMemberDef = outermostMemberDefPrev;
2449            }
2450            seen = unseen;
2451        }
2452
2453        // Convert a protected modifier to public, mask static modifier.
2454        if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2455        tree.mods.flags &= ClassFlags;
2456
2457        // Convert name to flat representation, replacing '.' by '$'.
2458        tree.name = Convert.shortName(currentClass.flatName());
2459
2460        // Add this$n and free variables proxy definitions to class.
2461
2462        for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2463            tree.defs = tree.defs.prepend(l.head);
2464            enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2465        }
2466        if (currentClass.hasOuterInstance()) {
2467            tree.defs = tree.defs.prepend(otdef);
2468            enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2469        }
2470
2471        proxies = proxies.leave();
2472        outerThisStack = prevOuterThisStack;
2473
2474        // Append translated tree to `translated' queue.
2475        translated.append(tree);
2476
2477        attrEnv = prevEnv;
2478        currentClass = currentClassPrev;
2479        currentMethodSym = currentMethodSymPrev;
2480
2481        // Return empty block {} as a placeholder for an inner class.
2482        result = make_at(tree.pos()).Block(SYNTHETIC, List.<JCStatement>nil());
2483    }
2484
2485    /** Translate an enum class. */
2486    private void visitEnumDef(JCClassDecl tree) {
2487        make_at(tree.pos());
2488
2489        // add the supertype, if needed
2490        if (tree.extending == null)
2491            tree.extending = make.Type(types.supertype(tree.type));
2492
2493        // classOfType adds a cache field to tree.defs
2494        JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2495            setType(types.erasure(syms.classType));
2496
2497        // process each enumeration constant, adding implicit constructor parameters
2498        int nextOrdinal = 0;
2499        ListBuffer<JCExpression> values = new ListBuffer<>();
2500        ListBuffer<JCTree> enumDefs = new ListBuffer<>();
2501        ListBuffer<JCTree> otherDefs = new ListBuffer<>();
2502        for (List<JCTree> defs = tree.defs;
2503             defs.nonEmpty();
2504             defs=defs.tail) {
2505            if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2506                JCVariableDecl var = (JCVariableDecl)defs.head;
2507                visitEnumConstantDef(var, nextOrdinal++);
2508                values.append(make.QualIdent(var.sym));
2509                enumDefs.append(var);
2510            } else {
2511                otherDefs.append(defs.head);
2512            }
2513        }
2514
2515        // private static final T[] #VALUES = { a, b, c };
2516        Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2517        while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash
2518            valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2519        Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2520        VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2521                                            valuesName,
2522                                            arrayType,
2523                                            tree.type.tsym);
2524        JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2525                                          List.<JCExpression>nil(),
2526                                          values.toList());
2527        newArray.type = arrayType;
2528        enumDefs.append(make.VarDef(valuesVar, newArray));
2529        tree.sym.members().enter(valuesVar);
2530
2531        Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2532                                        tree.type, List.<Type>nil());
2533        List<JCStatement> valuesBody;
2534        if (useClone()) {
2535            // return (T[]) $VALUES.clone();
2536            JCTypeCast valuesResult =
2537                make.TypeCast(valuesSym.type.getReturnType(),
2538                              make.App(make.Select(make.Ident(valuesVar),
2539                                                   syms.arrayCloneMethod)));
2540            valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2541        } else {
2542            // template: T[] $result = new T[$values.length];
2543            Name resultName = names.fromString(target.syntheticNameChar() + "result");
2544            while (tree.sym.members().findFirst(resultName) != null) // avoid name clash
2545                resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2546            VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2547                                                resultName,
2548                                                arrayType,
2549                                                valuesSym);
2550            JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2551                                  List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2552                                  null);
2553            resultArray.type = arrayType;
2554            JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2555
2556            // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2557            if (systemArraycopyMethod == null) {
2558                systemArraycopyMethod =
2559                    new MethodSymbol(PUBLIC | STATIC,
2560                                     names.fromString("arraycopy"),
2561                                     new MethodType(List.<Type>of(syms.objectType,
2562                                                            syms.intType,
2563                                                            syms.objectType,
2564                                                            syms.intType,
2565                                                            syms.intType),
2566                                                    syms.voidType,
2567                                                    List.<Type>nil(),
2568                                                    syms.methodClass),
2569                                     syms.systemType.tsym);
2570            }
2571            JCStatement copy =
2572                make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2573                                               systemArraycopyMethod),
2574                          List.of(make.Ident(valuesVar), make.Literal(0),
2575                                  make.Ident(resultVar), make.Literal(0),
2576                                  make.Select(make.Ident(valuesVar), syms.lengthVar))));
2577
2578            // template: return $result;
2579            JCStatement ret = make.Return(make.Ident(resultVar));
2580            valuesBody = List.<JCStatement>of(decl, copy, ret);
2581        }
2582
2583        JCMethodDecl valuesDef =
2584             make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2585
2586        enumDefs.append(valuesDef);
2587
2588        if (debugLower)
2589            System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2590
2591        /** The template for the following code is:
2592         *
2593         *     public static E valueOf(String name) {
2594         *         return (E)Enum.valueOf(E.class, name);
2595         *     }
2596         *
2597         *  where E is tree.sym
2598         */
2599        MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2600                         names.valueOf,
2601                         tree.sym.type,
2602                         List.of(syms.stringType));
2603        Assert.check((valueOfSym.flags() & STATIC) != 0);
2604        VarSymbol nameArgSym = valueOfSym.params.head;
2605        JCIdent nameVal = make.Ident(nameArgSym);
2606        JCStatement enum_ValueOf =
2607            make.Return(make.TypeCast(tree.sym.type,
2608                                      makeCall(make.Ident(syms.enumSym),
2609                                               names.valueOf,
2610                                               List.of(e_class, nameVal))));
2611        JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2612                                           make.Block(0, List.of(enum_ValueOf)));
2613        nameVal.sym = valueOf.params.head.sym;
2614        if (debugLower)
2615            System.err.println(tree.sym + ".valueOf = " + valueOf);
2616        enumDefs.append(valueOf);
2617
2618        enumDefs.appendList(otherDefs.toList());
2619        tree.defs = enumDefs.toList();
2620    }
2621        // where
2622        private MethodSymbol systemArraycopyMethod;
2623        private boolean useClone() {
2624            try {
2625                return syms.objectType.tsym.members().findFirst(names.clone) != null;
2626            }
2627            catch (CompletionFailure e) {
2628                return false;
2629            }
2630        }
2631
2632    /** Translate an enumeration constant and its initializer. */
2633    private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2634        JCNewClass varDef = (JCNewClass)var.init;
2635        varDef.args = varDef.args.
2636            prepend(makeLit(syms.intType, ordinal)).
2637            prepend(makeLit(syms.stringType, var.name.toString()));
2638    }
2639
2640    public void visitMethodDef(JCMethodDecl tree) {
2641        if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2642            // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2643            // argument list for each constructor of an enum.
2644            JCVariableDecl nameParam = make_at(tree.pos()).
2645                Param(names.fromString(target.syntheticNameChar() +
2646                                       "enum" + target.syntheticNameChar() + "name"),
2647                      syms.stringType, tree.sym);
2648            nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2649            JCVariableDecl ordParam = make.
2650                Param(names.fromString(target.syntheticNameChar() +
2651                                       "enum" + target.syntheticNameChar() +
2652                                       "ordinal"),
2653                      syms.intType, tree.sym);
2654            ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2655
2656            MethodSymbol m = tree.sym;
2657            tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2658
2659            m.extraParams = m.extraParams.prepend(ordParam.sym);
2660            m.extraParams = m.extraParams.prepend(nameParam.sym);
2661            Type olderasure = m.erasure(types);
2662            m.erasure_field = new MethodType(
2663                olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2664                olderasure.getReturnType(),
2665                olderasure.getThrownTypes(),
2666                syms.methodClass);
2667        }
2668
2669        JCMethodDecl prevMethodDef = currentMethodDef;
2670        MethodSymbol prevMethodSym = currentMethodSym;
2671        try {
2672            currentMethodDef = tree;
2673            currentMethodSym = tree.sym;
2674            visitMethodDefInternal(tree);
2675        } finally {
2676            currentMethodDef = prevMethodDef;
2677            currentMethodSym = prevMethodSym;
2678        }
2679    }
2680
2681    private void visitMethodDefInternal(JCMethodDecl tree) {
2682        if (tree.name == names.init &&
2683            (currentClass.isInner() || currentClass.isLocal())) {
2684            // We are seeing a constructor of an inner class.
2685            MethodSymbol m = tree.sym;
2686
2687            // Push a new proxy scope for constructor parameters.
2688            // and create definitions for any this$n and proxy parameters.
2689            proxies = proxies.dup(m);
2690            List<VarSymbol> prevOuterThisStack = outerThisStack;
2691            List<VarSymbol> fvs = freevars(currentClass);
2692            JCVariableDecl otdef = null;
2693            if (currentClass.hasOuterInstance())
2694                otdef = outerThisDef(tree.pos, m);
2695            List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER);
2696
2697            // Recursively translate result type, parameters and thrown list.
2698            tree.restype = translate(tree.restype);
2699            tree.params = translateVarDefs(tree.params);
2700            tree.thrown = translate(tree.thrown);
2701
2702            // when compiling stubs, don't process body
2703            if (tree.body == null) {
2704                result = tree;
2705                return;
2706            }
2707
2708            // Add this$n (if needed) in front of and free variables behind
2709            // constructor parameter list.
2710            tree.params = tree.params.appendList(fvdefs);
2711            if (currentClass.hasOuterInstance()) {
2712                tree.params = tree.params.prepend(otdef);
2713            }
2714
2715            // If this is an initial constructor, i.e., it does not start with
2716            // this(...), insert initializers for this$n and proxies
2717            // before (pre-1.4, after) the call to superclass constructor.
2718            JCStatement selfCall = translate(tree.body.stats.head);
2719
2720            List<JCStatement> added = List.nil();
2721            if (fvs.nonEmpty()) {
2722                List<Type> addedargtypes = List.nil();
2723                for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2724                    final Name pName = proxyName(l.head.name);
2725                    m.capturedLocals =
2726                        m.capturedLocals.prepend((VarSymbol)
2727                                                (proxies.findFirst(pName)));
2728                    if (TreeInfo.isInitialConstructor(tree)) {
2729                        added = added.prepend(
2730                          initField(tree.body.pos, pName));
2731                    }
2732                    addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2733                }
2734                Type olderasure = m.erasure(types);
2735                m.erasure_field = new MethodType(
2736                    olderasure.getParameterTypes().appendList(addedargtypes),
2737                    olderasure.getReturnType(),
2738                    olderasure.getThrownTypes(),
2739                    syms.methodClass);
2740            }
2741            if (currentClass.hasOuterInstance() &&
2742                TreeInfo.isInitialConstructor(tree))
2743            {
2744                added = added.prepend(initOuterThis(tree.body.pos));
2745            }
2746
2747            // pop local variables from proxy stack
2748            proxies = proxies.leave();
2749
2750            // recursively translate following local statements and
2751            // combine with this- or super-call
2752            List<JCStatement> stats = translate(tree.body.stats.tail);
2753            tree.body.stats = stats.prepend(selfCall).prependList(added);
2754            outerThisStack = prevOuterThisStack;
2755        } else {
2756            Map<Symbol, Symbol> prevLambdaTranslationMap =
2757                    lambdaTranslationMap;
2758            try {
2759                lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
2760                        tree.sym.name.startsWith(names.lambda) ?
2761                        makeTranslationMap(tree) : null;
2762                super.visitMethodDef(tree);
2763            } finally {
2764                lambdaTranslationMap = prevLambdaTranslationMap;
2765            }
2766        }
2767        result = tree;
2768    }
2769    //where
2770        private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
2771            Map<Symbol, Symbol> translationMap = new HashMap<>();
2772            for (JCVariableDecl vd : tree.params) {
2773                Symbol p = vd.sym;
2774                if (p != p.baseSymbol()) {
2775                    translationMap.put(p.baseSymbol(), p);
2776                }
2777            }
2778            return translationMap;
2779        }
2780
2781    public void visitTypeCast(JCTypeCast tree) {
2782        tree.clazz = translate(tree.clazz);
2783        if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2784            tree.expr = translate(tree.expr, tree.type);
2785        else
2786            tree.expr = translate(tree.expr);
2787        result = tree;
2788    }
2789
2790    public void visitNewClass(JCNewClass tree) {
2791        ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2792
2793        // Box arguments, if necessary
2794        boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2795        List<Type> argTypes = tree.constructor.type.getParameterTypes();
2796        if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2797        tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2798        tree.varargsElement = null;
2799
2800        // If created class is local, add free variables after
2801        // explicit constructor arguments.
2802        if (c.isLocal()) {
2803            tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2804        }
2805
2806        // If an access constructor is used, append null as a last argument.
2807        Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2808        if (constructor != tree.constructor) {
2809            tree.args = tree.args.append(makeNull());
2810            tree.constructor = constructor;
2811        }
2812
2813        // If created class has an outer instance, and new is qualified, pass
2814        // qualifier as first argument. If new is not qualified, pass the
2815        // correct outer instance as first argument.
2816        if (c.hasOuterInstance()) {
2817            JCExpression thisArg;
2818            if (tree.encl != null) {
2819                thisArg = attr.makeNullCheck(translate(tree.encl));
2820                thisArg.type = tree.encl.type;
2821            } else if (c.isLocal()) {
2822                // local class
2823                thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2824            } else {
2825                // nested class
2826                thisArg = makeOwnerThis(tree.pos(), c, false);
2827            }
2828            tree.args = tree.args.prepend(thisArg);
2829        }
2830        tree.encl = null;
2831
2832        // If we have an anonymous class, create its flat version, rather
2833        // than the class or interface following new.
2834        if (tree.def != null) {
2835            translate(tree.def);
2836            tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2837            tree.def = null;
2838        } else {
2839            tree.clazz = access(c, tree.clazz, enclOp, false);
2840        }
2841        result = tree;
2842    }
2843
2844    // Simplify conditionals with known constant controlling expressions.
2845    // This allows us to avoid generating supporting declarations for
2846    // the dead code, which will not be eliminated during code generation.
2847    // Note that Flow.isFalse and Flow.isTrue only return true
2848    // for constant expressions in the sense of JLS 15.27, which
2849    // are guaranteed to have no side-effects.  More aggressive
2850    // constant propagation would require that we take care to
2851    // preserve possible side-effects in the condition expression.
2852
2853    // One common case is equality expressions involving a constant and null.
2854    // Since null is not a constant expression (because null cannot be
2855    // represented in the constant pool), equality checks involving null are
2856    // not captured by Flow.isTrue/isFalse.
2857    // Equality checks involving a constant and null, e.g.
2858    //     "" == null
2859    // are safe to simplify as no side-effects can occur.
2860
2861    private boolean isTrue(JCTree exp) {
2862        if (exp.type.isTrue())
2863            return true;
2864        Boolean b = expValue(exp);
2865        return b == null ? false : b;
2866    }
2867    private boolean isFalse(JCTree exp) {
2868        if (exp.type.isFalse())
2869            return true;
2870        Boolean b = expValue(exp);
2871        return b == null ? false : !b;
2872    }
2873    /* look for (in)equality relations involving null.
2874     * return true - if expression is always true
2875     *       false - if expression is always false
2876     *        null - if expression cannot be eliminated
2877     */
2878    private Boolean expValue(JCTree exp) {
2879        while (exp.hasTag(PARENS))
2880            exp = ((JCParens)exp).expr;
2881
2882        boolean eq;
2883        switch (exp.getTag()) {
2884        case EQ: eq = true;  break;
2885        case NE: eq = false; break;
2886        default:
2887            return null;
2888        }
2889
2890        // we have a JCBinary(EQ|NE)
2891        // check if we have two literals (constants or null)
2892        JCBinary b = (JCBinary)exp;
2893        if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs);
2894        if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs);
2895        return null;
2896    }
2897    private Boolean expValueIsNull(boolean eq, JCTree t) {
2898        if (t.type.hasTag(BOT)) return Boolean.valueOf(eq);
2899        if (t.hasTag(LITERAL))  return Boolean.valueOf(!eq);
2900        return null;
2901    }
2902
2903    /** Visitor method for conditional expressions.
2904     */
2905    @Override
2906    public void visitConditional(JCConditional tree) {
2907        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2908        if (isTrue(cond)) {
2909            result = convert(translate(tree.truepart, tree.type), tree.type);
2910            addPrunedInfo(cond);
2911        } else if (isFalse(cond)) {
2912            result = convert(translate(tree.falsepart, tree.type), tree.type);
2913            addPrunedInfo(cond);
2914        } else {
2915            // Condition is not a compile-time constant.
2916            tree.truepart = translate(tree.truepart, tree.type);
2917            tree.falsepart = translate(tree.falsepart, tree.type);
2918            result = tree;
2919        }
2920    }
2921//where
2922    private JCExpression convert(JCExpression tree, Type pt) {
2923        if (tree.type == pt || tree.type.hasTag(BOT))
2924            return tree;
2925        JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree);
2926        result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2927                                                       : pt;
2928        return result;
2929    }
2930
2931    /** Visitor method for if statements.
2932     */
2933    public void visitIf(JCIf tree) {
2934        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2935        if (isTrue(cond)) {
2936            result = translate(tree.thenpart);
2937            addPrunedInfo(cond);
2938        } else if (isFalse(cond)) {
2939            if (tree.elsepart != null) {
2940                result = translate(tree.elsepart);
2941            } else {
2942                result = make.Skip();
2943            }
2944            addPrunedInfo(cond);
2945        } else {
2946            // Condition is not a compile-time constant.
2947            tree.thenpart = translate(tree.thenpart);
2948            tree.elsepart = translate(tree.elsepart);
2949            result = tree;
2950        }
2951    }
2952
2953    /** Visitor method for assert statements. Translate them away.
2954     */
2955    public void visitAssert(JCAssert tree) {
2956        DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2957        tree.cond = translate(tree.cond, syms.booleanType);
2958        if (!tree.cond.type.isTrue()) {
2959            JCExpression cond = assertFlagTest(tree.pos());
2960            List<JCExpression> exnArgs = (tree.detail == null) ?
2961                List.<JCExpression>nil() : List.of(translate(tree.detail));
2962            if (!tree.cond.type.isFalse()) {
2963                cond = makeBinary
2964                    (AND,
2965                     cond,
2966                     makeUnary(NOT, tree.cond));
2967            }
2968            result =
2969                make.If(cond,
2970                        make_at(tree).
2971                           Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2972                        null);
2973        } else {
2974            result = make.Skip();
2975        }
2976    }
2977
2978    public void visitApply(JCMethodInvocation tree) {
2979        Symbol meth = TreeInfo.symbol(tree.meth);
2980        List<Type> argtypes = meth.type.getParameterTypes();
2981        if (meth.name == names.init && meth.owner == syms.enumSym)
2982            argtypes = argtypes.tail.tail;
2983        tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2984        tree.varargsElement = null;
2985        Name methName = TreeInfo.name(tree.meth);
2986        if (meth.name==names.init) {
2987            // We are seeing a this(...) or super(...) constructor call.
2988            // If an access constructor is used, append null as a last argument.
2989            Symbol constructor = accessConstructor(tree.pos(), meth);
2990            if (constructor != meth) {
2991                tree.args = tree.args.append(makeNull());
2992                TreeInfo.setSymbol(tree.meth, constructor);
2993            }
2994
2995            // If we are calling a constructor of a local class, add
2996            // free variables after explicit constructor arguments.
2997            ClassSymbol c = (ClassSymbol)constructor.owner;
2998            if (c.isLocal()) {
2999                tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
3000            }
3001
3002            // If we are calling a constructor of an enum class, pass
3003            // along the name and ordinal arguments
3004            if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
3005                List<JCVariableDecl> params = currentMethodDef.params;
3006                if (currentMethodSym.owner.hasOuterInstance())
3007                    params = params.tail; // drop this$n
3008                tree.args = tree.args
3009                    .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
3010                    .prepend(make.Ident(params.head.sym)); // name
3011            }
3012
3013            // If we are calling a constructor of a class with an outer
3014            // instance, and the call
3015            // is qualified, pass qualifier as first argument in front of
3016            // the explicit constructor arguments. If the call
3017            // is not qualified, pass the correct outer instance as
3018            // first argument.
3019            if (c.hasOuterInstance()) {
3020                JCExpression thisArg;
3021                if (tree.meth.hasTag(SELECT)) {
3022                    thisArg = attr.
3023                        makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
3024                    tree.meth = make.Ident(constructor);
3025                    ((JCIdent) tree.meth).name = methName;
3026                } else if (c.isLocal() || methName == names._this){
3027                    // local class or this() call
3028                    thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
3029                } else {
3030                    // super() call of nested class - never pick 'this'
3031                    thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
3032                }
3033                tree.args = tree.args.prepend(thisArg);
3034            }
3035        } else {
3036            // We are seeing a normal method invocation; translate this as usual.
3037            tree.meth = translate(tree.meth);
3038
3039            // If the translated method itself is an Apply tree, we are
3040            // seeing an access method invocation. In this case, append
3041            // the method arguments to the arguments of the access method.
3042            if (tree.meth.hasTag(APPLY)) {
3043                JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3044                app.args = tree.args.prependList(app.args);
3045                result = app;
3046                return;
3047            }
3048        }
3049        result = tree;
3050    }
3051
3052    List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3053        List<JCExpression> args = _args;
3054        if (parameters.isEmpty()) return args;
3055        boolean anyChanges = false;
3056        ListBuffer<JCExpression> result = new ListBuffer<>();
3057        while (parameters.tail.nonEmpty()) {
3058            JCExpression arg = translate(args.head, parameters.head);
3059            anyChanges |= (arg != args.head);
3060            result.append(arg);
3061            args = args.tail;
3062            parameters = parameters.tail;
3063        }
3064        Type parameter = parameters.head;
3065        if (varargsElement != null) {
3066            anyChanges = true;
3067            ListBuffer<JCExpression> elems = new ListBuffer<>();
3068            while (args.nonEmpty()) {
3069                JCExpression arg = translate(args.head, varargsElement);
3070                elems.append(arg);
3071                args = args.tail;
3072            }
3073            JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3074                                               List.<JCExpression>nil(),
3075                                               elems.toList());
3076            boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3077            result.append(boxedArgs);
3078        } else {
3079            if (args.length() != 1) throw new AssertionError(args);
3080            JCExpression arg = translate(args.head, parameter);
3081            anyChanges |= (arg != args.head);
3082            result.append(arg);
3083            if (!anyChanges) return _args;
3084        }
3085        return result.toList();
3086    }
3087
3088    /** Expand a boxing or unboxing conversion if needed. */
3089    @SuppressWarnings("unchecked") // XXX unchecked
3090    <T extends JCExpression> T boxIfNeeded(T tree, Type type) {
3091        boolean havePrimitive = tree.type.isPrimitive();
3092        if (havePrimitive == type.isPrimitive())
3093            return tree;
3094        if (havePrimitive) {
3095            Type unboxedTarget = types.unboxedType(type);
3096            if (!unboxedTarget.hasTag(NONE)) {
3097                if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3098                    tree.type = unboxedTarget.constType(tree.type.constValue());
3099                return (T)boxPrimitive(tree, types.erasure(type));
3100            } else {
3101                tree = (T)boxPrimitive(tree);
3102            }
3103        } else {
3104            tree = (T)unbox(tree, type);
3105        }
3106        return tree;
3107    }
3108
3109    /** Box up a single primitive expression. */
3110    JCExpression boxPrimitive(JCExpression tree) {
3111        return boxPrimitive(tree, types.boxedClass(tree.type).type);
3112    }
3113
3114    /** Box up a single primitive expression. */
3115    JCExpression boxPrimitive(JCExpression tree, Type box) {
3116        make_at(tree.pos());
3117        Symbol valueOfSym = lookupMethod(tree.pos(),
3118                                         names.valueOf,
3119                                         box,
3120                                         List.<Type>nil()
3121                                         .prepend(tree.type));
3122        return make.App(make.QualIdent(valueOfSym), List.of(tree));
3123    }
3124
3125    /** Unbox an object to a primitive value. */
3126    JCExpression unbox(JCExpression tree, Type primitive) {
3127        Type unboxedType = types.unboxedType(tree.type);
3128        if (unboxedType.hasTag(NONE)) {
3129            unboxedType = primitive;
3130            if (!unboxedType.isPrimitive())
3131                throw new AssertionError(unboxedType);
3132            make_at(tree.pos());
3133            tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3134        } else {
3135            // There must be a conversion from unboxedType to primitive.
3136            if (!types.isSubtype(unboxedType, primitive))
3137                throw new AssertionError(tree);
3138        }
3139        make_at(tree.pos());
3140        Symbol valueSym = lookupMethod(tree.pos(),
3141                                       unboxedType.tsym.name.append(names.Value), // x.intValue()
3142                                       tree.type,
3143                                       List.<Type>nil());
3144        return make.App(make.Select(tree, valueSym));
3145    }
3146
3147    /** Visitor method for parenthesized expressions.
3148     *  If the subexpression has changed, omit the parens.
3149     */
3150    public void visitParens(JCParens tree) {
3151        JCTree expr = translate(tree.expr);
3152        result = ((expr == tree.expr) ? tree : expr);
3153    }
3154
3155    public void visitIndexed(JCArrayAccess tree) {
3156        tree.indexed = translate(tree.indexed);
3157        tree.index = translate(tree.index, syms.intType);
3158        result = tree;
3159    }
3160
3161    public void visitAssign(JCAssign tree) {
3162        tree.lhs = translate(tree.lhs, tree);
3163        tree.rhs = translate(tree.rhs, tree.lhs.type);
3164
3165        // If translated left hand side is an Apply, we are
3166        // seeing an access method invocation. In this case, append
3167        // right hand side as last argument of the access method.
3168        if (tree.lhs.hasTag(APPLY)) {
3169            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3170            app.args = List.of(tree.rhs).prependList(app.args);
3171            result = app;
3172        } else {
3173            result = tree;
3174        }
3175    }
3176
3177    public void visitAssignop(final JCAssignOp tree) {
3178        JCTree lhsAccess = access(TreeInfo.skipParens(tree.lhs));
3179        final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3180            tree.operator.type.getReturnType().isPrimitive();
3181
3182        if (boxingReq || lhsAccess.hasTag(APPLY)) {
3183            // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3184            // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3185            // (but without recomputing x)
3186            JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3187                    public JCExpression build(final JCExpression lhs) {
3188                        JCTree.Tag newTag = tree.getTag().noAssignOp();
3189                        // Erasure (TransTypes) can change the type of
3190                        // tree.lhs.  However, we can still get the
3191                        // unerased type of tree.lhs as it is stored
3192                        // in tree.type in Attr.
3193                        Symbol newOperator = operators.resolveBinary(tree,
3194                                                                      newTag,
3195                                                                      tree.type,
3196                                                                      tree.rhs.type);
3197                        JCExpression expr = lhs;
3198                        if (expr.type != tree.type)
3199                            expr = make.TypeCast(tree.type, expr);
3200                        JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3201                        opResult.operator = newOperator;
3202                        opResult.type = newOperator.type.getReturnType();
3203                        JCExpression newRhs = boxingReq ?
3204                            make.TypeCast(types.unboxedType(tree.type), opResult) :
3205                            opResult;
3206                        return make.Assign(lhs, newRhs).setType(tree.type);
3207                    }
3208                });
3209            result = translate(newTree);
3210            return;
3211        }
3212        tree.lhs = translate(tree.lhs, tree);
3213        tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3214
3215        // If translated left hand side is an Apply, we are
3216        // seeing an access method invocation. In this case, append
3217        // right hand side as last argument of the access method.
3218        if (tree.lhs.hasTag(APPLY)) {
3219            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3220            // if operation is a += on strings,
3221            // make sure to convert argument to string
3222            JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
3223              ? makeString(tree.rhs)
3224              : tree.rhs;
3225            app.args = List.of(rhs).prependList(app.args);
3226            result = app;
3227        } else {
3228            result = tree;
3229        }
3230    }
3231
3232    /** Lower a tree of the form e++ or e-- where e is an object type */
3233    JCExpression lowerBoxedPostop(final JCUnary tree) {
3234        // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3235        // or
3236        // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3237        // where OP is += or -=
3238        final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3239        return abstractLval(tree.arg, new TreeBuilder() {
3240                public JCExpression build(final JCExpression tmp1) {
3241                    return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3242                            public JCExpression build(final JCExpression tmp2) {
3243                                JCTree.Tag opcode = (tree.hasTag(POSTINC))
3244                                    ? PLUS_ASG : MINUS_ASG;
3245                                JCTree lhs = cast
3246                                    ? make.TypeCast(tree.arg.type, tmp1)
3247                                    : tmp1;
3248                                JCExpression update = makeAssignop(opcode,
3249                                                             lhs,
3250                                                             make.Literal(1));
3251                                return makeComma(update, tmp2);
3252                            }
3253                        });
3254                }
3255            });
3256    }
3257
3258    public void visitUnary(JCUnary tree) {
3259        boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3260        if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3261            switch(tree.getTag()) {
3262            case PREINC:            // ++ e
3263                    // translate to e += 1
3264            case PREDEC:            // -- e
3265                    // translate to e -= 1
3266                {
3267                    JCTree.Tag opcode = (tree.hasTag(PREINC))
3268                        ? PLUS_ASG : MINUS_ASG;
3269                    JCAssignOp newTree = makeAssignop(opcode,
3270                                                    tree.arg,
3271                                                    make.Literal(1));
3272                    result = translate(newTree, tree.type);
3273                    return;
3274                }
3275            case POSTINC:           // e ++
3276            case POSTDEC:           // e --
3277                {
3278                    result = translate(lowerBoxedPostop(tree), tree.type);
3279                    return;
3280                }
3281            }
3282            throw new AssertionError(tree);
3283        }
3284
3285        tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3286
3287        if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3288            tree.type = cfolder.fold1(bool_not, tree.arg.type);
3289        }
3290
3291        // If translated left hand side is an Apply, we are
3292        // seeing an access method invocation. In this case, return
3293        // that access method invocation as result.
3294        if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3295            result = tree.arg;
3296        } else {
3297            result = tree;
3298        }
3299    }
3300
3301    public void visitBinary(JCBinary tree) {
3302        List<Type> formals = tree.operator.type.getParameterTypes();
3303        JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3304        switch (tree.getTag()) {
3305        case OR:
3306            if (isTrue(lhs)) {
3307                result = lhs;
3308                return;
3309            }
3310            if (isFalse(lhs)) {
3311                result = translate(tree.rhs, formals.tail.head);
3312                return;
3313            }
3314            break;
3315        case AND:
3316            if (isFalse(lhs)) {
3317                result = lhs;
3318                return;
3319            }
3320            if (isTrue(lhs)) {
3321                result = translate(tree.rhs, formals.tail.head);
3322                return;
3323            }
3324            break;
3325        }
3326        tree.rhs = translate(tree.rhs, formals.tail.head);
3327        result = tree;
3328    }
3329
3330    public void visitIdent(JCIdent tree) {
3331        result = access(tree.sym, tree, enclOp, false);
3332    }
3333
3334    /** Translate away the foreach loop.  */
3335    public void visitForeachLoop(JCEnhancedForLoop tree) {
3336        if (types.elemtype(tree.expr.type) == null)
3337            visitIterableForeachLoop(tree);
3338        else
3339            visitArrayForeachLoop(tree);
3340    }
3341        // where
3342        /**
3343         * A statement of the form
3344         *
3345         * <pre>
3346         *     for ( T v : arrayexpr ) stmt;
3347         * </pre>
3348         *
3349         * (where arrayexpr is of an array type) gets translated to
3350         *
3351         * <pre>{@code
3352         *     for ( { arraytype #arr = arrayexpr;
3353         *             int #len = array.length;
3354         *             int #i = 0; };
3355         *           #i < #len; i$++ ) {
3356         *         T v = arr$[#i];
3357         *         stmt;
3358         *     }
3359         * }</pre>
3360         *
3361         * where #arr, #len, and #i are freshly named synthetic local variables.
3362         */
3363        private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3364            make_at(tree.expr.pos());
3365            VarSymbol arraycache = new VarSymbol(SYNTHETIC,
3366                                                 names.fromString("arr" + target.syntheticNameChar()),
3367                                                 tree.expr.type,
3368                                                 currentMethodSym);
3369            JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3370            VarSymbol lencache = new VarSymbol(SYNTHETIC,
3371                                               names.fromString("len" + target.syntheticNameChar()),
3372                                               syms.intType,
3373                                               currentMethodSym);
3374            JCStatement lencachedef = make.
3375                VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3376            VarSymbol index = new VarSymbol(SYNTHETIC,
3377                                            names.fromString("i" + target.syntheticNameChar()),
3378                                            syms.intType,
3379                                            currentMethodSym);
3380
3381            JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3382            indexdef.init.type = indexdef.type = syms.intType.constType(0);
3383
3384            List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3385            JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3386
3387            JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3388
3389            Type elemtype = types.elemtype(tree.expr.type);
3390            JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3391                                                    make.Ident(index)).setType(elemtype);
3392            JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3393                                                  tree.var.name,
3394                                                  tree.var.vartype,
3395                                                  loopvarinit).setType(tree.var.type);
3396            loopvardef.sym = tree.var.sym;
3397            JCBlock body = make.
3398                Block(0, List.of(loopvardef, tree.body));
3399
3400            result = translate(make.
3401                               ForLoop(loopinit,
3402                                       cond,
3403                                       List.of(step),
3404                                       body));
3405            patchTargets(body, tree, result);
3406        }
3407        /** Patch up break and continue targets. */
3408        private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3409            class Patcher extends TreeScanner {
3410                public void visitBreak(JCBreak tree) {
3411                    if (tree.target == src)
3412                        tree.target = dest;
3413                }
3414                public void visitContinue(JCContinue tree) {
3415                    if (tree.target == src)
3416                        tree.target = dest;
3417                }
3418                public void visitClassDef(JCClassDecl tree) {}
3419            }
3420            new Patcher().scan(body);
3421        }
3422        /**
3423         * A statement of the form
3424         *
3425         * <pre>
3426         *     for ( T v : coll ) stmt ;
3427         * </pre>
3428         *
3429         * (where coll implements {@code Iterable<? extends T>}) gets translated to
3430         *
3431         * <pre>{@code
3432         *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3433         *         T v = (T) #i.next();
3434         *         stmt;
3435         *     }
3436         * }</pre>
3437         *
3438         * where #i is a freshly named synthetic local variable.
3439         */
3440        private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3441            make_at(tree.expr.pos());
3442            Type iteratorTarget = syms.objectType;
3443            Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type),
3444                                              syms.iterableType.tsym);
3445            if (iterableType.getTypeArguments().nonEmpty())
3446                iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3447            Type eType = types.skipTypeVars(tree.expr.type, false);
3448            tree.expr.type = types.erasure(eType);
3449            if (eType.isCompound())
3450                tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3451            Symbol iterator = lookupMethod(tree.expr.pos(),
3452                                           names.iterator,
3453                                           eType,
3454                                           List.<Type>nil());
3455            VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
3456                                            types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)),
3457                                            currentMethodSym);
3458
3459             JCStatement init = make.
3460                VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3461                     .setType(types.erasure(iterator.type))));
3462
3463            Symbol hasNext = lookupMethod(tree.expr.pos(),
3464                                          names.hasNext,
3465                                          itvar.type,
3466                                          List.<Type>nil());
3467            JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3468            Symbol next = lookupMethod(tree.expr.pos(),
3469                                       names.next,
3470                                       itvar.type,
3471                                       List.<Type>nil());
3472            JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3473            if (tree.var.type.isPrimitive())
3474                vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
3475            else
3476                vardefinit = make.TypeCast(tree.var.type, vardefinit);
3477            JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3478                                                  tree.var.name,
3479                                                  tree.var.vartype,
3480                                                  vardefinit).setType(tree.var.type);
3481            indexDef.sym = tree.var.sym;
3482            JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3483            body.endpos = TreeInfo.endPos(tree.body);
3484            result = translate(make.
3485                ForLoop(List.of(init),
3486                        cond,
3487                        List.<JCExpressionStatement>nil(),
3488                        body));
3489            patchTargets(body, tree, result);
3490        }
3491
3492    public void visitVarDef(JCVariableDecl tree) {
3493        MethodSymbol oldMethodSym = currentMethodSym;
3494        tree.mods = translate(tree.mods);
3495        tree.vartype = translate(tree.vartype);
3496        if (currentMethodSym == null) {
3497            // A class or instance field initializer.
3498            currentMethodSym =
3499                new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3500                                 names.empty, null,
3501                                 currentClass);
3502        }
3503        if (tree.init != null) tree.init = translate(tree.init, tree.type);
3504        result = tree;
3505        currentMethodSym = oldMethodSym;
3506    }
3507
3508    public void visitBlock(JCBlock tree) {
3509        MethodSymbol oldMethodSym = currentMethodSym;
3510        if (currentMethodSym == null) {
3511            // Block is a static or instance initializer.
3512            currentMethodSym =
3513                new MethodSymbol(tree.flags | BLOCK,
3514                                 names.empty, null,
3515                                 currentClass);
3516        }
3517        super.visitBlock(tree);
3518        currentMethodSym = oldMethodSym;
3519    }
3520
3521    public void visitDoLoop(JCDoWhileLoop tree) {
3522        tree.body = translate(tree.body);
3523        tree.cond = translate(tree.cond, syms.booleanType);
3524        result = tree;
3525    }
3526
3527    public void visitWhileLoop(JCWhileLoop tree) {
3528        tree.cond = translate(tree.cond, syms.booleanType);
3529        tree.body = translate(tree.body);
3530        result = tree;
3531    }
3532
3533    public void visitForLoop(JCForLoop tree) {
3534        tree.init = translate(tree.init);
3535        if (tree.cond != null)
3536            tree.cond = translate(tree.cond, syms.booleanType);
3537        tree.step = translate(tree.step);
3538        tree.body = translate(tree.body);
3539        result = tree;
3540    }
3541
3542    public void visitReturn(JCReturn tree) {
3543        if (tree.expr != null)
3544            tree.expr = translate(tree.expr,
3545                                  types.erasure(currentMethodDef
3546                                                .restype.type));
3547        result = tree;
3548    }
3549
3550    public void visitSwitch(JCSwitch tree) {
3551        Type selsuper = types.supertype(tree.selector.type);
3552        boolean enumSwitch = selsuper != null &&
3553            (tree.selector.type.tsym.flags() & ENUM) != 0;
3554        boolean stringSwitch = selsuper != null &&
3555            types.isSameType(tree.selector.type, syms.stringType);
3556        Type target = enumSwitch ? tree.selector.type :
3557            (stringSwitch? syms.stringType : syms.intType);
3558        tree.selector = translate(tree.selector, target);
3559        tree.cases = translateCases(tree.cases);
3560        if (enumSwitch) {
3561            result = visitEnumSwitch(tree);
3562        } else if (stringSwitch) {
3563            result = visitStringSwitch(tree);
3564        } else {
3565            result = tree;
3566        }
3567    }
3568
3569    public JCTree visitEnumSwitch(JCSwitch tree) {
3570        TypeSymbol enumSym = tree.selector.type.tsym;
3571        EnumMapping map = mapForEnum(tree.pos(), enumSym);
3572        make_at(tree.pos());
3573        Symbol ordinalMethod = lookupMethod(tree.pos(),
3574                                            names.ordinal,
3575                                            tree.selector.type,
3576                                            List.<Type>nil());
3577        JCArrayAccess selector = make.Indexed(map.mapVar,
3578                                        make.App(make.Select(tree.selector,
3579                                                             ordinalMethod)));
3580        ListBuffer<JCCase> cases = new ListBuffer<>();
3581        for (JCCase c : tree.cases) {
3582            if (c.pat != null) {
3583                VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3584                JCLiteral pat = map.forConstant(label);
3585                cases.append(make.Case(pat, c.stats));
3586            } else {
3587                cases.append(c);
3588            }
3589        }
3590        JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3591        patchTargets(enumSwitch, tree, enumSwitch);
3592        return enumSwitch;
3593    }
3594
3595    public JCTree visitStringSwitch(JCSwitch tree) {
3596        List<JCCase> caseList = tree.getCases();
3597        int alternatives = caseList.size();
3598
3599        if (alternatives == 0) { // Strange but legal possibility
3600            return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3601        } else {
3602            /*
3603             * The general approach used is to translate a single
3604             * string switch statement into a series of two chained
3605             * switch statements: the first a synthesized statement
3606             * switching on the argument string's hash value and
3607             * computing a string's position in the list of original
3608             * case labels, if any, followed by a second switch on the
3609             * computed integer value.  The second switch has the same
3610             * code structure as the original string switch statement
3611             * except that the string case labels are replaced with
3612             * positional integer constants starting at 0.
3613             *
3614             * The first switch statement can be thought of as an
3615             * inlined map from strings to their position in the case
3616             * label list.  An alternate implementation would use an
3617             * actual Map for this purpose, as done for enum switches.
3618             *
3619             * With some additional effort, it would be possible to
3620             * use a single switch statement on the hash code of the
3621             * argument, but care would need to be taken to preserve
3622             * the proper control flow in the presence of hash
3623             * collisions and other complications, such as
3624             * fallthroughs.  Switch statements with one or two
3625             * alternatives could also be specially translated into
3626             * if-then statements to omit the computation of the hash
3627             * code.
3628             *
3629             * The generated code assumes that the hashing algorithm
3630             * of String is the same in the compilation environment as
3631             * in the environment the code will run in.  The string
3632             * hashing algorithm in the SE JDK has been unchanged
3633             * since at least JDK 1.2.  Since the algorithm has been
3634             * specified since that release as well, it is very
3635             * unlikely to be changed in the future.
3636             *
3637             * Different hashing algorithms, such as the length of the
3638             * strings or a perfect hashing algorithm over the
3639             * particular set of case labels, could potentially be
3640             * used instead of String.hashCode.
3641             */
3642
3643            ListBuffer<JCStatement> stmtList = new ListBuffer<>();
3644
3645            // Map from String case labels to their original position in
3646            // the list of case labels.
3647            Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f);
3648
3649            // Map of hash codes to the string case labels having that hashCode.
3650            Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f);
3651
3652            int casePosition = 0;
3653            for(JCCase oneCase : caseList) {
3654                JCExpression expression = oneCase.getExpression();
3655
3656                if (expression != null) { // expression for a "default" case is null
3657                    String labelExpr = (String) expression.type.constValue();
3658                    Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3659                    Assert.checkNull(mapping);
3660                    int hashCode = labelExpr.hashCode();
3661
3662                    Set<String> stringSet = hashToString.get(hashCode);
3663                    if (stringSet == null) {
3664                        stringSet = new LinkedHashSet<>(1, 1.0f);
3665                        stringSet.add(labelExpr);
3666                        hashToString.put(hashCode, stringSet);
3667                    } else {
3668                        boolean added = stringSet.add(labelExpr);
3669                        Assert.check(added);
3670                    }
3671                }
3672                casePosition++;
3673            }
3674
3675            // Synthesize a switch statement that has the effect of
3676            // mapping from a string to the integer position of that
3677            // string in the list of case labels.  This is done by
3678            // switching on the hashCode of the string followed by an
3679            // if-then-else chain comparing the input for equality
3680            // with all the case labels having that hash value.
3681
3682            /*
3683             * s$ = top of stack;
3684             * tmp$ = -1;
3685             * switch($s.hashCode()) {
3686             *     case caseLabel.hashCode:
3687             *         if (s$.equals("caseLabel_1")
3688             *           tmp$ = caseLabelToPosition("caseLabel_1");
3689             *         else if (s$.equals("caseLabel_2"))
3690             *           tmp$ = caseLabelToPosition("caseLabel_2");
3691             *         ...
3692             *         break;
3693             * ...
3694             * }
3695             */
3696
3697            VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3698                                               names.fromString("s" + tree.pos + target.syntheticNameChar()),
3699                                               syms.stringType,
3700                                               currentMethodSym);
3701            stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3702
3703            VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3704                                                 names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3705                                                 syms.intType,
3706                                                 currentMethodSym);
3707            JCVariableDecl dollar_tmp_def =
3708                (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3709            dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3710            stmtList.append(dollar_tmp_def);
3711            ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
3712            // hashCode will trigger nullcheck on original switch expression
3713            JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3714                                                       names.hashCode,
3715                                                       List.<JCExpression>nil()).setType(syms.intType);
3716            JCSwitch switch1 = make.Switch(hashCodeCall,
3717                                        caseBuffer.toList());
3718            for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3719                int hashCode = entry.getKey();
3720                Set<String> stringsWithHashCode = entry.getValue();
3721                Assert.check(stringsWithHashCode.size() >= 1);
3722
3723                JCStatement elsepart = null;
3724                for(String caseLabel : stringsWithHashCode ) {
3725                    JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3726                                                                   names.equals,
3727                                                                   List.<JCExpression>of(make.Literal(caseLabel)));
3728                    elsepart = make.If(stringEqualsCall,
3729                                       make.Exec(make.Assign(make.Ident(dollar_tmp),
3730                                                             make.Literal(caseLabelToPosition.get(caseLabel))).
3731                                                 setType(dollar_tmp.type)),
3732                                       elsepart);
3733                }
3734
3735                ListBuffer<JCStatement> lb = new ListBuffer<>();
3736                JCBreak breakStmt = make.Break(null);
3737                breakStmt.target = switch1;
3738                lb.append(elsepart).append(breakStmt);
3739
3740                caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3741            }
3742
3743            switch1.cases = caseBuffer.toList();
3744            stmtList.append(switch1);
3745
3746            // Make isomorphic switch tree replacing string labels
3747            // with corresponding integer ones from the label to
3748            // position map.
3749
3750            ListBuffer<JCCase> lb = new ListBuffer<>();
3751            JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3752            for(JCCase oneCase : caseList ) {
3753                // Rewire up old unlabeled break statements to the
3754                // replacement switch being created.
3755                patchTargets(oneCase, tree, switch2);
3756
3757                boolean isDefault = (oneCase.getExpression() == null);
3758                JCExpression caseExpr;
3759                if (isDefault)
3760                    caseExpr = null;
3761                else {
3762                    caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3763                                                                                                getExpression()).
3764                                                                    type.constValue()));
3765                }
3766
3767                lb.append(make.Case(caseExpr,
3768                                    oneCase.getStatements()));
3769            }
3770
3771            switch2.cases = lb.toList();
3772            stmtList.append(switch2);
3773
3774            return make.Block(0L, stmtList.toList());
3775        }
3776    }
3777
3778    public void visitNewArray(JCNewArray tree) {
3779        tree.elemtype = translate(tree.elemtype);
3780        for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3781            if (t.head != null) t.head = translate(t.head, syms.intType);
3782        tree.elems = translate(tree.elems, types.elemtype(tree.type));
3783        result = tree;
3784    }
3785
3786    public void visitSelect(JCFieldAccess tree) {
3787        // need to special case-access of the form C.super.x
3788        // these will always need an access method, unless C
3789        // is a default interface subclassed by the current class.
3790        boolean qualifiedSuperAccess =
3791            tree.selected.hasTag(SELECT) &&
3792            TreeInfo.name(tree.selected) == names._super &&
3793            !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
3794        tree.selected = translate(tree.selected);
3795        if (tree.name == names._class) {
3796            result = classOf(tree.selected);
3797        }
3798        else if (tree.name == names._super &&
3799                types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
3800            //default super call!! Not a classic qualified super call
3801            TypeSymbol supSym = tree.selected.type.tsym;
3802            Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
3803            result = tree;
3804        }
3805        else if (tree.name == names._this || tree.name == names._super) {
3806            result = makeThis(tree.pos(), tree.selected.type.tsym);
3807        }
3808        else
3809            result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3810    }
3811
3812    public void visitLetExpr(LetExpr tree) {
3813        tree.defs = translateVarDefs(tree.defs);
3814        tree.expr = translate(tree.expr, tree.type);
3815        result = tree;
3816    }
3817
3818    // There ought to be nothing to rewrite here;
3819    // we don't generate code.
3820    public void visitAnnotation(JCAnnotation tree) {
3821        result = tree;
3822    }
3823
3824    @Override
3825    public void visitTry(JCTry tree) {
3826        if (tree.resources.nonEmpty()) {
3827            result = makeTwrTry(tree);
3828            return;
3829        }
3830
3831        boolean hasBody = tree.body.getStatements().nonEmpty();
3832        boolean hasCatchers = tree.catchers.nonEmpty();
3833        boolean hasFinally = tree.finalizer != null &&
3834                tree.finalizer.getStatements().nonEmpty();
3835
3836        if (!hasCatchers && !hasFinally) {
3837            result = translate(tree.body);
3838            return;
3839        }
3840
3841        if (!hasBody) {
3842            if (hasFinally) {
3843                result = translate(tree.finalizer);
3844            } else {
3845                result = translate(tree.body);
3846            }
3847            return;
3848        }
3849
3850        // no optimizations possible
3851        super.visitTry(tree);
3852    }
3853
3854/**************************************************************************
3855 * main method
3856 *************************************************************************/
3857
3858    /** Translate a toplevel class and return a list consisting of
3859     *  the translated class and translated versions of all inner classes.
3860     *  @param env   The attribution environment current at the class definition.
3861     *               We need this for resolving some additional symbols.
3862     *  @param cdef  The tree representing the class definition.
3863     */
3864    public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3865        ListBuffer<JCTree> translated = null;
3866        try {
3867            attrEnv = env;
3868            this.make = make;
3869            endPosTable = env.toplevel.endPositions;
3870            currentClass = null;
3871            currentMethodDef = null;
3872            outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3873            outermostMemberDef = null;
3874            this.translated = new ListBuffer<>();
3875            classdefs = new HashMap<>();
3876            actualSymbols = new HashMap<>();
3877            freevarCache = new HashMap<>();
3878            proxies = WriteableScope.create(syms.noSymbol);
3879            twrVars = WriteableScope.create(syms.noSymbol);
3880            outerThisStack = List.nil();
3881            accessNums = new HashMap<>();
3882            accessSyms = new HashMap<>();
3883            accessConstrs = new HashMap<>();
3884            accessConstrTags = List.nil();
3885            accessed = new ListBuffer<>();
3886            translate(cdef, (JCExpression)null);
3887            for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3888                makeAccessible(l.head);
3889            for (EnumMapping map : enumSwitchMap.values())
3890                map.translate();
3891            checkConflicts(this.translated.toList());
3892            checkAccessConstructorTags();
3893            translated = this.translated;
3894        } finally {
3895            // note that recursive invocations of this method fail hard
3896            attrEnv = null;
3897            this.make = null;
3898            endPosTable = null;
3899            currentClass = null;
3900            currentMethodDef = null;
3901            outermostClassDef = null;
3902            outermostMemberDef = null;
3903            this.translated = null;
3904            classdefs = null;
3905            actualSymbols = null;
3906            freevarCache = null;
3907            proxies = null;
3908            outerThisStack = null;
3909            accessNums = null;
3910            accessSyms = null;
3911            accessConstrs = null;
3912            accessConstrTags = null;
3913            accessed = null;
3914            enumSwitchMap.clear();
3915            assertionsDisabledClassCache = null;
3916        }
3917        return translated.toList();
3918    }
3919}
3920