Fri, 31 May 2013 10:04:59 +0100
7179353: try-with-resources fails to compile with generic exception parameters
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2013, 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 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
30 import com.sun.tools.javac.code.*;
31 import com.sun.tools.javac.code.Symbol.*;
32 import com.sun.tools.javac.tree.*;
33 import com.sun.tools.javac.tree.JCTree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
38 import static com.sun.tools.javac.code.Flags.*;
39 import static com.sun.tools.javac.code.Kinds.*;
40 import static com.sun.tools.javac.code.TypeTag.CLASS;
41 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
42 import static com.sun.tools.javac.code.TypeTag.VOID;
43 import static com.sun.tools.javac.comp.CompileStates.CompileState;
45 /** This pass translates Generic Java to conventional Java.
46 *
47 * <p><b>This is NOT part of any supported API.
48 * If you write code that depends on this, you do so at your own risk.
49 * This code and its internal interfaces are subject to change or
50 * deletion without notice.</b>
51 */
52 public class TransTypes extends TreeTranslator {
53 /** The context key for the TransTypes phase. */
54 protected static final Context.Key<TransTypes> transTypesKey =
55 new Context.Key<TransTypes>();
57 /** Get the instance for this context. */
58 public static TransTypes instance(Context context) {
59 TransTypes instance = context.get(transTypesKey);
60 if (instance == null)
61 instance = new TransTypes(context);
62 return instance;
63 }
65 private Names names;
66 private Log log;
67 private Symtab syms;
68 private TreeMaker make;
69 private Enter enter;
70 private boolean allowEnums;
71 private Types types;
72 private final Resolve resolve;
74 /**
75 * Flag to indicate whether or not to generate bridge methods.
76 * For pre-Tiger source there is no need for bridge methods, so it
77 * can be skipped to get better performance for -source 1.4 etc.
78 */
79 private final boolean addBridges;
81 private final CompileStates compileStates;
83 protected TransTypes(Context context) {
84 context.put(transTypesKey, this);
85 compileStates = CompileStates.instance(context);
86 names = Names.instance(context);
87 log = Log.instance(context);
88 syms = Symtab.instance(context);
89 enter = Enter.instance(context);
90 overridden = new HashMap<MethodSymbol,MethodSymbol>();
91 Source source = Source.instance(context);
92 allowEnums = source.allowEnums();
93 addBridges = source.addBridges();
94 types = Types.instance(context);
95 make = TreeMaker.instance(context);
96 resolve = Resolve.instance(context);
97 }
99 /** A hashtable mapping bridge methods to the methods they override after
100 * type erasure.
101 */
102 Map<MethodSymbol,MethodSymbol> overridden;
104 /** Construct an attributed tree for a cast of expression to target type,
105 * unless it already has precisely that type.
106 * @param tree The expression tree.
107 * @param target The target type.
108 */
109 JCExpression cast(JCExpression tree, Type target) {
110 int oldpos = make.pos;
111 make.at(tree.pos);
112 if (!types.isSameType(tree.type, target)) {
113 if (!resolve.isAccessible(env, target.tsym))
114 resolve.logAccessErrorInternal(env, tree, target);
115 tree = make.TypeCast(make.Type(target), tree).setType(target);
116 }
117 make.pos = oldpos;
118 return tree;
119 }
121 /** Construct an attributed tree to coerce an expression to some erased
122 * target type, unless the expression is already assignable to that type.
123 * If target type is a constant type, use its base type instead.
124 * @param tree The expression tree.
125 * @param target The target type.
126 */
127 public JCExpression coerce(Env<AttrContext> env, JCExpression tree, Type target) {
128 Env<AttrContext> prevEnv = this.env;
129 try {
130 this.env = env;
131 return coerce(tree, target);
132 }
133 finally {
134 this.env = prevEnv;
135 }
136 }
137 JCExpression coerce(JCExpression tree, Type target) {
138 Type btarget = target.baseType();
139 if (tree.type.isPrimitive() == target.isPrimitive()) {
140 return types.isAssignable(tree.type, btarget, types.noWarnings)
141 ? tree
142 : cast(tree, btarget);
143 }
144 return tree;
145 }
147 /** Given an erased reference type, assume this type as the tree's type.
148 * Then, coerce to some given target type unless target type is null.
149 * This operation is used in situations like the following:
150 *
151 * <pre>{@code
152 * class Cell<A> { A value; }
153 * ...
154 * Cell<Integer> cell;
155 * Integer x = cell.value;
156 * }</pre>
157 *
158 * Since the erasure of Cell.value is Object, but the type
159 * of cell.value in the assignment is Integer, we need to
160 * adjust the original type of cell.value to Object, and insert
161 * a cast to Integer. That is, the last assignment becomes:
162 *
163 * <pre>{@code
164 * Integer x = (Integer)cell.value;
165 * }</pre>
166 *
167 * @param tree The expression tree whose type might need adjustment.
168 * @param erasedType The expression's type after erasure.
169 * @param target The target type, which is usually the erasure of the
170 * expression's original type.
171 */
172 JCExpression retype(JCExpression tree, Type erasedType, Type target) {
173 // System.err.println("retype " + tree + " to " + erasedType);//DEBUG
174 if (!erasedType.isPrimitive()) {
175 if (target != null && target.isPrimitive()) {
176 target = erasure(tree.type);
177 }
178 tree.type = erasedType;
179 if (target != null) {
180 return coerce(tree, target);
181 }
182 }
183 return tree;
184 }
186 /** Translate method argument list, casting each argument
187 * to its corresponding type in a list of target types.
188 * @param _args The method argument list.
189 * @param parameters The list of target types.
190 * @param varargsElement The erasure of the varargs element type,
191 * or null if translating a non-varargs invocation
192 */
193 <T extends JCTree> List<T> translateArgs(List<T> _args,
194 List<Type> parameters,
195 Type varargsElement) {
196 if (parameters.isEmpty()) return _args;
197 List<T> args = _args;
198 while (parameters.tail.nonEmpty()) {
199 args.head = translate(args.head, parameters.head);
200 args = args.tail;
201 parameters = parameters.tail;
202 }
203 Type parameter = parameters.head;
204 Assert.check(varargsElement != null || args.length() == 1);
205 if (varargsElement != null) {
206 while (args.nonEmpty()) {
207 args.head = translate(args.head, varargsElement);
208 args = args.tail;
209 }
210 } else {
211 args.head = translate(args.head, parameter);
212 }
213 return _args;
214 }
216 public <T extends JCTree> List<T> translateArgs(List<T> _args,
217 List<Type> parameters,
218 Type varargsElement,
219 Env<AttrContext> localEnv) {
220 Env<AttrContext> prevEnv = env;
221 try {
222 env = localEnv;
223 return translateArgs(_args, parameters, varargsElement);
224 }
225 finally {
226 env = prevEnv;
227 }
228 }
230 /** Add a bridge definition and enter corresponding method symbol in
231 * local scope of origin.
232 *
233 * @param pos The source code position to be used for the definition.
234 * @param meth The method for which a bridge needs to be added
235 * @param impl That method's implementation (possibly the method itself)
236 * @param origin The class to which the bridge will be added
237 * @param hypothetical
238 * True if the bridge method is not strictly necessary in the
239 * binary, but is represented in the symbol table to detect
240 * erasure clashes.
241 * @param bridges The list buffer to which the bridge will be added
242 */
243 void addBridge(DiagnosticPosition pos,
244 MethodSymbol meth,
245 MethodSymbol impl,
246 ClassSymbol origin,
247 boolean hypothetical,
248 ListBuffer<JCTree> bridges) {
249 make.at(pos);
250 Type origType = types.memberType(origin.type, meth);
251 Type origErasure = erasure(origType);
253 // Create a bridge method symbol and a bridge definition without a body.
254 Type bridgeType = meth.erasure(types);
255 long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE;
256 if (hypothetical) flags |= HYPOTHETICAL;
257 MethodSymbol bridge = new MethodSymbol(flags,
258 meth.name,
259 bridgeType,
260 origin);
261 if (!hypothetical) {
262 JCMethodDecl md = make.MethodDef(bridge, null);
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);
270 // The type returned from the original method.
271 Type calltype = erasure(impl.type.getReturnType());
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), origErasure.getParameterTypes(), null))
280 .setType(calltype);
281 JCStatement stat = (origErasure.getReturnType().hasTag(VOID))
282 ? make.Exec(call)
283 : make.Return(coerce(call, bridgeType.getReturnType()));
284 md.body = make.Block(0, List.of(stat));
286 // Add bridge to `bridges' buffer
287 bridges.append(md);
288 }
290 // Add bridge to scope of enclosing class and `overridden' table.
291 origin.members().enter(bridge);
292 overridden.put(bridge, meth);
293 }
295 /** Add bridge if given symbol is a non-private, non-static member
296 * of the given class, which is either defined in the class or non-final
297 * inherited, and one of the two following conditions holds:
298 * 1. The method's type changes in the given class, as compared to the
299 * class where the symbol was defined, (in this case
300 * we have extended a parameterized class with non-trivial parameters).
301 * 2. The method has an implementation with a different erased return type.
302 * (in this case we have used co-variant returns).
303 * If a bridge already exists in some other class, no new bridge is added.
304 * Instead, it is checked that the bridge symbol overrides the method symbol.
305 * (Spec ???).
306 * todo: what about bridges for privates???
307 *
308 * @param pos The source code position to be used for the definition.
309 * @param sym The symbol for which a bridge might have to be added.
310 * @param origin The class in which the bridge would go.
311 * @param bridges The list buffer to which the bridge would be added.
312 */
313 void addBridgeIfNeeded(DiagnosticPosition pos,
314 Symbol sym,
315 ClassSymbol origin,
316 ListBuffer<JCTree> bridges) {
317 if (sym.kind == MTH &&
318 sym.name != names.init &&
319 (sym.flags() & (PRIVATE | STATIC)) == 0 &&
320 (sym.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC &&
321 sym.isMemberOf(origin, types))
322 {
323 MethodSymbol meth = (MethodSymbol)sym;
324 MethodSymbol bridge = meth.binaryImplementation(origin, types);
325 MethodSymbol impl = meth.implementation(origin, types, true, overrideBridgeFilter);
326 if (bridge == null ||
327 bridge == meth ||
328 (impl != null && !bridge.owner.isSubClass(impl.owner, types))) {
329 // No bridge was added yet.
330 if (impl != null && isBridgeNeeded(meth, impl, origin.type)) {
331 addBridge(pos, meth, impl, origin, bridge==impl, bridges);
332 } else if (impl == meth
333 && impl.owner != origin
334 && (impl.flags() & FINAL) == 0
335 && (meth.flags() & (ABSTRACT|PUBLIC)) == PUBLIC
336 && (origin.flags() & PUBLIC) > (impl.owner.flags() & PUBLIC)) {
337 // this is to work around a horrible but permanent
338 // reflection design error.
339 addBridge(pos, meth, impl, origin, false, bridges);
340 }
341 } else if ((bridge.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) == SYNTHETIC) {
342 MethodSymbol other = overridden.get(bridge);
343 if (other != null && other != meth) {
344 if (impl == null || !impl.overrides(other, origin, types, true)) {
345 // Bridge for other symbol pair was added
346 log.error(pos, "name.clash.same.erasure.no.override",
347 other, other.location(origin.type, types),
348 meth, meth.location(origin.type, types));
349 }
350 }
351 } else if (!bridge.overrides(meth, origin, types, true)) {
352 // Accidental binary override without source override.
353 if (bridge.owner == origin ||
354 types.asSuper(bridge.owner.type, meth.owner) == null)
355 // Don't diagnose the problem if it would already
356 // have been reported in the superclass
357 log.error(pos, "name.clash.same.erasure.no.override",
358 bridge, bridge.location(origin.type, types),
359 meth, meth.location(origin.type, types));
360 }
361 }
362 }
363 // where
364 Filter<Symbol> overrideBridgeFilter = new Filter<Symbol>() {
365 public boolean accepts(Symbol s) {
366 return (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
367 }
368 };
369 /**
370 * @param method The symbol for which a bridge might have to be added
371 * @param impl The implementation of method
372 * @param dest The type in which the bridge would go
373 */
374 private boolean isBridgeNeeded(MethodSymbol method,
375 MethodSymbol impl,
376 Type dest) {
377 if (impl != method) {
378 // If either method or impl have different erasures as
379 // members of dest, a bridge is needed.
380 Type method_erasure = method.erasure(types);
381 if (!isSameMemberWhenErased(dest, method, method_erasure))
382 return true;
383 Type impl_erasure = impl.erasure(types);
384 if (!isSameMemberWhenErased(dest, impl, impl_erasure))
385 return true;
387 // If the erasure of the return type is different, a
388 // bridge is needed.
389 return !types.isSameType(impl_erasure.getReturnType(),
390 method_erasure.getReturnType());
391 } else {
392 // method and impl are the same...
393 if ((method.flags() & ABSTRACT) != 0) {
394 // ...and abstract so a bridge is not needed.
395 // Concrete subclasses will bridge as needed.
396 return false;
397 }
399 // The erasure of the return type is always the same
400 // for the same symbol. Reducing the three tests in
401 // the other branch to just one:
402 return !isSameMemberWhenErased(dest, method, method.erasure(types));
403 }
404 }
405 /**
406 * Lookup the method as a member of the type. Compare the
407 * erasures.
408 * @param type the class where to look for the method
409 * @param method the method to look for in class
410 * @param erasure the erasure of method
411 */
412 private boolean isSameMemberWhenErased(Type type,
413 MethodSymbol method,
414 Type erasure) {
415 return types.isSameType(erasure(types.memberType(type, method)),
416 erasure);
417 }
419 void addBridges(DiagnosticPosition pos,
420 TypeSymbol i,
421 ClassSymbol origin,
422 ListBuffer<JCTree> bridges) {
423 for (Scope.Entry e = i.members().elems; e != null; e = e.sibling)
424 addBridgeIfNeeded(pos, e.sym, origin, bridges);
425 for (List<Type> l = types.interfaces(i.type); l.nonEmpty(); l = l.tail)
426 addBridges(pos, l.head.tsym, origin, bridges);
427 }
429 /** Add all necessary bridges to some class appending them to list buffer.
430 * @param pos The source code position to be used for the bridges.
431 * @param origin The class in which the bridges go.
432 * @param bridges The list buffer to which the bridges are added.
433 */
434 void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
435 Type st = types.supertype(origin.type);
436 while (st.hasTag(CLASS)) {
437 // if (isSpecialization(st))
438 addBridges(pos, st.tsym, origin, bridges);
439 st = types.supertype(st);
440 }
441 for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
442 // if (isSpecialization(l.head))
443 addBridges(pos, l.head.tsym, origin, bridges);
444 }
446 /* ************************************************************************
447 * Visitor methods
448 *************************************************************************/
450 /** Visitor argument: proto-type.
451 */
452 private Type pt;
454 /** Visitor method: perform a type translation on tree.
455 */
456 public <T extends JCTree> T translate(T tree, Type pt) {
457 Type prevPt = this.pt;
458 try {
459 this.pt = pt;
460 return translate(tree);
461 } finally {
462 this.pt = prevPt;
463 }
464 }
466 /** Visitor method: perform a type translation on list of trees.
467 */
468 public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
469 Type prevPt = this.pt;
470 List<T> res;
471 try {
472 this.pt = pt;
473 res = translate(trees);
474 } finally {
475 this.pt = prevPt;
476 }
477 return res;
478 }
480 public void visitClassDef(JCClassDecl tree) {
481 translateClass(tree.sym);
482 result = tree;
483 }
485 JCTree currentMethod = null;
486 public void visitMethodDef(JCMethodDecl tree) {
487 JCTree previousMethod = currentMethod;
488 try {
489 currentMethod = tree;
490 tree.restype = translate(tree.restype, null);
491 tree.typarams = List.nil();
492 tree.params = translateVarDefs(tree.params);
493 tree.recvparam = translate(tree.recvparam, null);
494 tree.thrown = translate(tree.thrown, null);
495 tree.body = translate(tree.body, tree.sym.erasure(types).getReturnType());
496 tree.type = erasure(tree.type);
497 result = tree;
498 } finally {
499 currentMethod = previousMethod;
500 }
502 // Check that we do not introduce a name clash by erasing types.
503 for (Scope.Entry e = tree.sym.owner.members().lookup(tree.name);
504 e.sym != null;
505 e = e.next()) {
506 if (e.sym != tree.sym &&
507 types.isSameType(erasure(e.sym.type), tree.type)) {
508 log.error(tree.pos(),
509 "name.clash.same.erasure", tree.sym,
510 e.sym);
511 return;
512 }
513 }
514 }
516 public void visitVarDef(JCVariableDecl tree) {
517 tree.vartype = translate(tree.vartype, null);
518 tree.init = translate(tree.init, tree.sym.erasure(types));
519 tree.type = erasure(tree.type);
520 result = tree;
521 }
523 public void visitDoLoop(JCDoWhileLoop tree) {
524 tree.body = translate(tree.body);
525 tree.cond = translate(tree.cond, syms.booleanType);
526 result = tree;
527 }
529 public void visitWhileLoop(JCWhileLoop tree) {
530 tree.cond = translate(tree.cond, syms.booleanType);
531 tree.body = translate(tree.body);
532 result = tree;
533 }
535 public void visitForLoop(JCForLoop tree) {
536 tree.init = translate(tree.init, null);
537 if (tree.cond != null)
538 tree.cond = translate(tree.cond, syms.booleanType);
539 tree.step = translate(tree.step, null);
540 tree.body = translate(tree.body);
541 result = tree;
542 }
544 public void visitForeachLoop(JCEnhancedForLoop tree) {
545 tree.var = translate(tree.var, null);
546 Type iterableType = tree.expr.type;
547 tree.expr = translate(tree.expr, erasure(tree.expr.type));
548 if (types.elemtype(tree.expr.type) == null)
549 tree.expr.type = iterableType; // preserve type for Lower
550 tree.body = translate(tree.body);
551 result = tree;
552 }
554 public void visitLambda(JCLambda tree) {
555 JCTree prevMethod = currentMethod;
556 try {
557 currentMethod = null;
558 tree.params = translate(tree.params);
559 tree.body = translate(tree.body, null);
560 tree.type = erasure(tree.type);
561 result = tree;
562 }
563 finally {
564 currentMethod = prevMethod;
565 }
566 }
568 public void visitSwitch(JCSwitch tree) {
569 Type selsuper = types.supertype(tree.selector.type);
570 boolean enumSwitch = selsuper != null &&
571 selsuper.tsym == syms.enumSym;
572 Type target = enumSwitch ? erasure(tree.selector.type) : syms.intType;
573 tree.selector = translate(tree.selector, target);
574 tree.cases = translateCases(tree.cases);
575 result = tree;
576 }
578 public void visitCase(JCCase tree) {
579 tree.pat = translate(tree.pat, null);
580 tree.stats = translate(tree.stats);
581 result = tree;
582 }
584 public void visitSynchronized(JCSynchronized tree) {
585 tree.lock = translate(tree.lock, erasure(tree.lock.type));
586 tree.body = translate(tree.body);
587 result = tree;
588 }
590 public void visitTry(JCTry tree) {
591 tree.resources = translate(tree.resources, syms.autoCloseableType);
592 tree.body = translate(tree.body);
593 tree.catchers = translateCatchers(tree.catchers);
594 tree.finalizer = translate(tree.finalizer);
595 result = tree;
596 }
598 public void visitConditional(JCConditional tree) {
599 tree.cond = translate(tree.cond, syms.booleanType);
600 tree.truepart = translate(tree.truepart, erasure(tree.type));
601 tree.falsepart = translate(tree.falsepart, erasure(tree.type));
602 tree.type = erasure(tree.type);
603 result = retype(tree, tree.type, pt);
604 }
606 public void visitIf(JCIf tree) {
607 tree.cond = translate(tree.cond, syms.booleanType);
608 tree.thenpart = translate(tree.thenpart);
609 tree.elsepart = translate(tree.elsepart);
610 result = tree;
611 }
613 public void visitExec(JCExpressionStatement tree) {
614 tree.expr = translate(tree.expr, null);
615 result = tree;
616 }
618 public void visitReturn(JCReturn tree) {
619 tree.expr = translate(tree.expr, currentMethod != null ? types.erasure(currentMethod.type).getReturnType() : null);
620 result = tree;
621 }
623 public void visitThrow(JCThrow tree) {
624 tree.expr = translate(tree.expr, erasure(tree.expr.type));
625 result = tree;
626 }
628 public void visitAssert(JCAssert tree) {
629 tree.cond = translate(tree.cond, syms.booleanType);
630 if (tree.detail != null)
631 tree.detail = translate(tree.detail, erasure(tree.detail.type));
632 result = tree;
633 }
635 public void visitApply(JCMethodInvocation tree) {
636 tree.meth = translate(tree.meth, null);
637 Symbol meth = TreeInfo.symbol(tree.meth);
638 Type mt = meth.erasure(types);
639 List<Type> argtypes = mt.getParameterTypes();
640 if (allowEnums &&
641 meth.name==names.init &&
642 meth.owner == syms.enumSym)
643 argtypes = argtypes.tail.tail;
644 if (tree.varargsElement != null)
645 tree.varargsElement = types.erasure(tree.varargsElement);
646 else
647 Assert.check(tree.args.length() == argtypes.length());
648 tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
650 tree.type = types.erasure(tree.type);
651 // Insert casts of method invocation results as needed.
652 result = retype(tree, mt.getReturnType(), pt);
653 }
655 public void visitNewClass(JCNewClass tree) {
656 if (tree.encl != null)
657 tree.encl = translate(tree.encl, erasure(tree.encl.type));
658 tree.clazz = translate(tree.clazz, null);
659 if (tree.varargsElement != null)
660 tree.varargsElement = types.erasure(tree.varargsElement);
661 tree.args = translateArgs(
662 tree.args, tree.constructor.erasure(types).getParameterTypes(), tree.varargsElement);
663 tree.def = translate(tree.def, null);
664 if (tree.constructorType != null)
665 tree.constructorType = erasure(tree.constructorType);
666 tree.type = erasure(tree.type);
667 result = tree;
668 }
670 public void visitNewArray(JCNewArray tree) {
671 tree.elemtype = translate(tree.elemtype, null);
672 translate(tree.dims, syms.intType);
673 if (tree.type != null) {
674 tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
675 tree.type = erasure(tree.type);
676 } else {
677 tree.elems = translate(tree.elems, null);
678 }
680 result = tree;
681 }
683 public void visitParens(JCParens tree) {
684 tree.expr = translate(tree.expr, pt);
685 tree.type = erasure(tree.type);
686 result = tree;
687 }
689 public void visitAssign(JCAssign tree) {
690 tree.lhs = translate(tree.lhs, null);
691 tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
692 tree.type = erasure(tree.lhs.type);
693 result = retype(tree, tree.type, pt);
694 }
696 public void visitAssignop(JCAssignOp tree) {
697 tree.lhs = translate(tree.lhs, null);
698 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
699 tree.type = erasure(tree.type);
700 result = tree;
701 }
703 public void visitUnary(JCUnary tree) {
704 tree.arg = translate(tree.arg, tree.operator.type.getParameterTypes().head);
705 result = tree;
706 }
708 public void visitBinary(JCBinary tree) {
709 tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
710 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
711 result = tree;
712 }
714 public void visitTypeCast(JCTypeCast tree) {
715 tree.clazz = translate(tree.clazz, null);
716 Type originalTarget = tree.type;
717 tree.type = erasure(tree.type);
718 tree.expr = translate(tree.expr, tree.type);
719 if (originalTarget.isCompound()) {
720 Type.IntersectionClassType ict = (Type.IntersectionClassType)originalTarget;
721 for (Type c : ict.getExplicitComponents()) {
722 Type ec = erasure(c);
723 if (!types.isSameType(ec, tree.type)) {
724 tree.expr = coerce(tree.expr, ec);
725 }
726 }
727 }
728 result = tree;
729 }
731 public void visitTypeTest(JCInstanceOf tree) {
732 tree.expr = translate(tree.expr, null);
733 tree.clazz = translate(tree.clazz, null);
734 result = tree;
735 }
737 public void visitIndexed(JCArrayAccess tree) {
738 tree.indexed = translate(tree.indexed, erasure(tree.indexed.type));
739 tree.index = translate(tree.index, syms.intType);
741 // Insert casts of indexed expressions as needed.
742 result = retype(tree, types.elemtype(tree.indexed.type), pt);
743 }
745 // There ought to be nothing to rewrite here;
746 // we don't generate code.
747 public void visitAnnotation(JCAnnotation tree) {
748 result = tree;
749 }
751 public void visitIdent(JCIdent tree) {
752 Type et = tree.sym.erasure(types);
754 // Map type variables to their bounds.
755 if (tree.sym.kind == TYP && tree.sym.type.hasTag(TYPEVAR)) {
756 result = make.at(tree.pos).Type(et);
757 } else
758 // Map constants expressions to themselves.
759 if (tree.type.constValue() != null) {
760 result = tree;
761 }
762 // Insert casts of variable uses as needed.
763 else if (tree.sym.kind == VAR) {
764 result = retype(tree, et, pt);
765 }
766 else {
767 tree.type = erasure(tree.type);
768 result = tree;
769 }
770 }
772 public void visitSelect(JCFieldAccess tree) {
773 Type t = tree.selected.type;
774 while (t.hasTag(TYPEVAR))
775 t = t.getUpperBound();
776 if (t.isCompound()) {
777 if ((tree.sym.flags() & IPROXY) != 0) {
778 tree.sym = ((MethodSymbol)tree.sym).
779 implemented((TypeSymbol)tree.sym.owner, types);
780 }
781 tree.selected = coerce(
782 translate(tree.selected, erasure(tree.selected.type)),
783 erasure(tree.sym.owner.type));
784 } else
785 tree.selected = translate(tree.selected, erasure(t));
787 // Map constants expressions to themselves.
788 if (tree.type.constValue() != null) {
789 result = tree;
790 }
791 // Insert casts of variable uses as needed.
792 else if (tree.sym.kind == VAR) {
793 result = retype(tree, tree.sym.erasure(types), pt);
794 }
795 else {
796 tree.type = erasure(tree.type);
797 result = tree;
798 }
799 }
801 public void visitReference(JCMemberReference tree) {
802 tree.expr = translate(tree.expr, null);
803 tree.type = erasure(tree.type);
804 result = tree;
805 }
807 public void visitTypeArray(JCArrayTypeTree tree) {
808 tree.elemtype = translate(tree.elemtype, null);
809 tree.type = erasure(tree.type);
810 result = tree;
811 }
813 /** Visitor method for parameterized types.
814 */
815 public void visitTypeApply(JCTypeApply tree) {
816 JCTree clazz = translate(tree.clazz, null);
817 result = clazz;
818 }
820 public void visitTypeIntersection(JCTypeIntersection tree) {
821 tree.bounds = translate(tree.bounds, null);
822 tree.type = erasure(tree.type);
823 result = tree;
824 }
826 /**************************************************************************
827 * utility methods
828 *************************************************************************/
830 private Type erasure(Type t) {
831 return types.erasure(t);
832 }
834 private boolean boundsRestricted(ClassSymbol c) {
835 Type st = types.supertype(c.type);
836 if (st.isParameterized()) {
837 List<Type> actuals = st.allparams();
838 List<Type> formals = st.tsym.type.allparams();
839 while (!actuals.isEmpty() && !formals.isEmpty()) {
840 Type actual = actuals.head;
841 Type formal = formals.head;
843 if (!types.isSameType(types.erasure(actual),
844 types.erasure(formal)))
845 return true;
847 actuals = actuals.tail;
848 formals = formals.tail;
849 }
850 }
851 return false;
852 }
854 private List<JCTree> addOverrideBridgesIfNeeded(DiagnosticPosition pos,
855 final ClassSymbol c) {
856 ListBuffer<JCTree> buf = ListBuffer.lb();
857 if (c.isInterface() || !boundsRestricted(c))
858 return buf.toList();
859 Type t = types.supertype(c.type);
860 Scope s = t.tsym.members();
861 if (s.elems != null) {
862 for (Symbol sym : s.getElements(new NeedsOverridBridgeFilter(c))) {
864 MethodSymbol m = (MethodSymbol)sym;
865 MethodSymbol member = (MethodSymbol)m.asMemberOf(c.type, types);
866 MethodSymbol impl = m.implementation(c, types, false);
868 if ((impl == null || impl.owner != c) &&
869 !types.isSameType(member.erasure(types), m.erasure(types))) {
870 addOverrideBridges(pos, m, member, c, buf);
871 }
872 }
873 }
874 return buf.toList();
875 }
876 // where
877 class NeedsOverridBridgeFilter implements Filter<Symbol> {
879 ClassSymbol c;
881 NeedsOverridBridgeFilter(ClassSymbol c) {
882 this.c = c;
883 }
884 public boolean accepts(Symbol s) {
885 return s.kind == MTH &&
886 !s.isConstructor() &&
887 s.isInheritedIn(c, types) &&
888 (s.flags() & FINAL) == 0 &&
889 (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
890 }
891 }
893 private void addOverrideBridges(DiagnosticPosition pos,
894 MethodSymbol impl,
895 MethodSymbol member,
896 ClassSymbol c,
897 ListBuffer<JCTree> bridges) {
898 Type implErasure = impl.erasure(types);
899 long flags = (impl.flags() & AccessFlags) | SYNTHETIC | BRIDGE | OVERRIDE_BRIDGE;
900 member = new MethodSymbol(flags, member.name, member.type, c);
901 JCMethodDecl md = make.MethodDef(member, null);
902 JCExpression receiver = make.Super(types.supertype(c.type).tsym.erasure(types), c);
903 Type calltype = erasure(impl.type.getReturnType());
904 JCExpression call =
905 make.Apply(null,
906 make.Select(receiver, impl).setType(calltype),
907 translateArgs(make.Idents(md.params),
908 implErasure.getParameterTypes(), null))
909 .setType(calltype);
910 JCStatement stat = (member.getReturnType().hasTag(VOID))
911 ? make.Exec(call)
912 : make.Return(coerce(call, member.erasure(types).getReturnType()));
913 md.body = make.Block(0, List.of(stat));
914 c.members().enter(member);
915 bridges.append(md);
916 }
918 /**************************************************************************
919 * main method
920 *************************************************************************/
922 private Env<AttrContext> env;
924 private static final String statePreviousToFlowAssertMsg =
925 "The current compile state [%s] of class %s is previous to FLOW";
927 void translateClass(ClassSymbol c) {
928 Type st = types.supertype(c.type);
929 // process superclass before derived
930 if (st.hasTag(CLASS)) {
931 translateClass((ClassSymbol)st.tsym);
932 }
934 Env<AttrContext> myEnv = enter.typeEnvs.remove(c);
935 if (myEnv == null) {
936 return;
937 }
939 /* The two assertions below are set for early detection of any attempt
940 * to translate a class that:
941 *
942 * 1) has no compile state being it the most outer class.
943 * We accept this condition for inner classes.
944 *
945 * 2) has a compile state which is previous to Flow state.
946 */
947 boolean envHasCompState = compileStates.get(myEnv) != null;
948 if (!envHasCompState && c.outermostClass() == c) {
949 Assert.error("No info for outermost class: " + myEnv.enclClass.sym);
950 }
952 if (envHasCompState &&
953 CompileState.FLOW.isAfter(compileStates.get(myEnv))) {
954 Assert.error(String.format(statePreviousToFlowAssertMsg,
955 compileStates.get(myEnv), myEnv.enclClass.sym));
956 }
958 Env<AttrContext> oldEnv = env;
959 try {
960 env = myEnv;
961 // class has not been translated yet
963 TreeMaker savedMake = make;
964 Type savedPt = pt;
965 make = make.forToplevel(env.toplevel);
966 pt = null;
967 try {
968 JCClassDecl tree = (JCClassDecl) env.tree;
969 tree.typarams = List.nil();
970 super.visitClassDef(tree);
971 make.at(tree.pos);
972 if (addBridges) {
973 ListBuffer<JCTree> bridges = new ListBuffer<JCTree>();
974 if (false) //see CR: 6996415
975 bridges.appendList(addOverrideBridgesIfNeeded(tree, c));
976 if ((tree.sym.flags() & INTERFACE) == 0)
977 addBridges(tree.pos(), tree.sym, bridges);
978 tree.defs = bridges.toList().prependList(tree.defs);
979 }
980 tree.type = erasure(tree.type);
981 } finally {
982 make = savedMake;
983 pt = savedPt;
984 }
985 } finally {
986 env = oldEnv;
987 }
988 }
990 /** Translate a toplevel class definition.
991 * @param cdef The definition to be translated.
992 */
993 public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
994 // note that this method does NOT support recursion.
995 this.make = make;
996 pt = null;
997 return translate(cdef, null);
998 }
999 }