1 /*
2  * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package com.sun.tools.javac.comp;
27 
28 import java.util.*;
29 
30 import com.sun.tools.javac.code.*;
31 import com.sun.tools.javac.code.Attribute.TypeCompound;
32 import com.sun.tools.javac.code.Source.Feature;
33 import com.sun.tools.javac.code.Symbol.*;
34 import com.sun.tools.javac.code.Type.IntersectionClassType;
35 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
36 import com.sun.tools.javac.resources.CompilerProperties.Errors;
37 import com.sun.tools.javac.tree.*;
38 import com.sun.tools.javac.tree.JCTree.*;
39 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
40 import com.sun.tools.javac.util.*;
41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
42 import com.sun.tools.javac.util.List;
43 
44 import static com.sun.tools.javac.code.Flags.*;
45 import static com.sun.tools.javac.code.Kinds.Kind.*;
46 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
47 import static com.sun.tools.javac.code.TypeTag.CLASS;
48 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
49 import static com.sun.tools.javac.code.TypeTag.VOID;
50 import static com.sun.tools.javac.comp.CompileStates.CompileState;
51 
52 /** This pass translates Generic Java to conventional Java.
53  *
54  *  <p><b>This is NOT part of any supported API.
55  *  If you write code that depends on this, you do so at your own risk.
56  *  This code and its internal interfaces are subject to change or
57  *  deletion without notice.</b>
58  */
59 public class TransTypes extends TreeTranslator {
60     /** The context key for the TransTypes phase. */
61     protected static final Context.Key<TransTypes> transTypesKey = new Context.Key<>();
62 
63     /** Get the instance for this context. */
instance(Context context)64     public static TransTypes instance(Context context) {
65         TransTypes instance = context.get(transTypesKey);
66         if (instance == null)
67             instance = new TransTypes(context);
68         return instance;
69     }
70 
71     private Names names;
72     private Log log;
73     private Symtab syms;
74     private TreeMaker make;
75     private Enter enter;
76     private Types types;
77     private Annotate annotate;
78     private Attr attr;
79     private final Resolve resolve;
80     private final CompileStates compileStates;
81 
82     /** Switch: is complex graph inference supported? */
83     private final boolean allowGraphInference;
84 
85     /** Switch: are default methods supported? */
86     private final boolean allowInterfaceBridges;
87 
TransTypes(Context context)88     protected TransTypes(Context context) {
89         context.put(transTypesKey, this);
90         compileStates = CompileStates.instance(context);
91         names = Names.instance(context);
92         log = Log.instance(context);
93         syms = Symtab.instance(context);
94         enter = Enter.instance(context);
95         types = Types.instance(context);
96         make = TreeMaker.instance(context);
97         resolve = Resolve.instance(context);
98         Source source = Source.instance(context);
99         allowInterfaceBridges = Feature.DEFAULT_METHODS.allowedInSource(source);
100         allowGraphInference = Feature.GRAPH_INFERENCE.allowedInSource(source);
101         annotate = Annotate.instance(context);
102         attr = Attr.instance(context);
103     }
104 
105     /** Construct an attributed tree for a cast of expression to target type,
106      *  unless it already has precisely that type.
107      *  @param tree    The expression tree.
108      *  @param target  The target type.
109      */
cast(JCExpression tree, Type target)110     JCExpression cast(JCExpression tree, Type target) {
111         int oldpos = make.pos;
112         make.at(tree.pos);
113         if (!types.isSameType(tree.type, target)) {
114             if (!resolve.isAccessible(env, target.tsym))
115                 resolve.logAccessErrorInternal(env, tree, target);
116             tree = make.TypeCast(make.Type(target), tree).setType(target);
117         }
118         make.pos = oldpos;
119         return tree;
120     }
121 
122     /** Construct an attributed tree to coerce an expression to some erased
123      *  target type, unless the expression is already assignable to that type.
124      *  If target type is a constant type, use its base type instead.
125      *  @param tree    The expression tree.
126      *  @param target  The target type.
127      */
coerce(Env<AttrContext> env, JCExpression tree, Type target)128     public JCExpression coerce(Env<AttrContext> env, JCExpression tree, Type target) {
129         Env<AttrContext> prevEnv = this.env;
130         try {
131             this.env = env;
132             return coerce(tree, target);
133         }
134         finally {
135             this.env = prevEnv;
136         }
137     }
coerce(JCExpression tree, Type target)138     JCExpression coerce(JCExpression tree, Type target) {
139         Type btarget = target.baseType();
140         if (tree.type.isPrimitive() == target.isPrimitive()) {
141             return types.isAssignable(tree.type, btarget, types.noWarnings)
142                 ? tree
143                 : cast(tree, btarget);
144         }
145         return tree;
146     }
147 
148     /** Given an erased reference type, assume this type as the tree's type.
149      *  Then, coerce to some given target type unless target type is null.
150      *  This operation is used in situations like the following:
151      *
152      *  <pre>{@code
153      *  class Cell<A> { A value; }
154      *  ...
155      *  Cell<Integer> cell;
156      *  Integer x = cell.value;
157      *  }</pre>
158      *
159      *  Since the erasure of Cell.value is Object, but the type
160      *  of cell.value in the assignment is Integer, we need to
161      *  adjust the original type of cell.value to Object, and insert
162      *  a cast to Integer. That is, the last assignment becomes:
163      *
164      *  <pre>{@code
165      *  Integer x = (Integer)cell.value;
166      *  }</pre>
167      *
168      *  @param tree       The expression tree whose type might need adjustment.
169      *  @param erasedType The expression's type after erasure.
170      *  @param target     The target type, which is usually the erasure of the
171      *                    expression's original type.
172      */
retype(JCExpression tree, Type erasedType, Type target)173     JCExpression retype(JCExpression tree, Type erasedType, Type target) {
174 //      System.err.println("retype " + tree + " to " + erasedType);//DEBUG
175         if (!erasedType.isPrimitive()) {
176             if (target != null && target.isPrimitive()) {
177                 target = erasure(tree.type);
178             }
179             tree.type = erasedType;
180             if (target != null) {
181                 return coerce(tree, target);
182             }
183         }
184         return tree;
185     }
186 
187     /** Translate method argument list, casting each argument
188      *  to its corresponding type in a list of target types.
189      *  @param _args            The method argument list.
190      *  @param parameters       The list of target types.
191      *  @param varargsElement   The erasure of the varargs element type,
192      *  or null if translating a non-varargs invocation
193      */
translateArgs(List<T> _args, List<Type> parameters, Type varargsElement)194     <T extends JCTree> List<T> translateArgs(List<T> _args,
195                                            List<Type> parameters,
196                                            Type varargsElement) {
197         if (parameters.isEmpty()) return _args;
198         List<T> args = _args;
199         while (parameters.tail.nonEmpty()) {
200             args.head = translate(args.head, parameters.head);
201             args = args.tail;
202             parameters = parameters.tail;
203         }
204         Type parameter = parameters.head;
205         Assert.check(varargsElement != null || args.length() == 1);
206         if (varargsElement != null) {
207             while (args.nonEmpty()) {
208                 args.head = translate(args.head, varargsElement);
209                 args = args.tail;
210             }
211         } else {
212             args.head = translate(args.head, parameter);
213         }
214         return _args;
215     }
216 
translateArgs(List<T> _args, List<Type> parameters, Type varargsElement, Env<AttrContext> localEnv)217     public <T extends JCTree> List<T> translateArgs(List<T> _args,
218                                            List<Type> parameters,
219                                            Type varargsElement,
220                                            Env<AttrContext> localEnv) {
221         Env<AttrContext> prevEnv = env;
222         try {
223             env = localEnv;
224             return translateArgs(_args, parameters, varargsElement);
225         }
226         finally {
227             env = prevEnv;
228         }
229     }
230 
231     /** Add a bridge definition and enter corresponding method symbol in
232      *  local scope of origin.
233      *
234      *  @param pos     The source code position to be used for the definition.
235      *  @param meth    The method for which a bridge needs to be added
236      *  @param impl    That method's implementation (possibly the method itself)
237      *  @param origin  The class to which the bridge will be added
238      *  @param bridges The list buffer to which the bridge will be added
239      */
addBridge(DiagnosticPosition pos, MethodSymbol meth, MethodSymbol impl, ClassSymbol origin, ListBuffer<JCTree> bridges)240     void addBridge(DiagnosticPosition pos,
241                    MethodSymbol meth,
242                    MethodSymbol impl,
243                    ClassSymbol origin,
244                    ListBuffer<JCTree> bridges) {
245         make.at(pos);
246         Type implTypeErasure = erasure(impl.type);
247 
248         // Create a bridge method symbol and a bridge definition without a body.
249         Type bridgeType = meth.erasure(types);
250         long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE |
251                 (origin.isInterface() ? DEFAULT : 0);
252         MethodSymbol bridge = new MethodSymbol(flags,
253                                                meth.name,
254                                                bridgeType,
255                                                origin);
256         /* once JDK-6996415 is solved it should be checked if this approach can
257          * be applied to method addOverrideBridgesIfNeeded
258          */
259         bridge.params = createBridgeParams(impl, bridge, bridgeType);
260         bridge.setAttributes(impl);
261 
262         JCMethodDecl md = make.MethodDef(bridge, null);
263 
264         // The bridge calls this.impl(..), if we have an implementation
265         // in the current class, super.impl(...) otherwise.
266         JCExpression receiver = (impl.owner == origin)
267             ? make.This(origin.erasure(types))
268             : make.Super(types.supertype(origin.type).tsym.erasure(types), origin);
269 
270         // The type returned from the original method.
271         Type calltype = implTypeErasure.getReturnType();
272 
273         // Construct a call of  this.impl(params), or super.impl(params),
274         // casting params and possibly results as needed.
275         JCExpression call =
276             make.Apply(
277                        null,
278                        make.Select(receiver, impl).setType(calltype),
279                        translateArgs(make.Idents(md.params), implTypeErasure.getParameterTypes(), null))
280             .setType(calltype);
281         JCStatement stat = (implTypeErasure.getReturnType().hasTag(VOID))
282             ? make.Exec(call)
283             : make.Return(coerce(call, bridgeType.getReturnType()));
284         md.body = make.Block(0, List.of(stat));
285 
286         // Add bridge to `bridges' buffer
287         bridges.append(md);
288 
289         // Add bridge to scope of enclosing class and keep track of the bridge span.
290         origin.members().enter(bridge);
291     }
292 
createBridgeParams(MethodSymbol impl, MethodSymbol bridge, Type bridgeType)293     private List<VarSymbol> createBridgeParams(MethodSymbol impl, MethodSymbol bridge,
294             Type bridgeType) {
295         List<VarSymbol> bridgeParams = null;
296         if (impl.params != null) {
297             bridgeParams = List.nil();
298             List<VarSymbol> implParams = impl.params;
299             Type.MethodType mType = (Type.MethodType)bridgeType;
300             List<Type> argTypes = mType.argtypes;
301             while (implParams.nonEmpty() && argTypes.nonEmpty()) {
302                 VarSymbol param = new VarSymbol(implParams.head.flags() | SYNTHETIC | PARAMETER,
303                         implParams.head.name, argTypes.head, bridge);
304                 param.setAttributes(implParams.head);
305                 bridgeParams = bridgeParams.append(param);
306                 implParams = implParams.tail;
307                 argTypes = argTypes.tail;
308             }
309         }
310         return bridgeParams;
311     }
312 
313     /** Add bridge if given symbol is a non-private, non-static member
314      *  of the given class, which is either defined in the class or non-final
315      *  inherited, and one of the two following conditions holds:
316      *  1. The method's type changes in the given class, as compared to the
317      *     class where the symbol was defined, (in this case
318      *     we have extended a parameterized class with non-trivial parameters).
319      *  2. The method has an implementation with a different erased return type.
320      *     (in this case we have used co-variant returns).
321      *  If a bridge already exists in some other class, no new bridge is added.
322      *  Instead, it is checked that the bridge symbol overrides the method symbol.
323      *  (Spec ???).
324      *  todo: what about bridges for privates???
325      *
326      *  @param pos     The source code position to be used for the definition.
327      *  @param sym     The symbol for which a bridge might have to be added.
328      *  @param origin  The class in which the bridge would go.
329      *  @param bridges The list buffer to which the bridge would be added.
330      */
addBridgeIfNeeded(DiagnosticPosition pos, Symbol sym, ClassSymbol origin, ListBuffer<JCTree> bridges)331     void addBridgeIfNeeded(DiagnosticPosition pos,
332                            Symbol sym,
333                            ClassSymbol origin,
334                            ListBuffer<JCTree> bridges) {
335         if (sym.kind == MTH &&
336                 sym.name != names.init &&
337                 (sym.flags() & (PRIVATE | STATIC)) == 0 &&
338                 (sym.flags() & SYNTHETIC) != SYNTHETIC &&
339                 sym.isMemberOf(origin, types)) {
340             MethodSymbol meth = (MethodSymbol)sym;
341             MethodSymbol bridge = meth.binaryImplementation(origin, types);
342             MethodSymbol impl = meth.implementation(origin, types, true);
343             if (bridge == null ||
344                 bridge == meth ||
345                 (impl != null && !bridge.owner.isSubClass(impl.owner, types))) {
346                 // No bridge was added yet.
347                 if (impl != null && bridge != impl && isBridgeNeeded(meth, impl, origin.type)) {
348                     addBridge(pos, meth, impl, origin, bridges);
349                 } else if (impl == meth
350                            && impl.owner != origin
351                            && (impl.flags() & FINAL) == 0
352                            && (meth.flags() & (ABSTRACT|PUBLIC)) == PUBLIC
353                            && (origin.flags() & PUBLIC) > (impl.owner.flags() & PUBLIC)) {
354                     // this is to work around a horrible but permanent
355                     // reflection design error.
356                     addBridge(pos, meth, impl, origin, bridges);
357                 }
358             }
359         }
360     }
361     // where
362 
363         /**
364          * @param method The symbol for which a bridge might have to be added
365          * @param impl The implementation of method
366          * @param dest The type in which the bridge would go
367          */
isBridgeNeeded(MethodSymbol method, MethodSymbol impl, Type dest)368         private boolean isBridgeNeeded(MethodSymbol method,
369                                        MethodSymbol impl,
370                                        Type dest) {
371             if (impl != method) {
372                 // If either method or impl have different erasures as
373                 // members of dest, a bridge is needed.
374                 Type method_erasure = method.erasure(types);
375                 if (!isSameMemberWhenErased(dest, method, method_erasure))
376                     return true;
377                 Type impl_erasure = impl.erasure(types);
378                 if (!isSameMemberWhenErased(dest, impl, impl_erasure))
379                     return true;
380 
381                 /* Bottom line: A bridge is needed if the erasure of the implementation
382                    is different from that of the method that it overrides.
383                 */
384                 return !types.isSameType(impl_erasure, method_erasure);
385             } else {
386                // method and impl are the same...
387                 if ((method.flags() & ABSTRACT) != 0) {
388                     // ...and abstract so a bridge is not needed.
389                     // Concrete subclasses will bridge as needed.
390                     return false;
391                 }
392 
393                 // The erasure of the return type is always the same
394                 // for the same symbol.  Reducing the three tests in
395                 // the other branch to just one:
396                 return !isSameMemberWhenErased(dest, method, method.erasure(types));
397             }
398         }
399         /**
400          * Lookup the method as a member of the type.  Compare the
401          * erasures.
402          * @param type the class where to look for the method
403          * @param method the method to look for in class
404          * @param erasure the erasure of method
405          */
isSameMemberWhenErased(Type type, MethodSymbol method, Type erasure)406         private boolean isSameMemberWhenErased(Type type,
407                                                MethodSymbol method,
408                                                Type erasure) {
409             return types.isSameType(erasure(types.memberType(type, method)),
410                                     erasure);
411         }
412 
addBridges(DiagnosticPosition pos, TypeSymbol i, ClassSymbol origin, ListBuffer<JCTree> bridges)413     void addBridges(DiagnosticPosition pos,
414                     TypeSymbol i,
415                     ClassSymbol origin,
416                     ListBuffer<JCTree> bridges) {
417         for (Symbol sym : i.members().getSymbols(NON_RECURSIVE))
418             addBridgeIfNeeded(pos, sym, origin, bridges);
419         for (List<Type> l = types.interfaces(i.type); l.nonEmpty(); l = l.tail)
420             addBridges(pos, l.head.tsym, origin, bridges);
421     }
422 
423     /** Add all necessary bridges to some class appending them to list buffer.
424      *  @param pos     The source code position to be used for the bridges.
425      *  @param origin  The class in which the bridges go.
426      *  @param bridges The list buffer to which the bridges are added.
427      */
addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges)428     void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
429         Type st = types.supertype(origin.type);
430         while (st.hasTag(CLASS)) {
431 //          if (isSpecialization(st))
432             addBridges(pos, st.tsym, origin, bridges);
433             st = types.supertype(st);
434         }
435         for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
436 //          if (isSpecialization(l.head))
437             addBridges(pos, l.head.tsym, origin, bridges);
438     }
439 
440 /* ************************************************************************
441  * Visitor methods
442  *************************************************************************/
443 
444     /** Visitor argument: proto-type.
445      */
446     private Type pt;
447 
448     /** Visitor method: perform a type translation on tree.
449      */
translate(T tree, Type pt)450     public <T extends JCTree> T translate(T tree, Type pt) {
451         Type prevPt = this.pt;
452         try {
453             this.pt = pt;
454             return translate(tree);
455         } finally {
456             this.pt = prevPt;
457         }
458     }
459 
460     /** Visitor method: perform a type translation on list of trees.
461      */
translate(List<T> trees, Type pt)462     public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
463         Type prevPt = this.pt;
464         List<T> res;
465         try {
466             this.pt = pt;
467             res = translate(trees);
468         } finally {
469             this.pt = prevPt;
470         }
471         return res;
472     }
473 
visitClassDef(JCClassDecl tree)474     public void visitClassDef(JCClassDecl tree) {
475         translateClass(tree.sym);
476         result = tree;
477     }
478 
479     Type returnType = null;
visitMethodDef(JCMethodDecl tree)480     public void visitMethodDef(JCMethodDecl tree) {
481         Type prevRetType = returnType;
482         try {
483             returnType = erasure(tree.type).getReturnType();
484             tree.restype = translate(tree.restype, null);
485             tree.typarams = List.nil();
486             tree.params = translateVarDefs(tree.params);
487             tree.recvparam = translate(tree.recvparam, null);
488             tree.thrown = translate(tree.thrown, null);
489             tree.body = translate(tree.body, tree.sym.erasure(types).getReturnType());
490             tree.type = erasure(tree.type);
491             result = tree;
492         } finally {
493             returnType = prevRetType;
494         }
495     }
496 
visitVarDef(JCVariableDecl tree)497     public void visitVarDef(JCVariableDecl tree) {
498         tree.vartype = translate(tree.vartype, null);
499         tree.init = translate(tree.init, tree.sym.erasure(types));
500         tree.type = erasure(tree.type);
501         result = tree;
502     }
503 
visitDoLoop(JCDoWhileLoop tree)504     public void visitDoLoop(JCDoWhileLoop tree) {
505         tree.body = translate(tree.body);
506         tree.cond = translate(tree.cond, syms.booleanType);
507         result = tree;
508     }
509 
visitWhileLoop(JCWhileLoop tree)510     public void visitWhileLoop(JCWhileLoop tree) {
511         tree.cond = translate(tree.cond, syms.booleanType);
512         tree.body = translate(tree.body);
513         result = tree;
514     }
515 
visitForLoop(JCForLoop tree)516     public void visitForLoop(JCForLoop tree) {
517         tree.init = translate(tree.init, null);
518         if (tree.cond != null)
519             tree.cond = translate(tree.cond, syms.booleanType);
520         tree.step = translate(tree.step, null);
521         tree.body = translate(tree.body);
522         result = tree;
523     }
524 
visitForeachLoop(JCEnhancedForLoop tree)525     public void visitForeachLoop(JCEnhancedForLoop tree) {
526         tree.var = translate(tree.var, null);
527         Type iterableType = tree.expr.type;
528         tree.expr = translate(tree.expr, erasure(tree.expr.type));
529         if (types.elemtype(tree.expr.type) == null)
530             tree.expr.type = iterableType; // preserve type for Lower
531         tree.body = translate(tree.body);
532         result = tree;
533     }
534 
visitLambda(JCLambda tree)535     public void visitLambda(JCLambda tree) {
536         Type prevRetType = returnType;
537         try {
538             returnType = erasure(tree.getDescriptorType(types)).getReturnType();
539             tree.params = translate(tree.params);
540             tree.body = translate(tree.body, tree.body.type == null || returnType.hasTag(VOID) ? null : returnType);
541             if (!tree.type.isIntersection()) {
542                 tree.type = erasure(tree.type);
543             } else {
544                 tree.type = types.erasure(types.findDescriptorSymbol(tree.type.tsym).owner.type);
545             }
546             result = tree;
547         }
548         finally {
549             returnType = prevRetType;
550         }
551     }
552 
visitSwitch(JCSwitch tree)553     public void visitSwitch(JCSwitch tree) {
554         Type selsuper = types.supertype(tree.selector.type);
555         boolean enumSwitch = selsuper != null &&
556             selsuper.tsym == syms.enumSym;
557         Type target = enumSwitch ? erasure(tree.selector.type) : syms.intType;
558         tree.selector = translate(tree.selector, target);
559         tree.cases = translateCases(tree.cases);
560         result = tree;
561     }
562 
visitCase(JCCase tree)563     public void visitCase(JCCase tree) {
564         tree.pat = translate(tree.pat, null);
565         tree.stats = translate(tree.stats);
566         result = tree;
567     }
568 
visitSynchronized(JCSynchronized tree)569     public void visitSynchronized(JCSynchronized tree) {
570         tree.lock = translate(tree.lock, erasure(tree.lock.type));
571         tree.body = translate(tree.body);
572         result = tree;
573     }
574 
visitTry(JCTry tree)575     public void visitTry(JCTry tree) {
576         tree.resources = translate(tree.resources, syms.autoCloseableType);
577         tree.body = translate(tree.body);
578         tree.catchers = translateCatchers(tree.catchers);
579         tree.finalizer = translate(tree.finalizer);
580         result = tree;
581     }
582 
visitConditional(JCConditional tree)583     public void visitConditional(JCConditional tree) {
584         tree.cond = translate(tree.cond, syms.booleanType);
585         tree.truepart = translate(tree.truepart, erasure(tree.type));
586         tree.falsepart = translate(tree.falsepart, erasure(tree.type));
587         tree.type = erasure(tree.type);
588         result = retype(tree, tree.type, pt);
589     }
590 
visitIf(JCIf tree)591    public void visitIf(JCIf tree) {
592         tree.cond = translate(tree.cond, syms.booleanType);
593         tree.thenpart = translate(tree.thenpart);
594         tree.elsepart = translate(tree.elsepart);
595         result = tree;
596     }
597 
visitExec(JCExpressionStatement tree)598     public void visitExec(JCExpressionStatement tree) {
599         tree.expr = translate(tree.expr, null);
600         result = tree;
601     }
602 
visitReturn(JCReturn tree)603     public void visitReturn(JCReturn tree) {
604         if (!returnType.hasTag(VOID))
605             tree.expr = translate(tree.expr, returnType);
606         result = tree;
607     }
608 
visitThrow(JCThrow tree)609     public void visitThrow(JCThrow tree) {
610         tree.expr = translate(tree.expr, erasure(tree.expr.type));
611         result = tree;
612     }
613 
visitAssert(JCAssert tree)614     public void visitAssert(JCAssert tree) {
615         tree.cond = translate(tree.cond, syms.booleanType);
616         if (tree.detail != null)
617             tree.detail = translate(tree.detail, erasure(tree.detail.type));
618         result = tree;
619     }
620 
visitApply(JCMethodInvocation tree)621     public void visitApply(JCMethodInvocation tree) {
622         tree.meth = translate(tree.meth, null);
623         Symbol meth = TreeInfo.symbol(tree.meth);
624         Type mt = meth.erasure(types);
625         boolean useInstantiatedPtArgs =
626                 allowGraphInference && !types.isSignaturePolymorphic((MethodSymbol)meth.baseSymbol());
627         List<Type> argtypes = useInstantiatedPtArgs ?
628                 tree.meth.type.getParameterTypes() :
629                 mt.getParameterTypes();
630         if (meth.name == names.init && meth.owner == syms.enumSym)
631             argtypes = argtypes.tail.tail;
632         if (tree.varargsElement != null)
633             tree.varargsElement = types.erasure(tree.varargsElement);
634         else
635             if (tree.args.length() != argtypes.length()) {
636                 Assert.error(String.format("Incorrect number of arguments; expected %d, found %d",
637                         tree.args.length(), argtypes.length()));
638             }
639         tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
640 
641         tree.type = types.erasure(tree.type);
642         // Insert casts of method invocation results as needed.
643         result = retype(tree, mt.getReturnType(), pt);
644     }
645 
visitNewClass(JCNewClass tree)646     public void visitNewClass(JCNewClass tree) {
647         if (tree.encl != null) {
648             if (tree.def == null) {
649                 tree.encl = translate(tree.encl, erasure(tree.encl.type));
650             } else {
651                 tree.args = tree.args.prepend(attr.makeNullCheck(tree.encl));
652                 tree.encl = null;
653             }
654         }
655 
656         Type erasedConstructorType = tree.constructorType != null ?
657                 erasure(tree.constructorType) :
658                 null;
659 
660         List<Type> argtypes = erasedConstructorType != null && allowGraphInference ?
661                 erasedConstructorType.getParameterTypes() :
662                 tree.constructor.erasure(types).getParameterTypes();
663 
664         tree.clazz = translate(tree.clazz, null);
665         if (tree.varargsElement != null)
666             tree.varargsElement = types.erasure(tree.varargsElement);
667         tree.args = translateArgs(
668             tree.args, argtypes, tree.varargsElement);
669         tree.def = translate(tree.def, null);
670         if (erasedConstructorType != null)
671             tree.constructorType = erasedConstructorType;
672         tree.type = erasure(tree.type);
673         result = tree;
674     }
675 
visitNewArray(JCNewArray tree)676     public void visitNewArray(JCNewArray tree) {
677         tree.elemtype = translate(tree.elemtype, null);
678         translate(tree.dims, syms.intType);
679         if (tree.type != null) {
680             tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
681             tree.type = erasure(tree.type);
682         } else {
683             tree.elems = translate(tree.elems, null);
684         }
685 
686         result = tree;
687     }
688 
visitParens(JCParens tree)689     public void visitParens(JCParens tree) {
690         tree.expr = translate(tree.expr, pt);
691         tree.type = erasure(tree.expr.type);
692         result = tree;
693     }
694 
visitAssign(JCAssign tree)695     public void visitAssign(JCAssign tree) {
696         tree.lhs = translate(tree.lhs, null);
697         tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
698         tree.type = erasure(tree.lhs.type);
699         result = retype(tree, tree.type, pt);
700     }
701 
visitAssignop(JCAssignOp tree)702     public void visitAssignop(JCAssignOp tree) {
703         tree.lhs = translate(tree.lhs, null);
704         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
705         tree.type = erasure(tree.type);
706         result = tree;
707     }
708 
visitUnary(JCUnary tree)709     public void visitUnary(JCUnary tree) {
710         tree.arg = translate(tree.arg, (tree.getTag() == Tag.NULLCHK)
711             ? tree.type
712             : tree.operator.type.getParameterTypes().head);
713         result = tree;
714     }
715 
visitBinary(JCBinary tree)716     public void visitBinary(JCBinary tree) {
717         tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
718         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
719         result = tree;
720     }
721 
visitAnnotatedType(JCAnnotatedType tree)722     public void visitAnnotatedType(JCAnnotatedType tree) {
723         // For now, we need to keep the annotations in the tree because of the current
724         // MultiCatch implementation wrt type annotations
725         List<TypeCompound> mirrors = annotate.fromAnnotations(tree.annotations);
726         tree.underlyingType = translate(tree.underlyingType);
727         tree.type = tree.underlyingType.type.annotatedType(mirrors);
728         result = tree;
729     }
730 
visitTypeCast(JCTypeCast tree)731     public void visitTypeCast(JCTypeCast tree) {
732         tree.clazz = translate(tree.clazz, null);
733         Type originalTarget = tree.type;
734         tree.type = erasure(tree.type);
735         JCExpression newExpression = translate(tree.expr, tree.type);
736         if (newExpression != tree.expr) {
737             JCTypeCast typeCast = newExpression.hasTag(Tag.TYPECAST)
738                 ? (JCTypeCast) newExpression
739                 : null;
740             tree.expr = typeCast != null && types.isSameType(typeCast.type, originalTarget)
741                 ? typeCast.expr
742                 : newExpression;
743         }
744         if (originalTarget.isIntersection()) {
745             Type.IntersectionClassType ict = (Type.IntersectionClassType)originalTarget;
746             for (Type c : ict.getExplicitComponents()) {
747                 Type ec = erasure(c);
748                 if (!types.isSameType(ec, tree.type)) {
749                     tree.expr = coerce(tree.expr, ec);
750                 }
751             }
752         }
753         result = tree;
754     }
755 
visitTypeTest(JCInstanceOf tree)756     public void visitTypeTest(JCInstanceOf tree) {
757         tree.expr = translate(tree.expr, null);
758         tree.clazz = translate(tree.clazz, null);
759         result = tree;
760     }
761 
visitIndexed(JCArrayAccess tree)762     public void visitIndexed(JCArrayAccess tree) {
763         tree.indexed = translate(tree.indexed, erasure(tree.indexed.type));
764         tree.index = translate(tree.index, syms.intType);
765 
766         // Insert casts of indexed expressions as needed.
767         result = retype(tree, types.elemtype(tree.indexed.type), pt);
768     }
769 
770     // There ought to be nothing to rewrite here;
771     // we don't generate code.
visitAnnotation(JCAnnotation tree)772     public void visitAnnotation(JCAnnotation tree) {
773         result = tree;
774     }
775 
visitIdent(JCIdent tree)776     public void visitIdent(JCIdent tree) {
777         Type et = tree.sym.erasure(types);
778 
779         // Map type variables to their bounds.
780         if (tree.sym.kind == TYP && tree.sym.type.hasTag(TYPEVAR)) {
781             result = make.at(tree.pos).Type(et);
782         } else
783         // Map constants expressions to themselves.
784         if (tree.type.constValue() != null) {
785             result = tree;
786         }
787         // Insert casts of variable uses as needed.
788         else if (tree.sym.kind == VAR) {
789             result = retype(tree, et, pt);
790         }
791         else {
792             tree.type = erasure(tree.type);
793             result = tree;
794         }
795     }
796 
visitSelect(JCFieldAccess tree)797     public void visitSelect(JCFieldAccess tree) {
798         Type t = types.skipTypeVars(tree.selected.type, false);
799         if (t.isCompound()) {
800             tree.selected = coerce(
801                 translate(tree.selected, erasure(tree.selected.type)),
802                 erasure(tree.sym.owner.type));
803         } else
804             tree.selected = translate(tree.selected, erasure(t));
805 
806         // Map constants expressions to themselves.
807         if (tree.type.constValue() != null) {
808             result = tree;
809         }
810         // Insert casts of variable uses as needed.
811         else if (tree.sym.kind == VAR) {
812             result = retype(tree, tree.sym.erasure(types), pt);
813         }
814         else {
815             tree.type = erasure(tree.type);
816             result = tree;
817         }
818     }
819 
visitReference(JCMemberReference tree)820     public void visitReference(JCMemberReference tree) {
821         Type t = types.skipTypeVars(tree.expr.type, false);
822         Type receiverTarget = t.isCompound() ? erasure(tree.sym.owner.type) : erasure(t);
823         if (tree.kind == ReferenceKind.UNBOUND) {
824             tree.expr = make.Type(receiverTarget);
825         } else {
826             tree.expr = translate(tree.expr, receiverTarget);
827         }
828         if (!tree.type.isIntersection()) {
829             tree.type = erasure(tree.type);
830         } else {
831             tree.type = types.erasure(types.findDescriptorSymbol(tree.type.tsym).owner.type);
832         }
833         if (tree.varargsElement != null)
834             tree.varargsElement = erasure(tree.varargsElement);
835         result = tree;
836     }
837 
visitTypeArray(JCArrayTypeTree tree)838     public void visitTypeArray(JCArrayTypeTree tree) {
839         tree.elemtype = translate(tree.elemtype, null);
840         tree.type = erasure(tree.type);
841         result = tree;
842     }
843 
844     /** Visitor method for parameterized types.
845      */
visitTypeApply(JCTypeApply tree)846     public void visitTypeApply(JCTypeApply tree) {
847         JCTree clazz = translate(tree.clazz, null);
848         result = clazz;
849     }
850 
visitTypeIntersection(JCTypeIntersection tree)851     public void visitTypeIntersection(JCTypeIntersection tree) {
852         tree.bounds = translate(tree.bounds, null);
853         tree.type = erasure(tree.type);
854         result = tree;
855     }
856 
857 /**************************************************************************
858  * utility methods
859  *************************************************************************/
860 
erasure(Type t)861     private Type erasure(Type t) {
862         return types.erasure(t);
863     }
864 
865 /**************************************************************************
866  * main method
867  *************************************************************************/
868 
869     private Env<AttrContext> env;
870 
871     private static final String statePreviousToFlowAssertMsg =
872             "The current compile state [%s] of class %s is previous to FLOW";
873 
translateClass(ClassSymbol c)874     void translateClass(ClassSymbol c) {
875         Type st = types.supertype(c.type);
876         // process superclass before derived
877         if (st.hasTag(CLASS)) {
878             translateClass((ClassSymbol)st.tsym);
879         }
880 
881         Env<AttrContext> myEnv = enter.getEnv(c);
882         if (myEnv == null || (c.flags_field & TYPE_TRANSLATED) != 0) {
883             return;
884         }
885         c.flags_field |= TYPE_TRANSLATED;
886 
887         /*  The two assertions below are set for early detection of any attempt
888          *  to translate a class that:
889          *
890          *  1) has no compile state being it the most outer class.
891          *     We accept this condition for inner classes.
892          *
893          *  2) has a compile state which is previous to Flow state.
894          */
895         boolean envHasCompState = compileStates.get(myEnv) != null;
896         if (!envHasCompState && c.outermostClass() == c) {
897             Assert.error("No info for outermost class: " + myEnv.enclClass.sym);
898         }
899 
900         if (envHasCompState &&
901                 CompileState.FLOW.isAfter(compileStates.get(myEnv))) {
902             Assert.error(String.format(statePreviousToFlowAssertMsg,
903                     compileStates.get(myEnv), myEnv.enclClass.sym));
904         }
905 
906         Env<AttrContext> oldEnv = env;
907         try {
908             env = myEnv;
909             // class has not been translated yet
910 
911             TreeMaker savedMake = make;
912             Type savedPt = pt;
913             make = make.forToplevel(env.toplevel);
914             pt = null;
915             try {
916                 JCClassDecl tree = (JCClassDecl) env.tree;
917                 tree.typarams = List.nil();
918                 super.visitClassDef(tree);
919                 make.at(tree.pos);
920                 ListBuffer<JCTree> bridges = new ListBuffer<>();
921                 if (allowInterfaceBridges || (tree.sym.flags() & INTERFACE) == 0) {
922                     addBridges(tree.pos(), c, bridges);
923                 }
924                 tree.defs = bridges.toList().prependList(tree.defs);
925                 tree.type = erasure(tree.type);
926             } finally {
927                 make = savedMake;
928                 pt = savedPt;
929             }
930         } finally {
931             env = oldEnv;
932         }
933     }
934 
935     /** Translate a toplevel class definition.
936      *  @param cdef    The definition to be translated.
937      */
translateTopLevelClass(JCTree cdef, TreeMaker make)938     public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
939         // note that this method does NOT support recursion.
940         this.make = make;
941         pt = null;
942         return translate(cdef, null);
943     }
944 }
945