Wed, 21 Sep 2011 21:56:53 -0700
7092965: javac should not close processorClassLoader before end of compilation
Reviewed-by: darcy
1 /*
2 * Copyright (c) 2003, 2011, 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.code;
28 import java.lang.ref.SoftReference;
29 import java.util.*;
31 import com.sun.tools.javac.util.*;
32 import com.sun.tools.javac.util.List;
34 import com.sun.tools.javac.jvm.ClassReader;
35 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
36 import com.sun.tools.javac.code.Lint.LintCategory;
37 import com.sun.tools.javac.comp.Check;
39 import static com.sun.tools.javac.code.Scope.*;
40 import static com.sun.tools.javac.code.Type.*;
41 import static com.sun.tools.javac.code.TypeTags.*;
42 import static com.sun.tools.javac.code.Symbol.*;
43 import static com.sun.tools.javac.code.Flags.*;
44 import static com.sun.tools.javac.code.BoundKind.*;
45 import static com.sun.tools.javac.util.ListBuffer.lb;
47 /**
48 * Utility class containing various operations on types.
49 *
50 * <p>Unless other names are more illustrative, the following naming
51 * conventions should be observed in this file:
52 *
53 * <dl>
54 * <dt>t</dt>
55 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
56 * <dt>s</dt>
57 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
58 * <dt>ts</dt>
59 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
60 * <dt>ss</dt>
61 * <dd>A second list of types should be named ss.</dd>
62 * </dl>
63 *
64 * <p><b>This is NOT part of any supported API.
65 * If you write code that depends on this, you do so at your own risk.
66 * This code and its internal interfaces are subject to change or
67 * deletion without notice.</b>
68 */
69 public class Types {
70 protected static final Context.Key<Types> typesKey =
71 new Context.Key<Types>();
73 final Symtab syms;
74 final JavacMessages messages;
75 final Names names;
76 final boolean allowBoxing;
77 final boolean allowCovariantReturns;
78 final boolean allowObjectToPrimitiveCast;
79 final ClassReader reader;
80 final Check chk;
81 List<Warner> warnStack = List.nil();
82 final Name capturedName;
84 // <editor-fold defaultstate="collapsed" desc="Instantiating">
85 public static Types instance(Context context) {
86 Types instance = context.get(typesKey);
87 if (instance == null)
88 instance = new Types(context);
89 return instance;
90 }
92 protected Types(Context context) {
93 context.put(typesKey, this);
94 syms = Symtab.instance(context);
95 names = Names.instance(context);
96 Source source = Source.instance(context);
97 allowBoxing = source.allowBoxing();
98 allowCovariantReturns = source.allowCovariantReturns();
99 allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
100 reader = ClassReader.instance(context);
101 chk = Check.instance(context);
102 capturedName = names.fromString("<captured wildcard>");
103 messages = JavacMessages.instance(context);
104 }
105 // </editor-fold>
107 // <editor-fold defaultstate="collapsed" desc="upperBound">
108 /**
109 * The "rvalue conversion".<br>
110 * The upper bound of most types is the type
111 * itself. Wildcards, on the other hand have upper
112 * and lower bounds.
113 * @param t a type
114 * @return the upper bound of the given type
115 */
116 public Type upperBound(Type t) {
117 return upperBound.visit(t);
118 }
119 // where
120 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
122 @Override
123 public Type visitWildcardType(WildcardType t, Void ignored) {
124 if (t.isSuperBound())
125 return t.bound == null ? syms.objectType : t.bound.bound;
126 else
127 return visit(t.type);
128 }
130 @Override
131 public Type visitCapturedType(CapturedType t, Void ignored) {
132 return visit(t.bound);
133 }
134 };
135 // </editor-fold>
137 // <editor-fold defaultstate="collapsed" desc="lowerBound">
138 /**
139 * The "lvalue conversion".<br>
140 * The lower bound of most types is the type
141 * itself. Wildcards, on the other hand have upper
142 * and lower bounds.
143 * @param t a type
144 * @return the lower bound of the given type
145 */
146 public Type lowerBound(Type t) {
147 return lowerBound.visit(t);
148 }
149 // where
150 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
152 @Override
153 public Type visitWildcardType(WildcardType t, Void ignored) {
154 return t.isExtendsBound() ? syms.botType : visit(t.type);
155 }
157 @Override
158 public Type visitCapturedType(CapturedType t, Void ignored) {
159 return visit(t.getLowerBound());
160 }
161 };
162 // </editor-fold>
164 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
165 /**
166 * Checks that all the arguments to a class are unbounded
167 * wildcards or something else that doesn't make any restrictions
168 * on the arguments. If a class isUnbounded, a raw super- or
169 * subclass can be cast to it without a warning.
170 * @param t a type
171 * @return true iff the given type is unbounded or raw
172 */
173 public boolean isUnbounded(Type t) {
174 return isUnbounded.visit(t);
175 }
176 // where
177 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
179 public Boolean visitType(Type t, Void ignored) {
180 return true;
181 }
183 @Override
184 public Boolean visitClassType(ClassType t, Void ignored) {
185 List<Type> parms = t.tsym.type.allparams();
186 List<Type> args = t.allparams();
187 while (parms.nonEmpty()) {
188 WildcardType unb = new WildcardType(syms.objectType,
189 BoundKind.UNBOUND,
190 syms.boundClass,
191 (TypeVar)parms.head);
192 if (!containsType(args.head, unb))
193 return false;
194 parms = parms.tail;
195 args = args.tail;
196 }
197 return true;
198 }
199 };
200 // </editor-fold>
202 // <editor-fold defaultstate="collapsed" desc="asSub">
203 /**
204 * Return the least specific subtype of t that starts with symbol
205 * sym. If none exists, return null. The least specific subtype
206 * is determined as follows:
207 *
208 * <p>If there is exactly one parameterized instance of sym that is a
209 * subtype of t, that parameterized instance is returned.<br>
210 * Otherwise, if the plain type or raw type `sym' is a subtype of
211 * type t, the type `sym' itself is returned. Otherwise, null is
212 * returned.
213 */
214 public Type asSub(Type t, Symbol sym) {
215 return asSub.visit(t, sym);
216 }
217 // where
218 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
220 public Type visitType(Type t, Symbol sym) {
221 return null;
222 }
224 @Override
225 public Type visitClassType(ClassType t, Symbol sym) {
226 if (t.tsym == sym)
227 return t;
228 Type base = asSuper(sym.type, t.tsym);
229 if (base == null)
230 return null;
231 ListBuffer<Type> from = new ListBuffer<Type>();
232 ListBuffer<Type> to = new ListBuffer<Type>();
233 try {
234 adapt(base, t, from, to);
235 } catch (AdaptFailure ex) {
236 return null;
237 }
238 Type res = subst(sym.type, from.toList(), to.toList());
239 if (!isSubtype(res, t))
240 return null;
241 ListBuffer<Type> openVars = new ListBuffer<Type>();
242 for (List<Type> l = sym.type.allparams();
243 l.nonEmpty(); l = l.tail)
244 if (res.contains(l.head) && !t.contains(l.head))
245 openVars.append(l.head);
246 if (openVars.nonEmpty()) {
247 if (t.isRaw()) {
248 // The subtype of a raw type is raw
249 res = erasure(res);
250 } else {
251 // Unbound type arguments default to ?
252 List<Type> opens = openVars.toList();
253 ListBuffer<Type> qs = new ListBuffer<Type>();
254 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
255 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
256 }
257 res = subst(res, opens, qs.toList());
258 }
259 }
260 return res;
261 }
263 @Override
264 public Type visitErrorType(ErrorType t, Symbol sym) {
265 return t;
266 }
267 };
268 // </editor-fold>
270 // <editor-fold defaultstate="collapsed" desc="isConvertible">
271 /**
272 * Is t a subtype of or convertible via boxing/unboxing
273 * conversion to s?
274 */
275 public boolean isConvertible(Type t, Type s, Warner warn) {
276 if (t.tag == ERROR)
277 return true;
278 boolean tPrimitive = t.isPrimitive();
279 boolean sPrimitive = s.isPrimitive();
280 if (tPrimitive == sPrimitive) {
281 checkUnsafeVarargsConversion(t, s, warn);
282 return isSubtypeUnchecked(t, s, warn);
283 }
284 if (!allowBoxing) return false;
285 return tPrimitive
286 ? isSubtype(boxedClass(t).type, s)
287 : isSubtype(unboxedType(t), s);
288 }
289 //where
290 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
291 if (t.tag != ARRAY || isReifiable(t)) return;
292 ArrayType from = (ArrayType)t;
293 boolean shouldWarn = false;
294 switch (s.tag) {
295 case ARRAY:
296 ArrayType to = (ArrayType)s;
297 shouldWarn = from.isVarargs() &&
298 !to.isVarargs() &&
299 !isReifiable(from);
300 break;
301 case CLASS:
302 shouldWarn = from.isVarargs() &&
303 isSubtype(from, s);
304 break;
305 }
306 if (shouldWarn) {
307 warn.warn(LintCategory.VARARGS);
308 }
309 }
311 /**
312 * Is t a subtype of or convertiable via boxing/unboxing
313 * convertions to s?
314 */
315 public boolean isConvertible(Type t, Type s) {
316 return isConvertible(t, s, Warner.noWarnings);
317 }
318 // </editor-fold>
320 // <editor-fold defaultstate="collapsed" desc="isSubtype">
321 /**
322 * Is t an unchecked subtype of s?
323 */
324 public boolean isSubtypeUnchecked(Type t, Type s) {
325 return isSubtypeUnchecked(t, s, Warner.noWarnings);
326 }
327 /**
328 * Is t an unchecked subtype of s?
329 */
330 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
331 if (t.tag == ARRAY && s.tag == ARRAY) {
332 if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
333 return isSameType(elemtype(t), elemtype(s));
334 } else {
335 ArrayType from = (ArrayType)t;
336 ArrayType to = (ArrayType)s;
337 if (from.isVarargs() &&
338 !to.isVarargs() &&
339 !isReifiable(from)) {
340 warn.warn(LintCategory.VARARGS);
341 }
342 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
343 }
344 } else if (isSubtype(t, s)) {
345 return true;
346 }
347 else if (t.tag == TYPEVAR) {
348 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
349 }
350 else if (s.tag == UNDETVAR) {
351 UndetVar uv = (UndetVar)s;
352 if (uv.inst != null)
353 return isSubtypeUnchecked(t, uv.inst, warn);
354 }
355 else if (!s.isRaw()) {
356 Type t2 = asSuper(t, s.tsym);
357 if (t2 != null && t2.isRaw()) {
358 if (isReifiable(s))
359 warn.silentWarn(LintCategory.UNCHECKED);
360 else
361 warn.warn(LintCategory.UNCHECKED);
362 return true;
363 }
364 }
365 return false;
366 }
368 /**
369 * Is t a subtype of s?<br>
370 * (not defined for Method and ForAll types)
371 */
372 final public boolean isSubtype(Type t, Type s) {
373 return isSubtype(t, s, true);
374 }
375 final public boolean isSubtypeNoCapture(Type t, Type s) {
376 return isSubtype(t, s, false);
377 }
378 public boolean isSubtype(Type t, Type s, boolean capture) {
379 if (t == s)
380 return true;
382 if (s.tag >= firstPartialTag)
383 return isSuperType(s, t);
385 if (s.isCompound()) {
386 for (Type s2 : interfaces(s).prepend(supertype(s))) {
387 if (!isSubtype(t, s2, capture))
388 return false;
389 }
390 return true;
391 }
393 Type lower = lowerBound(s);
394 if (s != lower)
395 return isSubtype(capture ? capture(t) : t, lower, false);
397 return isSubtype.visit(capture ? capture(t) : t, s);
398 }
399 // where
400 private TypeRelation isSubtype = new TypeRelation()
401 {
402 public Boolean visitType(Type t, Type s) {
403 switch (t.tag) {
404 case BYTE: case CHAR:
405 return (t.tag == s.tag ||
406 t.tag + 2 <= s.tag && s.tag <= DOUBLE);
407 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
408 return t.tag <= s.tag && s.tag <= DOUBLE;
409 case BOOLEAN: case VOID:
410 return t.tag == s.tag;
411 case TYPEVAR:
412 return isSubtypeNoCapture(t.getUpperBound(), s);
413 case BOT:
414 return
415 s.tag == BOT || s.tag == CLASS ||
416 s.tag == ARRAY || s.tag == TYPEVAR;
417 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
418 case NONE:
419 return false;
420 default:
421 throw new AssertionError("isSubtype " + t.tag);
422 }
423 }
425 private Set<TypePair> cache = new HashSet<TypePair>();
427 private boolean containsTypeRecursive(Type t, Type s) {
428 TypePair pair = new TypePair(t, s);
429 if (cache.add(pair)) {
430 try {
431 return containsType(t.getTypeArguments(),
432 s.getTypeArguments());
433 } finally {
434 cache.remove(pair);
435 }
436 } else {
437 return containsType(t.getTypeArguments(),
438 rewriteSupers(s).getTypeArguments());
439 }
440 }
442 private Type rewriteSupers(Type t) {
443 if (!t.isParameterized())
444 return t;
445 ListBuffer<Type> from = lb();
446 ListBuffer<Type> to = lb();
447 adaptSelf(t, from, to);
448 if (from.isEmpty())
449 return t;
450 ListBuffer<Type> rewrite = lb();
451 boolean changed = false;
452 for (Type orig : to.toList()) {
453 Type s = rewriteSupers(orig);
454 if (s.isSuperBound() && !s.isExtendsBound()) {
455 s = new WildcardType(syms.objectType,
456 BoundKind.UNBOUND,
457 syms.boundClass);
458 changed = true;
459 } else if (s != orig) {
460 s = new WildcardType(upperBound(s),
461 BoundKind.EXTENDS,
462 syms.boundClass);
463 changed = true;
464 }
465 rewrite.append(s);
466 }
467 if (changed)
468 return subst(t.tsym.type, from.toList(), rewrite.toList());
469 else
470 return t;
471 }
473 @Override
474 public Boolean visitClassType(ClassType t, Type s) {
475 Type sup = asSuper(t, s.tsym);
476 return sup != null
477 && sup.tsym == s.tsym
478 // You're not allowed to write
479 // Vector<Object> vec = new Vector<String>();
480 // But with wildcards you can write
481 // Vector<? extends Object> vec = new Vector<String>();
482 // which means that subtype checking must be done
483 // here instead of same-type checking (via containsType).
484 && (!s.isParameterized() || containsTypeRecursive(s, sup))
485 && isSubtypeNoCapture(sup.getEnclosingType(),
486 s.getEnclosingType());
487 }
489 @Override
490 public Boolean visitArrayType(ArrayType t, Type s) {
491 if (s.tag == ARRAY) {
492 if (t.elemtype.tag <= lastBaseTag)
493 return isSameType(t.elemtype, elemtype(s));
494 else
495 return isSubtypeNoCapture(t.elemtype, elemtype(s));
496 }
498 if (s.tag == CLASS) {
499 Name sname = s.tsym.getQualifiedName();
500 return sname == names.java_lang_Object
501 || sname == names.java_lang_Cloneable
502 || sname == names.java_io_Serializable;
503 }
505 return false;
506 }
508 @Override
509 public Boolean visitUndetVar(UndetVar t, Type s) {
510 //todo: test against origin needed? or replace with substitution?
511 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
512 return true;
513 } else if (s.tag == BOT) {
514 //if 's' is 'null' there's no instantiated type U for which
515 //U <: s (but 'null' itself, which is not a valid type)
516 return false;
517 }
519 if (t.inst != null)
520 return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
522 t.hibounds = t.hibounds.prepend(s);
523 return true;
524 }
526 @Override
527 public Boolean visitErrorType(ErrorType t, Type s) {
528 return true;
529 }
530 };
532 /**
533 * Is t a subtype of every type in given list `ts'?<br>
534 * (not defined for Method and ForAll types)<br>
535 * Allows unchecked conversions.
536 */
537 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
538 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
539 if (!isSubtypeUnchecked(t, l.head, warn))
540 return false;
541 return true;
542 }
544 /**
545 * Are corresponding elements of ts subtypes of ss? If lists are
546 * of different length, return false.
547 */
548 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
549 while (ts.tail != null && ss.tail != null
550 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
551 isSubtype(ts.head, ss.head)) {
552 ts = ts.tail;
553 ss = ss.tail;
554 }
555 return ts.tail == null && ss.tail == null;
556 /*inlined: ts.isEmpty() && ss.isEmpty();*/
557 }
559 /**
560 * Are corresponding elements of ts subtypes of ss, allowing
561 * unchecked conversions? If lists are of different length,
562 * return false.
563 **/
564 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
565 while (ts.tail != null && ss.tail != null
566 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
567 isSubtypeUnchecked(ts.head, ss.head, warn)) {
568 ts = ts.tail;
569 ss = ss.tail;
570 }
571 return ts.tail == null && ss.tail == null;
572 /*inlined: ts.isEmpty() && ss.isEmpty();*/
573 }
574 // </editor-fold>
576 // <editor-fold defaultstate="collapsed" desc="isSuperType">
577 /**
578 * Is t a supertype of s?
579 */
580 public boolean isSuperType(Type t, Type s) {
581 switch (t.tag) {
582 case ERROR:
583 return true;
584 case UNDETVAR: {
585 UndetVar undet = (UndetVar)t;
586 if (t == s ||
587 undet.qtype == s ||
588 s.tag == ERROR ||
589 s.tag == BOT) return true;
590 if (undet.inst != null)
591 return isSubtype(s, undet.inst);
592 undet.lobounds = undet.lobounds.prepend(s);
593 return true;
594 }
595 default:
596 return isSubtype(s, t);
597 }
598 }
599 // </editor-fold>
601 // <editor-fold defaultstate="collapsed" desc="isSameType">
602 /**
603 * Are corresponding elements of the lists the same type? If
604 * lists are of different length, return false.
605 */
606 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
607 while (ts.tail != null && ss.tail != null
608 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
609 isSameType(ts.head, ss.head)) {
610 ts = ts.tail;
611 ss = ss.tail;
612 }
613 return ts.tail == null && ss.tail == null;
614 /*inlined: ts.isEmpty() && ss.isEmpty();*/
615 }
617 /**
618 * Is t the same type as s?
619 */
620 public boolean isSameType(Type t, Type s) {
621 return isSameType.visit(t, s);
622 }
623 // where
624 private TypeRelation isSameType = new TypeRelation() {
626 public Boolean visitType(Type t, Type s) {
627 if (t == s)
628 return true;
630 if (s.tag >= firstPartialTag)
631 return visit(s, t);
633 switch (t.tag) {
634 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
635 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
636 return t.tag == s.tag;
637 case TYPEVAR: {
638 if (s.tag == TYPEVAR) {
639 //type-substitution does not preserve type-var types
640 //check that type var symbols and bounds are indeed the same
641 return t.tsym == s.tsym &&
642 visit(t.getUpperBound(), s.getUpperBound());
643 }
644 else {
645 //special case for s == ? super X, where upper(s) = u
646 //check that u == t, where u has been set by Type.withTypeVar
647 return s.isSuperBound() &&
648 !s.isExtendsBound() &&
649 visit(t, upperBound(s));
650 }
651 }
652 default:
653 throw new AssertionError("isSameType " + t.tag);
654 }
655 }
657 @Override
658 public Boolean visitWildcardType(WildcardType t, Type s) {
659 if (s.tag >= firstPartialTag)
660 return visit(s, t);
661 else
662 return false;
663 }
665 @Override
666 public Boolean visitClassType(ClassType t, Type s) {
667 if (t == s)
668 return true;
670 if (s.tag >= firstPartialTag)
671 return visit(s, t);
673 if (s.isSuperBound() && !s.isExtendsBound())
674 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
676 if (t.isCompound() && s.isCompound()) {
677 if (!visit(supertype(t), supertype(s)))
678 return false;
680 HashSet<SingletonType> set = new HashSet<SingletonType>();
681 for (Type x : interfaces(t))
682 set.add(new SingletonType(x));
683 for (Type x : interfaces(s)) {
684 if (!set.remove(new SingletonType(x)))
685 return false;
686 }
687 return (set.isEmpty());
688 }
689 return t.tsym == s.tsym
690 && visit(t.getEnclosingType(), s.getEnclosingType())
691 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
692 }
694 @Override
695 public Boolean visitArrayType(ArrayType t, Type s) {
696 if (t == s)
697 return true;
699 if (s.tag >= firstPartialTag)
700 return visit(s, t);
702 return s.tag == ARRAY
703 && containsTypeEquivalent(t.elemtype, elemtype(s));
704 }
706 @Override
707 public Boolean visitMethodType(MethodType t, Type s) {
708 // isSameType for methods does not take thrown
709 // exceptions into account!
710 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
711 }
713 @Override
714 public Boolean visitPackageType(PackageType t, Type s) {
715 return t == s;
716 }
718 @Override
719 public Boolean visitForAll(ForAll t, Type s) {
720 if (s.tag != FORALL)
721 return false;
723 ForAll forAll = (ForAll)s;
724 return hasSameBounds(t, forAll)
725 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
726 }
728 @Override
729 public Boolean visitUndetVar(UndetVar t, Type s) {
730 if (s.tag == WILDCARD)
731 // FIXME, this might be leftovers from before capture conversion
732 return false;
734 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
735 return true;
737 if (t.inst != null)
738 return visit(t.inst, s);
740 t.inst = fromUnknownFun.apply(s);
741 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
742 if (!isSubtype(l.head, t.inst))
743 return false;
744 }
745 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
746 if (!isSubtype(t.inst, l.head))
747 return false;
748 }
749 return true;
750 }
752 @Override
753 public Boolean visitErrorType(ErrorType t, Type s) {
754 return true;
755 }
756 };
757 // </editor-fold>
759 // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
760 /**
761 * A mapping that turns all unknown types in this type to fresh
762 * unknown variables.
763 */
764 public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
765 public Type apply(Type t) {
766 if (t.tag == UNKNOWN) return new UndetVar(t);
767 else return t.map(this);
768 }
769 };
770 // </editor-fold>
772 // <editor-fold defaultstate="collapsed" desc="Contains Type">
773 public boolean containedBy(Type t, Type s) {
774 switch (t.tag) {
775 case UNDETVAR:
776 if (s.tag == WILDCARD) {
777 UndetVar undetvar = (UndetVar)t;
778 WildcardType wt = (WildcardType)s;
779 switch(wt.kind) {
780 case UNBOUND: //similar to ? extends Object
781 case EXTENDS: {
782 Type bound = upperBound(s);
783 // We should check the new upper bound against any of the
784 // undetvar's lower bounds.
785 for (Type t2 : undetvar.lobounds) {
786 if (!isSubtype(t2, bound))
787 return false;
788 }
789 undetvar.hibounds = undetvar.hibounds.prepend(bound);
790 break;
791 }
792 case SUPER: {
793 Type bound = lowerBound(s);
794 // We should check the new lower bound against any of the
795 // undetvar's lower bounds.
796 for (Type t2 : undetvar.hibounds) {
797 if (!isSubtype(bound, t2))
798 return false;
799 }
800 undetvar.lobounds = undetvar.lobounds.prepend(bound);
801 break;
802 }
803 }
804 return true;
805 } else {
806 return isSameType(t, s);
807 }
808 case ERROR:
809 return true;
810 default:
811 return containsType(s, t);
812 }
813 }
815 boolean containsType(List<Type> ts, List<Type> ss) {
816 while (ts.nonEmpty() && ss.nonEmpty()
817 && containsType(ts.head, ss.head)) {
818 ts = ts.tail;
819 ss = ss.tail;
820 }
821 return ts.isEmpty() && ss.isEmpty();
822 }
824 /**
825 * Check if t contains s.
826 *
827 * <p>T contains S if:
828 *
829 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
830 *
831 * <p>This relation is only used by ClassType.isSubtype(), that
832 * is,
833 *
834 * <p>{@code C<S> <: C<T> if T contains S.}
835 *
836 * <p>Because of F-bounds, this relation can lead to infinite
837 * recursion. Thus we must somehow break that recursion. Notice
838 * that containsType() is only called from ClassType.isSubtype().
839 * Since the arguments have already been checked against their
840 * bounds, we know:
841 *
842 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
843 *
844 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
845 *
846 * @param t a type
847 * @param s a type
848 */
849 public boolean containsType(Type t, Type s) {
850 return containsType.visit(t, s);
851 }
852 // where
853 private TypeRelation containsType = new TypeRelation() {
855 private Type U(Type t) {
856 while (t.tag == WILDCARD) {
857 WildcardType w = (WildcardType)t;
858 if (w.isSuperBound())
859 return w.bound == null ? syms.objectType : w.bound.bound;
860 else
861 t = w.type;
862 }
863 return t;
864 }
866 private Type L(Type t) {
867 while (t.tag == WILDCARD) {
868 WildcardType w = (WildcardType)t;
869 if (w.isExtendsBound())
870 return syms.botType;
871 else
872 t = w.type;
873 }
874 return t;
875 }
877 public Boolean visitType(Type t, Type s) {
878 if (s.tag >= firstPartialTag)
879 return containedBy(s, t);
880 else
881 return isSameType(t, s);
882 }
884 // void debugContainsType(WildcardType t, Type s) {
885 // System.err.println();
886 // System.err.format(" does %s contain %s?%n", t, s);
887 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
888 // upperBound(s), s, t, U(t),
889 // t.isSuperBound()
890 // || isSubtypeNoCapture(upperBound(s), U(t)));
891 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
892 // L(t), t, s, lowerBound(s),
893 // t.isExtendsBound()
894 // || isSubtypeNoCapture(L(t), lowerBound(s)));
895 // System.err.println();
896 // }
898 @Override
899 public Boolean visitWildcardType(WildcardType t, Type s) {
900 if (s.tag >= firstPartialTag)
901 return containedBy(s, t);
902 else {
903 // debugContainsType(t, s);
904 return isSameWildcard(t, s)
905 || isCaptureOf(s, t)
906 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
907 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
908 }
909 }
911 @Override
912 public Boolean visitUndetVar(UndetVar t, Type s) {
913 if (s.tag != WILDCARD)
914 return isSameType(t, s);
915 else
916 return false;
917 }
919 @Override
920 public Boolean visitErrorType(ErrorType t, Type s) {
921 return true;
922 }
923 };
925 public boolean isCaptureOf(Type s, WildcardType t) {
926 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
927 return false;
928 return isSameWildcard(t, ((CapturedType)s).wildcard);
929 }
931 public boolean isSameWildcard(WildcardType t, Type s) {
932 if (s.tag != WILDCARD)
933 return false;
934 WildcardType w = (WildcardType)s;
935 return w.kind == t.kind && w.type == t.type;
936 }
938 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
939 while (ts.nonEmpty() && ss.nonEmpty()
940 && containsTypeEquivalent(ts.head, ss.head)) {
941 ts = ts.tail;
942 ss = ss.tail;
943 }
944 return ts.isEmpty() && ss.isEmpty();
945 }
946 // </editor-fold>
948 // <editor-fold defaultstate="collapsed" desc="isCastable">
949 public boolean isCastable(Type t, Type s) {
950 return isCastable(t, s, Warner.noWarnings);
951 }
953 /**
954 * Is t is castable to s?<br>
955 * s is assumed to be an erased type.<br>
956 * (not defined for Method and ForAll types).
957 */
958 public boolean isCastable(Type t, Type s, Warner warn) {
959 if (t == s)
960 return true;
962 if (t.isPrimitive() != s.isPrimitive())
963 return allowBoxing && (
964 isConvertible(t, s, warn)
965 || (allowObjectToPrimitiveCast &&
966 s.isPrimitive() &&
967 isSubtype(boxedClass(s).type, t)));
968 if (warn != warnStack.head) {
969 try {
970 warnStack = warnStack.prepend(warn);
971 checkUnsafeVarargsConversion(t, s, warn);
972 return isCastable.visit(t,s);
973 } finally {
974 warnStack = warnStack.tail;
975 }
976 } else {
977 return isCastable.visit(t,s);
978 }
979 }
980 // where
981 private TypeRelation isCastable = new TypeRelation() {
983 public Boolean visitType(Type t, Type s) {
984 if (s.tag == ERROR)
985 return true;
987 switch (t.tag) {
988 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
989 case DOUBLE:
990 return s.tag <= DOUBLE;
991 case BOOLEAN:
992 return s.tag == BOOLEAN;
993 case VOID:
994 return false;
995 case BOT:
996 return isSubtype(t, s);
997 default:
998 throw new AssertionError();
999 }
1000 }
1002 @Override
1003 public Boolean visitWildcardType(WildcardType t, Type s) {
1004 return isCastable(upperBound(t), s, warnStack.head);
1005 }
1007 @Override
1008 public Boolean visitClassType(ClassType t, Type s) {
1009 if (s.tag == ERROR || s.tag == BOT)
1010 return true;
1012 if (s.tag == TYPEVAR) {
1013 if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
1014 warnStack.head.warn(LintCategory.UNCHECKED);
1015 return true;
1016 } else {
1017 return false;
1018 }
1019 }
1021 if (t.isCompound()) {
1022 Warner oldWarner = warnStack.head;
1023 warnStack.head = Warner.noWarnings;
1024 if (!visit(supertype(t), s))
1025 return false;
1026 for (Type intf : interfaces(t)) {
1027 if (!visit(intf, s))
1028 return false;
1029 }
1030 if (warnStack.head.hasLint(LintCategory.UNCHECKED))
1031 oldWarner.warn(LintCategory.UNCHECKED);
1032 return true;
1033 }
1035 if (s.isCompound()) {
1036 // call recursively to reuse the above code
1037 return visitClassType((ClassType)s, t);
1038 }
1040 if (s.tag == CLASS || s.tag == ARRAY) {
1041 boolean upcast;
1042 if ((upcast = isSubtype(erasure(t), erasure(s)))
1043 || isSubtype(erasure(s), erasure(t))) {
1044 if (!upcast && s.tag == ARRAY) {
1045 if (!isReifiable(s))
1046 warnStack.head.warn(LintCategory.UNCHECKED);
1047 return true;
1048 } else if (s.isRaw()) {
1049 return true;
1050 } else if (t.isRaw()) {
1051 if (!isUnbounded(s))
1052 warnStack.head.warn(LintCategory.UNCHECKED);
1053 return true;
1054 }
1055 // Assume |a| <: |b|
1056 final Type a = upcast ? t : s;
1057 final Type b = upcast ? s : t;
1058 final boolean HIGH = true;
1059 final boolean LOW = false;
1060 final boolean DONT_REWRITE_TYPEVARS = false;
1061 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1062 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1063 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1064 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1065 Type lowSub = asSub(bLow, aLow.tsym);
1066 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1067 if (highSub == null) {
1068 final boolean REWRITE_TYPEVARS = true;
1069 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1070 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1071 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1072 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1073 lowSub = asSub(bLow, aLow.tsym);
1074 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1075 }
1076 if (highSub != null) {
1077 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1078 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1079 }
1080 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1081 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1082 && !disjointTypes(aLow.allparams(), highSub.allparams())
1083 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1084 if (upcast ? giveWarning(a, b) :
1085 giveWarning(b, a))
1086 warnStack.head.warn(LintCategory.UNCHECKED);
1087 return true;
1088 }
1089 }
1090 if (isReifiable(s))
1091 return isSubtypeUnchecked(a, b);
1092 else
1093 return isSubtypeUnchecked(a, b, warnStack.head);
1094 }
1096 // Sidecast
1097 if (s.tag == CLASS) {
1098 if ((s.tsym.flags() & INTERFACE) != 0) {
1099 return ((t.tsym.flags() & FINAL) == 0)
1100 ? sideCast(t, s, warnStack.head)
1101 : sideCastFinal(t, s, warnStack.head);
1102 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1103 return ((s.tsym.flags() & FINAL) == 0)
1104 ? sideCast(t, s, warnStack.head)
1105 : sideCastFinal(t, s, warnStack.head);
1106 } else {
1107 // unrelated class types
1108 return false;
1109 }
1110 }
1111 }
1112 return false;
1113 }
1115 @Override
1116 public Boolean visitArrayType(ArrayType t, Type s) {
1117 switch (s.tag) {
1118 case ERROR:
1119 case BOT:
1120 return true;
1121 case TYPEVAR:
1122 if (isCastable(s, t, Warner.noWarnings)) {
1123 warnStack.head.warn(LintCategory.UNCHECKED);
1124 return true;
1125 } else {
1126 return false;
1127 }
1128 case CLASS:
1129 return isSubtype(t, s);
1130 case ARRAY:
1131 if (elemtype(t).tag <= lastBaseTag ||
1132 elemtype(s).tag <= lastBaseTag) {
1133 return elemtype(t).tag == elemtype(s).tag;
1134 } else {
1135 return visit(elemtype(t), elemtype(s));
1136 }
1137 default:
1138 return false;
1139 }
1140 }
1142 @Override
1143 public Boolean visitTypeVar(TypeVar t, Type s) {
1144 switch (s.tag) {
1145 case ERROR:
1146 case BOT:
1147 return true;
1148 case TYPEVAR:
1149 if (isSubtype(t, s)) {
1150 return true;
1151 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1152 warnStack.head.warn(LintCategory.UNCHECKED);
1153 return true;
1154 } else {
1155 return false;
1156 }
1157 default:
1158 return isCastable(t.bound, s, warnStack.head);
1159 }
1160 }
1162 @Override
1163 public Boolean visitErrorType(ErrorType t, Type s) {
1164 return true;
1165 }
1166 };
1167 // </editor-fold>
1169 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1170 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1171 while (ts.tail != null && ss.tail != null) {
1172 if (disjointType(ts.head, ss.head)) return true;
1173 ts = ts.tail;
1174 ss = ss.tail;
1175 }
1176 return false;
1177 }
1179 /**
1180 * Two types or wildcards are considered disjoint if it can be
1181 * proven that no type can be contained in both. It is
1182 * conservative in that it is allowed to say that two types are
1183 * not disjoint, even though they actually are.
1184 *
1185 * The type C<X> is castable to C<Y> exactly if X and Y are not
1186 * disjoint.
1187 */
1188 public boolean disjointType(Type t, Type s) {
1189 return disjointType.visit(t, s);
1190 }
1191 // where
1192 private TypeRelation disjointType = new TypeRelation() {
1194 private Set<TypePair> cache = new HashSet<TypePair>();
1196 public Boolean visitType(Type t, Type s) {
1197 if (s.tag == WILDCARD)
1198 return visit(s, t);
1199 else
1200 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1201 }
1203 private boolean isCastableRecursive(Type t, Type s) {
1204 TypePair pair = new TypePair(t, s);
1205 if (cache.add(pair)) {
1206 try {
1207 return Types.this.isCastable(t, s);
1208 } finally {
1209 cache.remove(pair);
1210 }
1211 } else {
1212 return true;
1213 }
1214 }
1216 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1217 TypePair pair = new TypePair(t, s);
1218 if (cache.add(pair)) {
1219 try {
1220 return Types.this.notSoftSubtype(t, s);
1221 } finally {
1222 cache.remove(pair);
1223 }
1224 } else {
1225 return false;
1226 }
1227 }
1229 @Override
1230 public Boolean visitWildcardType(WildcardType t, Type s) {
1231 if (t.isUnbound())
1232 return false;
1234 if (s.tag != WILDCARD) {
1235 if (t.isExtendsBound())
1236 return notSoftSubtypeRecursive(s, t.type);
1237 else // isSuperBound()
1238 return notSoftSubtypeRecursive(t.type, s);
1239 }
1241 if (s.isUnbound())
1242 return false;
1244 if (t.isExtendsBound()) {
1245 if (s.isExtendsBound())
1246 return !isCastableRecursive(t.type, upperBound(s));
1247 else if (s.isSuperBound())
1248 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1249 } else if (t.isSuperBound()) {
1250 if (s.isExtendsBound())
1251 return notSoftSubtypeRecursive(t.type, upperBound(s));
1252 }
1253 return false;
1254 }
1255 };
1256 // </editor-fold>
1258 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1259 /**
1260 * Returns the lower bounds of the formals of a method.
1261 */
1262 public List<Type> lowerBoundArgtypes(Type t) {
1263 return map(t.getParameterTypes(), lowerBoundMapping);
1264 }
1265 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1266 public Type apply(Type t) {
1267 return lowerBound(t);
1268 }
1269 };
1270 // </editor-fold>
1272 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1273 /**
1274 * This relation answers the question: is impossible that
1275 * something of type `t' can be a subtype of `s'? This is
1276 * different from the question "is `t' not a subtype of `s'?"
1277 * when type variables are involved: Integer is not a subtype of T
1278 * where <T extends Number> but it is not true that Integer cannot
1279 * possibly be a subtype of T.
1280 */
1281 public boolean notSoftSubtype(Type t, Type s) {
1282 if (t == s) return false;
1283 if (t.tag == TYPEVAR) {
1284 TypeVar tv = (TypeVar) t;
1285 return !isCastable(tv.bound,
1286 relaxBound(s),
1287 Warner.noWarnings);
1288 }
1289 if (s.tag != WILDCARD)
1290 s = upperBound(s);
1292 return !isSubtype(t, relaxBound(s));
1293 }
1295 private Type relaxBound(Type t) {
1296 if (t.tag == TYPEVAR) {
1297 while (t.tag == TYPEVAR)
1298 t = t.getUpperBound();
1299 t = rewriteQuantifiers(t, true, true);
1300 }
1301 return t;
1302 }
1303 // </editor-fold>
1305 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1306 public boolean isReifiable(Type t) {
1307 return isReifiable.visit(t);
1308 }
1309 // where
1310 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1312 public Boolean visitType(Type t, Void ignored) {
1313 return true;
1314 }
1316 @Override
1317 public Boolean visitClassType(ClassType t, Void ignored) {
1318 if (t.isCompound())
1319 return false;
1320 else {
1321 if (!t.isParameterized())
1322 return true;
1324 for (Type param : t.allparams()) {
1325 if (!param.isUnbound())
1326 return false;
1327 }
1328 return true;
1329 }
1330 }
1332 @Override
1333 public Boolean visitArrayType(ArrayType t, Void ignored) {
1334 return visit(t.elemtype);
1335 }
1337 @Override
1338 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1339 return false;
1340 }
1341 };
1342 // </editor-fold>
1344 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1345 public boolean isArray(Type t) {
1346 while (t.tag == WILDCARD)
1347 t = upperBound(t);
1348 return t.tag == ARRAY;
1349 }
1351 /**
1352 * The element type of an array.
1353 */
1354 public Type elemtype(Type t) {
1355 switch (t.tag) {
1356 case WILDCARD:
1357 return elemtype(upperBound(t));
1358 case ARRAY:
1359 return ((ArrayType)t).elemtype;
1360 case FORALL:
1361 return elemtype(((ForAll)t).qtype);
1362 case ERROR:
1363 return t;
1364 default:
1365 return null;
1366 }
1367 }
1369 public Type elemtypeOrType(Type t) {
1370 Type elemtype = elemtype(t);
1371 return elemtype != null ?
1372 elemtype :
1373 t;
1374 }
1376 /**
1377 * Mapping to take element type of an arraytype
1378 */
1379 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1380 public Type apply(Type t) { return elemtype(t); }
1381 };
1383 /**
1384 * The number of dimensions of an array type.
1385 */
1386 public int dimensions(Type t) {
1387 int result = 0;
1388 while (t.tag == ARRAY) {
1389 result++;
1390 t = elemtype(t);
1391 }
1392 return result;
1393 }
1394 // </editor-fold>
1396 // <editor-fold defaultstate="collapsed" desc="asSuper">
1397 /**
1398 * Return the (most specific) base type of t that starts with the
1399 * given symbol. If none exists, return null.
1400 *
1401 * @param t a type
1402 * @param sym a symbol
1403 */
1404 public Type asSuper(Type t, Symbol sym) {
1405 return asSuper.visit(t, sym);
1406 }
1407 // where
1408 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1410 public Type visitType(Type t, Symbol sym) {
1411 return null;
1412 }
1414 @Override
1415 public Type visitClassType(ClassType t, Symbol sym) {
1416 if (t.tsym == sym)
1417 return t;
1419 Type st = supertype(t);
1420 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1421 Type x = asSuper(st, sym);
1422 if (x != null)
1423 return x;
1424 }
1425 if ((sym.flags() & INTERFACE) != 0) {
1426 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1427 Type x = asSuper(l.head, sym);
1428 if (x != null)
1429 return x;
1430 }
1431 }
1432 return null;
1433 }
1435 @Override
1436 public Type visitArrayType(ArrayType t, Symbol sym) {
1437 return isSubtype(t, sym.type) ? sym.type : null;
1438 }
1440 @Override
1441 public Type visitTypeVar(TypeVar t, Symbol sym) {
1442 if (t.tsym == sym)
1443 return t;
1444 else
1445 return asSuper(t.bound, sym);
1446 }
1448 @Override
1449 public Type visitErrorType(ErrorType t, Symbol sym) {
1450 return t;
1451 }
1452 };
1454 /**
1455 * Return the base type of t or any of its outer types that starts
1456 * with the given symbol. If none exists, return null.
1457 *
1458 * @param t a type
1459 * @param sym a symbol
1460 */
1461 public Type asOuterSuper(Type t, Symbol sym) {
1462 switch (t.tag) {
1463 case CLASS:
1464 do {
1465 Type s = asSuper(t, sym);
1466 if (s != null) return s;
1467 t = t.getEnclosingType();
1468 } while (t.tag == CLASS);
1469 return null;
1470 case ARRAY:
1471 return isSubtype(t, sym.type) ? sym.type : null;
1472 case TYPEVAR:
1473 return asSuper(t, sym);
1474 case ERROR:
1475 return t;
1476 default:
1477 return null;
1478 }
1479 }
1481 /**
1482 * Return the base type of t or any of its enclosing types that
1483 * starts with the given symbol. If none exists, return null.
1484 *
1485 * @param t a type
1486 * @param sym a symbol
1487 */
1488 public Type asEnclosingSuper(Type t, Symbol sym) {
1489 switch (t.tag) {
1490 case CLASS:
1491 do {
1492 Type s = asSuper(t, sym);
1493 if (s != null) return s;
1494 Type outer = t.getEnclosingType();
1495 t = (outer.tag == CLASS) ? outer :
1496 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1497 Type.noType;
1498 } while (t.tag == CLASS);
1499 return null;
1500 case ARRAY:
1501 return isSubtype(t, sym.type) ? sym.type : null;
1502 case TYPEVAR:
1503 return asSuper(t, sym);
1504 case ERROR:
1505 return t;
1506 default:
1507 return null;
1508 }
1509 }
1510 // </editor-fold>
1512 // <editor-fold defaultstate="collapsed" desc="memberType">
1513 /**
1514 * The type of given symbol, seen as a member of t.
1515 *
1516 * @param t a type
1517 * @param sym a symbol
1518 */
1519 public Type memberType(Type t, Symbol sym) {
1520 return (sym.flags() & STATIC) != 0
1521 ? sym.type
1522 : memberType.visit(t, sym);
1523 }
1524 // where
1525 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1527 public Type visitType(Type t, Symbol sym) {
1528 return sym.type;
1529 }
1531 @Override
1532 public Type visitWildcardType(WildcardType t, Symbol sym) {
1533 return memberType(upperBound(t), sym);
1534 }
1536 @Override
1537 public Type visitClassType(ClassType t, Symbol sym) {
1538 Symbol owner = sym.owner;
1539 long flags = sym.flags();
1540 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1541 Type base = asOuterSuper(t, owner);
1542 //if t is an intersection type T = CT & I1 & I2 ... & In
1543 //its supertypes CT, I1, ... In might contain wildcards
1544 //so we need to go through capture conversion
1545 base = t.isCompound() ? capture(base) : base;
1546 if (base != null) {
1547 List<Type> ownerParams = owner.type.allparams();
1548 List<Type> baseParams = base.allparams();
1549 if (ownerParams.nonEmpty()) {
1550 if (baseParams.isEmpty()) {
1551 // then base is a raw type
1552 return erasure(sym.type);
1553 } else {
1554 return subst(sym.type, ownerParams, baseParams);
1555 }
1556 }
1557 }
1558 }
1559 return sym.type;
1560 }
1562 @Override
1563 public Type visitTypeVar(TypeVar t, Symbol sym) {
1564 return memberType(t.bound, sym);
1565 }
1567 @Override
1568 public Type visitErrorType(ErrorType t, Symbol sym) {
1569 return t;
1570 }
1571 };
1572 // </editor-fold>
1574 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1575 public boolean isAssignable(Type t, Type s) {
1576 return isAssignable(t, s, Warner.noWarnings);
1577 }
1579 /**
1580 * Is t assignable to s?<br>
1581 * Equivalent to subtype except for constant values and raw
1582 * types.<br>
1583 * (not defined for Method and ForAll types)
1584 */
1585 public boolean isAssignable(Type t, Type s, Warner warn) {
1586 if (t.tag == ERROR)
1587 return true;
1588 if (t.tag <= INT && t.constValue() != null) {
1589 int value = ((Number)t.constValue()).intValue();
1590 switch (s.tag) {
1591 case BYTE:
1592 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1593 return true;
1594 break;
1595 case CHAR:
1596 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1597 return true;
1598 break;
1599 case SHORT:
1600 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1601 return true;
1602 break;
1603 case INT:
1604 return true;
1605 case CLASS:
1606 switch (unboxedType(s).tag) {
1607 case BYTE:
1608 case CHAR:
1609 case SHORT:
1610 return isAssignable(t, unboxedType(s), warn);
1611 }
1612 break;
1613 }
1614 }
1615 return isConvertible(t, s, warn);
1616 }
1617 // </editor-fold>
1619 // <editor-fold defaultstate="collapsed" desc="erasure">
1620 /**
1621 * The erasure of t {@code |t|} -- the type that results when all
1622 * type parameters in t are deleted.
1623 */
1624 public Type erasure(Type t) {
1625 return erasure(t, false);
1626 }
1627 //where
1628 private Type erasure(Type t, boolean recurse) {
1629 if (t.tag <= lastBaseTag)
1630 return t; /* fast special case */
1631 else
1632 return erasure.visit(t, recurse);
1633 }
1634 // where
1635 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1636 public Type visitType(Type t, Boolean recurse) {
1637 if (t.tag <= lastBaseTag)
1638 return t; /*fast special case*/
1639 else
1640 return t.map(recurse ? erasureRecFun : erasureFun);
1641 }
1643 @Override
1644 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1645 return erasure(upperBound(t), recurse);
1646 }
1648 @Override
1649 public Type visitClassType(ClassType t, Boolean recurse) {
1650 Type erased = t.tsym.erasure(Types.this);
1651 if (recurse) {
1652 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1653 }
1654 return erased;
1655 }
1657 @Override
1658 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1659 return erasure(t.bound, recurse);
1660 }
1662 @Override
1663 public Type visitErrorType(ErrorType t, Boolean recurse) {
1664 return t;
1665 }
1666 };
1668 private Mapping erasureFun = new Mapping ("erasure") {
1669 public Type apply(Type t) { return erasure(t); }
1670 };
1672 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1673 public Type apply(Type t) { return erasureRecursive(t); }
1674 };
1676 public List<Type> erasure(List<Type> ts) {
1677 return Type.map(ts, erasureFun);
1678 }
1680 public Type erasureRecursive(Type t) {
1681 return erasure(t, true);
1682 }
1684 public List<Type> erasureRecursive(List<Type> ts) {
1685 return Type.map(ts, erasureRecFun);
1686 }
1687 // </editor-fold>
1689 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1690 /**
1691 * Make a compound type from non-empty list of types
1692 *
1693 * @param bounds the types from which the compound type is formed
1694 * @param supertype is objectType if all bounds are interfaces,
1695 * null otherwise.
1696 */
1697 public Type makeCompoundType(List<Type> bounds,
1698 Type supertype) {
1699 ClassSymbol bc =
1700 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1701 Type.moreInfo
1702 ? names.fromString(bounds.toString())
1703 : names.empty,
1704 syms.noSymbol);
1705 if (bounds.head.tag == TYPEVAR)
1706 // error condition, recover
1707 bc.erasure_field = syms.objectType;
1708 else
1709 bc.erasure_field = erasure(bounds.head);
1710 bc.members_field = new Scope(bc);
1711 ClassType bt = (ClassType)bc.type;
1712 bt.allparams_field = List.nil();
1713 if (supertype != null) {
1714 bt.supertype_field = supertype;
1715 bt.interfaces_field = bounds;
1716 } else {
1717 bt.supertype_field = bounds.head;
1718 bt.interfaces_field = bounds.tail;
1719 }
1720 Assert.check(bt.supertype_field.tsym.completer != null
1721 || !bt.supertype_field.isInterface(),
1722 bt.supertype_field);
1723 return bt;
1724 }
1726 /**
1727 * Same as {@link #makeCompoundType(List,Type)}, except that the
1728 * second parameter is computed directly. Note that this might
1729 * cause a symbol completion. Hence, this version of
1730 * makeCompoundType may not be called during a classfile read.
1731 */
1732 public Type makeCompoundType(List<Type> bounds) {
1733 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1734 supertype(bounds.head) : null;
1735 return makeCompoundType(bounds, supertype);
1736 }
1738 /**
1739 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1740 * arguments are converted to a list and passed to the other
1741 * method. Note that this might cause a symbol completion.
1742 * Hence, this version of makeCompoundType may not be called
1743 * during a classfile read.
1744 */
1745 public Type makeCompoundType(Type bound1, Type bound2) {
1746 return makeCompoundType(List.of(bound1, bound2));
1747 }
1748 // </editor-fold>
1750 // <editor-fold defaultstate="collapsed" desc="supertype">
1751 public Type supertype(Type t) {
1752 return supertype.visit(t);
1753 }
1754 // where
1755 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1757 public Type visitType(Type t, Void ignored) {
1758 // A note on wildcards: there is no good way to
1759 // determine a supertype for a super bounded wildcard.
1760 return null;
1761 }
1763 @Override
1764 public Type visitClassType(ClassType t, Void ignored) {
1765 if (t.supertype_field == null) {
1766 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1767 // An interface has no superclass; its supertype is Object.
1768 if (t.isInterface())
1769 supertype = ((ClassType)t.tsym.type).supertype_field;
1770 if (t.supertype_field == null) {
1771 List<Type> actuals = classBound(t).allparams();
1772 List<Type> formals = t.tsym.type.allparams();
1773 if (t.hasErasedSupertypes()) {
1774 t.supertype_field = erasureRecursive(supertype);
1775 } else if (formals.nonEmpty()) {
1776 t.supertype_field = subst(supertype, formals, actuals);
1777 }
1778 else {
1779 t.supertype_field = supertype;
1780 }
1781 }
1782 }
1783 return t.supertype_field;
1784 }
1786 /**
1787 * The supertype is always a class type. If the type
1788 * variable's bounds start with a class type, this is also
1789 * the supertype. Otherwise, the supertype is
1790 * java.lang.Object.
1791 */
1792 @Override
1793 public Type visitTypeVar(TypeVar t, Void ignored) {
1794 if (t.bound.tag == TYPEVAR ||
1795 (!t.bound.isCompound() && !t.bound.isInterface())) {
1796 return t.bound;
1797 } else {
1798 return supertype(t.bound);
1799 }
1800 }
1802 @Override
1803 public Type visitArrayType(ArrayType t, Void ignored) {
1804 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1805 return arraySuperType();
1806 else
1807 return new ArrayType(supertype(t.elemtype), t.tsym);
1808 }
1810 @Override
1811 public Type visitErrorType(ErrorType t, Void ignored) {
1812 return t;
1813 }
1814 };
1815 // </editor-fold>
1817 // <editor-fold defaultstate="collapsed" desc="interfaces">
1818 /**
1819 * Return the interfaces implemented by this class.
1820 */
1821 public List<Type> interfaces(Type t) {
1822 return interfaces.visit(t);
1823 }
1824 // where
1825 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1827 public List<Type> visitType(Type t, Void ignored) {
1828 return List.nil();
1829 }
1831 @Override
1832 public List<Type> visitClassType(ClassType t, Void ignored) {
1833 if (t.interfaces_field == null) {
1834 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1835 if (t.interfaces_field == null) {
1836 // If t.interfaces_field is null, then t must
1837 // be a parameterized type (not to be confused
1838 // with a generic type declaration).
1839 // Terminology:
1840 // Parameterized type: List<String>
1841 // Generic type declaration: class List<E> { ... }
1842 // So t corresponds to List<String> and
1843 // t.tsym.type corresponds to List<E>.
1844 // The reason t must be parameterized type is
1845 // that completion will happen as a side
1846 // effect of calling
1847 // ClassSymbol.getInterfaces. Since
1848 // t.interfaces_field is null after
1849 // completion, we can assume that t is not the
1850 // type of a class/interface declaration.
1851 Assert.check(t != t.tsym.type, t);
1852 List<Type> actuals = t.allparams();
1853 List<Type> formals = t.tsym.type.allparams();
1854 if (t.hasErasedSupertypes()) {
1855 t.interfaces_field = erasureRecursive(interfaces);
1856 } else if (formals.nonEmpty()) {
1857 t.interfaces_field =
1858 upperBounds(subst(interfaces, formals, actuals));
1859 }
1860 else {
1861 t.interfaces_field = interfaces;
1862 }
1863 }
1864 }
1865 return t.interfaces_field;
1866 }
1868 @Override
1869 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1870 if (t.bound.isCompound())
1871 return interfaces(t.bound);
1873 if (t.bound.isInterface())
1874 return List.of(t.bound);
1876 return List.nil();
1877 }
1878 };
1879 // </editor-fold>
1881 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1882 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1884 public boolean isDerivedRaw(Type t) {
1885 Boolean result = isDerivedRawCache.get(t);
1886 if (result == null) {
1887 result = isDerivedRawInternal(t);
1888 isDerivedRawCache.put(t, result);
1889 }
1890 return result;
1891 }
1893 public boolean isDerivedRawInternal(Type t) {
1894 if (t.isErroneous())
1895 return false;
1896 return
1897 t.isRaw() ||
1898 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1899 isDerivedRaw(interfaces(t));
1900 }
1902 public boolean isDerivedRaw(List<Type> ts) {
1903 List<Type> l = ts;
1904 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1905 return l.nonEmpty();
1906 }
1907 // </editor-fold>
1909 // <editor-fold defaultstate="collapsed" desc="setBounds">
1910 /**
1911 * Set the bounds field of the given type variable to reflect a
1912 * (possibly multiple) list of bounds.
1913 * @param t a type variable
1914 * @param bounds the bounds, must be nonempty
1915 * @param supertype is objectType if all bounds are interfaces,
1916 * null otherwise.
1917 */
1918 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1919 if (bounds.tail.isEmpty())
1920 t.bound = bounds.head;
1921 else
1922 t.bound = makeCompoundType(bounds, supertype);
1923 t.rank_field = -1;
1924 }
1926 /**
1927 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1928 * third parameter is computed directly, as follows: if all
1929 * all bounds are interface types, the computed supertype is Object,
1930 * otherwise the supertype is simply left null (in this case, the supertype
1931 * is assumed to be the head of the bound list passed as second argument).
1932 * Note that this check might cause a symbol completion. Hence, this version of
1933 * setBounds may not be called during a classfile read.
1934 */
1935 public void setBounds(TypeVar t, List<Type> bounds) {
1936 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1937 syms.objectType : null;
1938 setBounds(t, bounds, supertype);
1939 t.rank_field = -1;
1940 }
1941 // </editor-fold>
1943 // <editor-fold defaultstate="collapsed" desc="getBounds">
1944 /**
1945 * Return list of bounds of the given type variable.
1946 */
1947 public List<Type> getBounds(TypeVar t) {
1948 if (t.bound.isErroneous() || !t.bound.isCompound())
1949 return List.of(t.bound);
1950 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1951 return interfaces(t).prepend(supertype(t));
1952 else
1953 // No superclass was given in bounds.
1954 // In this case, supertype is Object, erasure is first interface.
1955 return interfaces(t);
1956 }
1957 // </editor-fold>
1959 // <editor-fold defaultstate="collapsed" desc="classBound">
1960 /**
1961 * If the given type is a (possibly selected) type variable,
1962 * return the bounding class of this type, otherwise return the
1963 * type itself.
1964 */
1965 public Type classBound(Type t) {
1966 return classBound.visit(t);
1967 }
1968 // where
1969 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1971 public Type visitType(Type t, Void ignored) {
1972 return t;
1973 }
1975 @Override
1976 public Type visitClassType(ClassType t, Void ignored) {
1977 Type outer1 = classBound(t.getEnclosingType());
1978 if (outer1 != t.getEnclosingType())
1979 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1980 else
1981 return t;
1982 }
1984 @Override
1985 public Type visitTypeVar(TypeVar t, Void ignored) {
1986 return classBound(supertype(t));
1987 }
1989 @Override
1990 public Type visitErrorType(ErrorType t, Void ignored) {
1991 return t;
1992 }
1993 };
1994 // </editor-fold>
1996 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1997 /**
1998 * Returns true iff the first signature is a <em>sub
1999 * signature</em> of the other. This is <b>not</b> an equivalence
2000 * relation.
2001 *
2002 * @jls section 8.4.2.
2003 * @see #overrideEquivalent(Type t, Type s)
2004 * @param t first signature (possibly raw).
2005 * @param s second signature (could be subjected to erasure).
2006 * @return true if t is a sub signature of s.
2007 */
2008 public boolean isSubSignature(Type t, Type s) {
2009 return isSubSignature(t, s, true);
2010 }
2012 public boolean isSubSignature(Type t, Type s, boolean strict) {
2013 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2014 }
2016 /**
2017 * Returns true iff these signatures are related by <em>override
2018 * equivalence</em>. This is the natural extension of
2019 * isSubSignature to an equivalence relation.
2020 *
2021 * @jls section 8.4.2.
2022 * @see #isSubSignature(Type t, Type s)
2023 * @param t a signature (possible raw, could be subjected to
2024 * erasure).
2025 * @param s a signature (possible raw, could be subjected to
2026 * erasure).
2027 * @return true if either argument is a sub signature of the other.
2028 */
2029 public boolean overrideEquivalent(Type t, Type s) {
2030 return hasSameArgs(t, s) ||
2031 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2032 }
2034 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2035 class ImplementationCache {
2037 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2038 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2040 class Entry {
2041 final MethodSymbol cachedImpl;
2042 final Filter<Symbol> implFilter;
2043 final boolean checkResult;
2044 final int prevMark;
2046 public Entry(MethodSymbol cachedImpl,
2047 Filter<Symbol> scopeFilter,
2048 boolean checkResult,
2049 int prevMark) {
2050 this.cachedImpl = cachedImpl;
2051 this.implFilter = scopeFilter;
2052 this.checkResult = checkResult;
2053 this.prevMark = prevMark;
2054 }
2056 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2057 return this.implFilter == scopeFilter &&
2058 this.checkResult == checkResult &&
2059 this.prevMark == mark;
2060 }
2061 }
2063 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2064 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2065 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2066 if (cache == null) {
2067 cache = new HashMap<TypeSymbol, Entry>();
2068 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2069 }
2070 Entry e = cache.get(origin);
2071 CompoundScope members = membersClosure(origin.type, true);
2072 if (e == null ||
2073 !e.matches(implFilter, checkResult, members.getMark())) {
2074 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2075 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2076 return impl;
2077 }
2078 else {
2079 return e.cachedImpl;
2080 }
2081 }
2083 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2084 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2085 while (t.tag == TYPEVAR)
2086 t = t.getUpperBound();
2087 TypeSymbol c = t.tsym;
2088 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2089 e.scope != null;
2090 e = e.next(implFilter)) {
2091 if (e.sym != null &&
2092 e.sym.overrides(ms, origin, Types.this, checkResult))
2093 return (MethodSymbol)e.sym;
2094 }
2095 }
2096 return null;
2097 }
2098 }
2100 private ImplementationCache implCache = new ImplementationCache();
2102 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2103 return implCache.get(ms, origin, checkResult, implFilter);
2104 }
2105 // </editor-fold>
2107 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2108 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2110 private WeakHashMap<TypeSymbol, Entry> _map =
2111 new WeakHashMap<TypeSymbol, Entry>();
2113 class Entry {
2114 final boolean skipInterfaces;
2115 final CompoundScope compoundScope;
2117 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2118 this.skipInterfaces = skipInterfaces;
2119 this.compoundScope = compoundScope;
2120 }
2122 boolean matches(boolean skipInterfaces) {
2123 return this.skipInterfaces == skipInterfaces;
2124 }
2125 }
2127 List<TypeSymbol> seenTypes = List.nil();
2129 /** members closure visitor methods **/
2131 public CompoundScope visitType(Type t, Boolean skipInterface) {
2132 return null;
2133 }
2135 @Override
2136 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2137 if (seenTypes.contains(t.tsym)) {
2138 //this is possible when an interface is implemented in multiple
2139 //superclasses, or when a classs hierarchy is circular - in such
2140 //cases we don't need to recurse (empty scope is returned)
2141 return new CompoundScope(t.tsym);
2142 }
2143 try {
2144 seenTypes = seenTypes.prepend(t.tsym);
2145 ClassSymbol csym = (ClassSymbol)t.tsym;
2146 Entry e = _map.get(csym);
2147 if (e == null || !e.matches(skipInterface)) {
2148 CompoundScope membersClosure = new CompoundScope(csym);
2149 if (!skipInterface) {
2150 for (Type i : interfaces(t)) {
2151 membersClosure.addSubScope(visit(i, skipInterface));
2152 }
2153 }
2154 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2155 membersClosure.addSubScope(csym.members());
2156 e = new Entry(skipInterface, membersClosure);
2157 _map.put(csym, e);
2158 }
2159 return e.compoundScope;
2160 }
2161 finally {
2162 seenTypes = seenTypes.tail;
2163 }
2164 }
2166 @Override
2167 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2168 return visit(t.getUpperBound(), skipInterface);
2169 }
2170 }
2172 private MembersClosureCache membersCache = new MembersClosureCache();
2174 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2175 return membersCache.visit(site, skipInterface);
2176 }
2177 // </editor-fold>
2179 /**
2180 * Does t have the same arguments as s? It is assumed that both
2181 * types are (possibly polymorphic) method types. Monomorphic
2182 * method types "have the same arguments", if their argument lists
2183 * are equal. Polymorphic method types "have the same arguments",
2184 * if they have the same arguments after renaming all type
2185 * variables of one to corresponding type variables in the other,
2186 * where correspondence is by position in the type parameter list.
2187 */
2188 public boolean hasSameArgs(Type t, Type s) {
2189 return hasSameArgs(t, s, true);
2190 }
2192 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2193 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2194 }
2196 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2197 return hasSameArgs.visit(t, s);
2198 }
2199 // where
2200 private class HasSameArgs extends TypeRelation {
2202 boolean strict;
2204 public HasSameArgs(boolean strict) {
2205 this.strict = strict;
2206 }
2208 public Boolean visitType(Type t, Type s) {
2209 throw new AssertionError();
2210 }
2212 @Override
2213 public Boolean visitMethodType(MethodType t, Type s) {
2214 return s.tag == METHOD
2215 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2216 }
2218 @Override
2219 public Boolean visitForAll(ForAll t, Type s) {
2220 if (s.tag != FORALL)
2221 return strict ? false : visitMethodType(t.asMethodType(), s);
2223 ForAll forAll = (ForAll)s;
2224 return hasSameBounds(t, forAll)
2225 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2226 }
2228 @Override
2229 public Boolean visitErrorType(ErrorType t, Type s) {
2230 return false;
2231 }
2232 };
2234 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2235 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2237 // </editor-fold>
2239 // <editor-fold defaultstate="collapsed" desc="subst">
2240 public List<Type> subst(List<Type> ts,
2241 List<Type> from,
2242 List<Type> to) {
2243 return new Subst(from, to).subst(ts);
2244 }
2246 /**
2247 * Substitute all occurrences of a type in `from' with the
2248 * corresponding type in `to' in 't'. Match lists `from' and `to'
2249 * from the right: If lists have different length, discard leading
2250 * elements of the longer list.
2251 */
2252 public Type subst(Type t, List<Type> from, List<Type> to) {
2253 return new Subst(from, to).subst(t);
2254 }
2256 private class Subst extends UnaryVisitor<Type> {
2257 List<Type> from;
2258 List<Type> to;
2260 public Subst(List<Type> from, List<Type> to) {
2261 int fromLength = from.length();
2262 int toLength = to.length();
2263 while (fromLength > toLength) {
2264 fromLength--;
2265 from = from.tail;
2266 }
2267 while (fromLength < toLength) {
2268 toLength--;
2269 to = to.tail;
2270 }
2271 this.from = from;
2272 this.to = to;
2273 }
2275 Type subst(Type t) {
2276 if (from.tail == null)
2277 return t;
2278 else
2279 return visit(t);
2280 }
2282 List<Type> subst(List<Type> ts) {
2283 if (from.tail == null)
2284 return ts;
2285 boolean wild = false;
2286 if (ts.nonEmpty() && from.nonEmpty()) {
2287 Type head1 = subst(ts.head);
2288 List<Type> tail1 = subst(ts.tail);
2289 if (head1 != ts.head || tail1 != ts.tail)
2290 return tail1.prepend(head1);
2291 }
2292 return ts;
2293 }
2295 public Type visitType(Type t, Void ignored) {
2296 return t;
2297 }
2299 @Override
2300 public Type visitMethodType(MethodType t, Void ignored) {
2301 List<Type> argtypes = subst(t.argtypes);
2302 Type restype = subst(t.restype);
2303 List<Type> thrown = subst(t.thrown);
2304 if (argtypes == t.argtypes &&
2305 restype == t.restype &&
2306 thrown == t.thrown)
2307 return t;
2308 else
2309 return new MethodType(argtypes, restype, thrown, t.tsym);
2310 }
2312 @Override
2313 public Type visitTypeVar(TypeVar t, Void ignored) {
2314 for (List<Type> from = this.from, to = this.to;
2315 from.nonEmpty();
2316 from = from.tail, to = to.tail) {
2317 if (t == from.head) {
2318 return to.head.withTypeVar(t);
2319 }
2320 }
2321 return t;
2322 }
2324 @Override
2325 public Type visitClassType(ClassType t, Void ignored) {
2326 if (!t.isCompound()) {
2327 List<Type> typarams = t.getTypeArguments();
2328 List<Type> typarams1 = subst(typarams);
2329 Type outer = t.getEnclosingType();
2330 Type outer1 = subst(outer);
2331 if (typarams1 == typarams && outer1 == outer)
2332 return t;
2333 else
2334 return new ClassType(outer1, typarams1, t.tsym);
2335 } else {
2336 Type st = subst(supertype(t));
2337 List<Type> is = upperBounds(subst(interfaces(t)));
2338 if (st == supertype(t) && is == interfaces(t))
2339 return t;
2340 else
2341 return makeCompoundType(is.prepend(st));
2342 }
2343 }
2345 @Override
2346 public Type visitWildcardType(WildcardType t, Void ignored) {
2347 Type bound = t.type;
2348 if (t.kind != BoundKind.UNBOUND)
2349 bound = subst(bound);
2350 if (bound == t.type) {
2351 return t;
2352 } else {
2353 if (t.isExtendsBound() && bound.isExtendsBound())
2354 bound = upperBound(bound);
2355 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2356 }
2357 }
2359 @Override
2360 public Type visitArrayType(ArrayType t, Void ignored) {
2361 Type elemtype = subst(t.elemtype);
2362 if (elemtype == t.elemtype)
2363 return t;
2364 else
2365 return new ArrayType(upperBound(elemtype), t.tsym);
2366 }
2368 @Override
2369 public Type visitForAll(ForAll t, Void ignored) {
2370 if (Type.containsAny(to, t.tvars)) {
2371 //perform alpha-renaming of free-variables in 't'
2372 //if 'to' types contain variables that are free in 't'
2373 List<Type> freevars = newInstances(t.tvars);
2374 t = new ForAll(freevars,
2375 Types.this.subst(t.qtype, t.tvars, freevars));
2376 }
2377 List<Type> tvars1 = substBounds(t.tvars, from, to);
2378 Type qtype1 = subst(t.qtype);
2379 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2380 return t;
2381 } else if (tvars1 == t.tvars) {
2382 return new ForAll(tvars1, qtype1);
2383 } else {
2384 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2385 }
2386 }
2388 @Override
2389 public Type visitErrorType(ErrorType t, Void ignored) {
2390 return t;
2391 }
2392 }
2394 public List<Type> substBounds(List<Type> tvars,
2395 List<Type> from,
2396 List<Type> to) {
2397 if (tvars.isEmpty())
2398 return tvars;
2399 ListBuffer<Type> newBoundsBuf = lb();
2400 boolean changed = false;
2401 // calculate new bounds
2402 for (Type t : tvars) {
2403 TypeVar tv = (TypeVar) t;
2404 Type bound = subst(tv.bound, from, to);
2405 if (bound != tv.bound)
2406 changed = true;
2407 newBoundsBuf.append(bound);
2408 }
2409 if (!changed)
2410 return tvars;
2411 ListBuffer<Type> newTvars = lb();
2412 // create new type variables without bounds
2413 for (Type t : tvars) {
2414 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2415 }
2416 // the new bounds should use the new type variables in place
2417 // of the old
2418 List<Type> newBounds = newBoundsBuf.toList();
2419 from = tvars;
2420 to = newTvars.toList();
2421 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2422 newBounds.head = subst(newBounds.head, from, to);
2423 }
2424 newBounds = newBoundsBuf.toList();
2425 // set the bounds of new type variables to the new bounds
2426 for (Type t : newTvars.toList()) {
2427 TypeVar tv = (TypeVar) t;
2428 tv.bound = newBounds.head;
2429 newBounds = newBounds.tail;
2430 }
2431 return newTvars.toList();
2432 }
2434 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2435 Type bound1 = subst(t.bound, from, to);
2436 if (bound1 == t.bound)
2437 return t;
2438 else {
2439 // create new type variable without bounds
2440 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2441 // the new bound should use the new type variable in place
2442 // of the old
2443 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2444 return tv;
2445 }
2446 }
2447 // </editor-fold>
2449 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2450 /**
2451 * Does t have the same bounds for quantified variables as s?
2452 */
2453 boolean hasSameBounds(ForAll t, ForAll s) {
2454 List<Type> l1 = t.tvars;
2455 List<Type> l2 = s.tvars;
2456 while (l1.nonEmpty() && l2.nonEmpty() &&
2457 isSameType(l1.head.getUpperBound(),
2458 subst(l2.head.getUpperBound(),
2459 s.tvars,
2460 t.tvars))) {
2461 l1 = l1.tail;
2462 l2 = l2.tail;
2463 }
2464 return l1.isEmpty() && l2.isEmpty();
2465 }
2466 // </editor-fold>
2468 // <editor-fold defaultstate="collapsed" desc="newInstances">
2469 /** Create new vector of type variables from list of variables
2470 * changing all recursive bounds from old to new list.
2471 */
2472 public List<Type> newInstances(List<Type> tvars) {
2473 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2474 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2475 TypeVar tv = (TypeVar) l.head;
2476 tv.bound = subst(tv.bound, tvars, tvars1);
2477 }
2478 return tvars1;
2479 }
2480 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2481 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2482 };
2483 // </editor-fold>
2485 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2486 return original.accept(methodWithParameters, newParams);
2487 }
2488 // where
2489 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2490 public Type visitType(Type t, List<Type> newParams) {
2491 throw new IllegalArgumentException("Not a method type: " + t);
2492 }
2493 public Type visitMethodType(MethodType t, List<Type> newParams) {
2494 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2495 }
2496 public Type visitForAll(ForAll t, List<Type> newParams) {
2497 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2498 }
2499 };
2501 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2502 return original.accept(methodWithThrown, newThrown);
2503 }
2504 // where
2505 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2506 public Type visitType(Type t, List<Type> newThrown) {
2507 throw new IllegalArgumentException("Not a method type: " + t);
2508 }
2509 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2510 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2511 }
2512 public Type visitForAll(ForAll t, List<Type> newThrown) {
2513 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2514 }
2515 };
2517 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2518 return original.accept(methodWithReturn, newReturn);
2519 }
2520 // where
2521 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2522 public Type visitType(Type t, Type newReturn) {
2523 throw new IllegalArgumentException("Not a method type: " + t);
2524 }
2525 public Type visitMethodType(MethodType t, Type newReturn) {
2526 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2527 }
2528 public Type visitForAll(ForAll t, Type newReturn) {
2529 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2530 }
2531 };
2533 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2534 public Type createErrorType(Type originalType) {
2535 return new ErrorType(originalType, syms.errSymbol);
2536 }
2538 public Type createErrorType(ClassSymbol c, Type originalType) {
2539 return new ErrorType(c, originalType);
2540 }
2542 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2543 return new ErrorType(name, container, originalType);
2544 }
2545 // </editor-fold>
2547 // <editor-fold defaultstate="collapsed" desc="rank">
2548 /**
2549 * The rank of a class is the length of the longest path between
2550 * the class and java.lang.Object in the class inheritance
2551 * graph. Undefined for all but reference types.
2552 */
2553 public int rank(Type t) {
2554 switch(t.tag) {
2555 case CLASS: {
2556 ClassType cls = (ClassType)t;
2557 if (cls.rank_field < 0) {
2558 Name fullname = cls.tsym.getQualifiedName();
2559 if (fullname == names.java_lang_Object)
2560 cls.rank_field = 0;
2561 else {
2562 int r = rank(supertype(cls));
2563 for (List<Type> l = interfaces(cls);
2564 l.nonEmpty();
2565 l = l.tail) {
2566 if (rank(l.head) > r)
2567 r = rank(l.head);
2568 }
2569 cls.rank_field = r + 1;
2570 }
2571 }
2572 return cls.rank_field;
2573 }
2574 case TYPEVAR: {
2575 TypeVar tvar = (TypeVar)t;
2576 if (tvar.rank_field < 0) {
2577 int r = rank(supertype(tvar));
2578 for (List<Type> l = interfaces(tvar);
2579 l.nonEmpty();
2580 l = l.tail) {
2581 if (rank(l.head) > r) r = rank(l.head);
2582 }
2583 tvar.rank_field = r + 1;
2584 }
2585 return tvar.rank_field;
2586 }
2587 case ERROR:
2588 return 0;
2589 default:
2590 throw new AssertionError();
2591 }
2592 }
2593 // </editor-fold>
2595 /**
2596 * Helper method for generating a string representation of a given type
2597 * accordingly to a given locale
2598 */
2599 public String toString(Type t, Locale locale) {
2600 return Printer.createStandardPrinter(messages).visit(t, locale);
2601 }
2603 /**
2604 * Helper method for generating a string representation of a given type
2605 * accordingly to a given locale
2606 */
2607 public String toString(Symbol t, Locale locale) {
2608 return Printer.createStandardPrinter(messages).visit(t, locale);
2609 }
2611 // <editor-fold defaultstate="collapsed" desc="toString">
2612 /**
2613 * This toString is slightly more descriptive than the one on Type.
2614 *
2615 * @deprecated Types.toString(Type t, Locale l) provides better support
2616 * for localization
2617 */
2618 @Deprecated
2619 public String toString(Type t) {
2620 if (t.tag == FORALL) {
2621 ForAll forAll = (ForAll)t;
2622 return typaramsString(forAll.tvars) + forAll.qtype;
2623 }
2624 return "" + t;
2625 }
2626 // where
2627 private String typaramsString(List<Type> tvars) {
2628 StringBuilder s = new StringBuilder();
2629 s.append('<');
2630 boolean first = true;
2631 for (Type t : tvars) {
2632 if (!first) s.append(", ");
2633 first = false;
2634 appendTyparamString(((TypeVar)t), s);
2635 }
2636 s.append('>');
2637 return s.toString();
2638 }
2639 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2640 buf.append(t);
2641 if (t.bound == null ||
2642 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2643 return;
2644 buf.append(" extends "); // Java syntax; no need for i18n
2645 Type bound = t.bound;
2646 if (!bound.isCompound()) {
2647 buf.append(bound);
2648 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2649 buf.append(supertype(t));
2650 for (Type intf : interfaces(t)) {
2651 buf.append('&');
2652 buf.append(intf);
2653 }
2654 } else {
2655 // No superclass was given in bounds.
2656 // In this case, supertype is Object, erasure is first interface.
2657 boolean first = true;
2658 for (Type intf : interfaces(t)) {
2659 if (!first) buf.append('&');
2660 first = false;
2661 buf.append(intf);
2662 }
2663 }
2664 }
2665 // </editor-fold>
2667 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2668 /**
2669 * A cache for closures.
2670 *
2671 * <p>A closure is a list of all the supertypes and interfaces of
2672 * a class or interface type, ordered by ClassSymbol.precedes
2673 * (that is, subclasses come first, arbitrary but fixed
2674 * otherwise).
2675 */
2676 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2678 /**
2679 * Returns the closure of a class or interface type.
2680 */
2681 public List<Type> closure(Type t) {
2682 List<Type> cl = closureCache.get(t);
2683 if (cl == null) {
2684 Type st = supertype(t);
2685 if (!t.isCompound()) {
2686 if (st.tag == CLASS) {
2687 cl = insert(closure(st), t);
2688 } else if (st.tag == TYPEVAR) {
2689 cl = closure(st).prepend(t);
2690 } else {
2691 cl = List.of(t);
2692 }
2693 } else {
2694 cl = closure(supertype(t));
2695 }
2696 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2697 cl = union(cl, closure(l.head));
2698 closureCache.put(t, cl);
2699 }
2700 return cl;
2701 }
2703 /**
2704 * Insert a type in a closure
2705 */
2706 public List<Type> insert(List<Type> cl, Type t) {
2707 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2708 return cl.prepend(t);
2709 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2710 return insert(cl.tail, t).prepend(cl.head);
2711 } else {
2712 return cl;
2713 }
2714 }
2716 /**
2717 * Form the union of two closures
2718 */
2719 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2720 if (cl1.isEmpty()) {
2721 return cl2;
2722 } else if (cl2.isEmpty()) {
2723 return cl1;
2724 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2725 return union(cl1.tail, cl2).prepend(cl1.head);
2726 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2727 return union(cl1, cl2.tail).prepend(cl2.head);
2728 } else {
2729 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2730 }
2731 }
2733 /**
2734 * Intersect two closures
2735 */
2736 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2737 if (cl1 == cl2)
2738 return cl1;
2739 if (cl1.isEmpty() || cl2.isEmpty())
2740 return List.nil();
2741 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2742 return intersect(cl1.tail, cl2);
2743 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2744 return intersect(cl1, cl2.tail);
2745 if (isSameType(cl1.head, cl2.head))
2746 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2747 if (cl1.head.tsym == cl2.head.tsym &&
2748 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2749 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2750 Type merge = merge(cl1.head,cl2.head);
2751 return intersect(cl1.tail, cl2.tail).prepend(merge);
2752 }
2753 if (cl1.head.isRaw() || cl2.head.isRaw())
2754 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2755 }
2756 return intersect(cl1.tail, cl2.tail);
2757 }
2758 // where
2759 class TypePair {
2760 final Type t1;
2761 final Type t2;
2762 TypePair(Type t1, Type t2) {
2763 this.t1 = t1;
2764 this.t2 = t2;
2765 }
2766 @Override
2767 public int hashCode() {
2768 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2769 }
2770 @Override
2771 public boolean equals(Object obj) {
2772 if (!(obj instanceof TypePair))
2773 return false;
2774 TypePair typePair = (TypePair)obj;
2775 return isSameType(t1, typePair.t1)
2776 && isSameType(t2, typePair.t2);
2777 }
2778 }
2779 Set<TypePair> mergeCache = new HashSet<TypePair>();
2780 private Type merge(Type c1, Type c2) {
2781 ClassType class1 = (ClassType) c1;
2782 List<Type> act1 = class1.getTypeArguments();
2783 ClassType class2 = (ClassType) c2;
2784 List<Type> act2 = class2.getTypeArguments();
2785 ListBuffer<Type> merged = new ListBuffer<Type>();
2786 List<Type> typarams = class1.tsym.type.getTypeArguments();
2788 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2789 if (containsType(act1.head, act2.head)) {
2790 merged.append(act1.head);
2791 } else if (containsType(act2.head, act1.head)) {
2792 merged.append(act2.head);
2793 } else {
2794 TypePair pair = new TypePair(c1, c2);
2795 Type m;
2796 if (mergeCache.add(pair)) {
2797 m = new WildcardType(lub(upperBound(act1.head),
2798 upperBound(act2.head)),
2799 BoundKind.EXTENDS,
2800 syms.boundClass);
2801 mergeCache.remove(pair);
2802 } else {
2803 m = new WildcardType(syms.objectType,
2804 BoundKind.UNBOUND,
2805 syms.boundClass);
2806 }
2807 merged.append(m.withTypeVar(typarams.head));
2808 }
2809 act1 = act1.tail;
2810 act2 = act2.tail;
2811 typarams = typarams.tail;
2812 }
2813 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2814 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2815 }
2817 /**
2818 * Return the minimum type of a closure, a compound type if no
2819 * unique minimum exists.
2820 */
2821 private Type compoundMin(List<Type> cl) {
2822 if (cl.isEmpty()) return syms.objectType;
2823 List<Type> compound = closureMin(cl);
2824 if (compound.isEmpty())
2825 return null;
2826 else if (compound.tail.isEmpty())
2827 return compound.head;
2828 else
2829 return makeCompoundType(compound);
2830 }
2832 /**
2833 * Return the minimum types of a closure, suitable for computing
2834 * compoundMin or glb.
2835 */
2836 private List<Type> closureMin(List<Type> cl) {
2837 ListBuffer<Type> classes = lb();
2838 ListBuffer<Type> interfaces = lb();
2839 while (!cl.isEmpty()) {
2840 Type current = cl.head;
2841 if (current.isInterface())
2842 interfaces.append(current);
2843 else
2844 classes.append(current);
2845 ListBuffer<Type> candidates = lb();
2846 for (Type t : cl.tail) {
2847 if (!isSubtypeNoCapture(current, t))
2848 candidates.append(t);
2849 }
2850 cl = candidates.toList();
2851 }
2852 return classes.appendList(interfaces).toList();
2853 }
2855 /**
2856 * Return the least upper bound of pair of types. if the lub does
2857 * not exist return null.
2858 */
2859 public Type lub(Type t1, Type t2) {
2860 return lub(List.of(t1, t2));
2861 }
2863 /**
2864 * Return the least upper bound (lub) of set of types. If the lub
2865 * does not exist return the type of null (bottom).
2866 */
2867 public Type lub(List<Type> ts) {
2868 final int ARRAY_BOUND = 1;
2869 final int CLASS_BOUND = 2;
2870 int boundkind = 0;
2871 for (Type t : ts) {
2872 switch (t.tag) {
2873 case CLASS:
2874 boundkind |= CLASS_BOUND;
2875 break;
2876 case ARRAY:
2877 boundkind |= ARRAY_BOUND;
2878 break;
2879 case TYPEVAR:
2880 do {
2881 t = t.getUpperBound();
2882 } while (t.tag == TYPEVAR);
2883 if (t.tag == ARRAY) {
2884 boundkind |= ARRAY_BOUND;
2885 } else {
2886 boundkind |= CLASS_BOUND;
2887 }
2888 break;
2889 default:
2890 if (t.isPrimitive())
2891 return syms.errType;
2892 }
2893 }
2894 switch (boundkind) {
2895 case 0:
2896 return syms.botType;
2898 case ARRAY_BOUND:
2899 // calculate lub(A[], B[])
2900 List<Type> elements = Type.map(ts, elemTypeFun);
2901 for (Type t : elements) {
2902 if (t.isPrimitive()) {
2903 // if a primitive type is found, then return
2904 // arraySuperType unless all the types are the
2905 // same
2906 Type first = ts.head;
2907 for (Type s : ts.tail) {
2908 if (!isSameType(first, s)) {
2909 // lub(int[], B[]) is Cloneable & Serializable
2910 return arraySuperType();
2911 }
2912 }
2913 // all the array types are the same, return one
2914 // lub(int[], int[]) is int[]
2915 return first;
2916 }
2917 }
2918 // lub(A[], B[]) is lub(A, B)[]
2919 return new ArrayType(lub(elements), syms.arrayClass);
2921 case CLASS_BOUND:
2922 // calculate lub(A, B)
2923 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2924 ts = ts.tail;
2925 Assert.check(!ts.isEmpty());
2926 //step 1 - compute erased candidate set (EC)
2927 List<Type> cl = erasedSupertypes(ts.head);
2928 for (Type t : ts.tail) {
2929 if (t.tag == CLASS || t.tag == TYPEVAR)
2930 cl = intersect(cl, erasedSupertypes(t));
2931 }
2932 //step 2 - compute minimal erased candidate set (MEC)
2933 List<Type> mec = closureMin(cl);
2934 //step 3 - for each element G in MEC, compute lci(Inv(G))
2935 List<Type> candidates = List.nil();
2936 for (Type erasedSupertype : mec) {
2937 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
2938 for (Type t : ts) {
2939 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
2940 }
2941 candidates = candidates.appendList(lci);
2942 }
2943 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
2944 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
2945 return compoundMin(candidates);
2947 default:
2948 // calculate lub(A, B[])
2949 List<Type> classes = List.of(arraySuperType());
2950 for (Type t : ts) {
2951 if (t.tag != ARRAY) // Filter out any arrays
2952 classes = classes.prepend(t);
2953 }
2954 // lub(A, B[]) is lub(A, arraySuperType)
2955 return lub(classes);
2956 }
2957 }
2958 // where
2959 List<Type> erasedSupertypes(Type t) {
2960 ListBuffer<Type> buf = lb();
2961 for (Type sup : closure(t)) {
2962 if (sup.tag == TYPEVAR) {
2963 buf.append(sup);
2964 } else {
2965 buf.append(erasure(sup));
2966 }
2967 }
2968 return buf.toList();
2969 }
2971 private Type arraySuperType = null;
2972 private Type arraySuperType() {
2973 // initialized lazily to avoid problems during compiler startup
2974 if (arraySuperType == null) {
2975 synchronized (this) {
2976 if (arraySuperType == null) {
2977 // JLS 10.8: all arrays implement Cloneable and Serializable.
2978 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2979 syms.cloneableType),
2980 syms.objectType);
2981 }
2982 }
2983 }
2984 return arraySuperType;
2985 }
2986 // </editor-fold>
2988 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2989 public Type glb(List<Type> ts) {
2990 Type t1 = ts.head;
2991 for (Type t2 : ts.tail) {
2992 if (t1.isErroneous())
2993 return t1;
2994 t1 = glb(t1, t2);
2995 }
2996 return t1;
2997 }
2998 //where
2999 public Type glb(Type t, Type s) {
3000 if (s == null)
3001 return t;
3002 else if (t.isPrimitive() || s.isPrimitive())
3003 return syms.errType;
3004 else if (isSubtypeNoCapture(t, s))
3005 return t;
3006 else if (isSubtypeNoCapture(s, t))
3007 return s;
3009 List<Type> closure = union(closure(t), closure(s));
3010 List<Type> bounds = closureMin(closure);
3012 if (bounds.isEmpty()) { // length == 0
3013 return syms.objectType;
3014 } else if (bounds.tail.isEmpty()) { // length == 1
3015 return bounds.head;
3016 } else { // length > 1
3017 int classCount = 0;
3018 for (Type bound : bounds)
3019 if (!bound.isInterface())
3020 classCount++;
3021 if (classCount > 1)
3022 return createErrorType(t);
3023 }
3024 return makeCompoundType(bounds);
3025 }
3026 // </editor-fold>
3028 // <editor-fold defaultstate="collapsed" desc="hashCode">
3029 /**
3030 * Compute a hash code on a type.
3031 */
3032 public static int hashCode(Type t) {
3033 return hashCode.visit(t);
3034 }
3035 // where
3036 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3038 public Integer visitType(Type t, Void ignored) {
3039 return t.tag;
3040 }
3042 @Override
3043 public Integer visitClassType(ClassType t, Void ignored) {
3044 int result = visit(t.getEnclosingType());
3045 result *= 127;
3046 result += t.tsym.flatName().hashCode();
3047 for (Type s : t.getTypeArguments()) {
3048 result *= 127;
3049 result += visit(s);
3050 }
3051 return result;
3052 }
3054 @Override
3055 public Integer visitWildcardType(WildcardType t, Void ignored) {
3056 int result = t.kind.hashCode();
3057 if (t.type != null) {
3058 result *= 127;
3059 result += visit(t.type);
3060 }
3061 return result;
3062 }
3064 @Override
3065 public Integer visitArrayType(ArrayType t, Void ignored) {
3066 return visit(t.elemtype) + 12;
3067 }
3069 @Override
3070 public Integer visitTypeVar(TypeVar t, Void ignored) {
3071 return System.identityHashCode(t.tsym);
3072 }
3074 @Override
3075 public Integer visitUndetVar(UndetVar t, Void ignored) {
3076 return System.identityHashCode(t);
3077 }
3079 @Override
3080 public Integer visitErrorType(ErrorType t, Void ignored) {
3081 return 0;
3082 }
3083 };
3084 // </editor-fold>
3086 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3087 /**
3088 * Does t have a result that is a subtype of the result type of s,
3089 * suitable for covariant returns? It is assumed that both types
3090 * are (possibly polymorphic) method types. Monomorphic method
3091 * types are handled in the obvious way. Polymorphic method types
3092 * require renaming all type variables of one to corresponding
3093 * type variables in the other, where correspondence is by
3094 * position in the type parameter list. */
3095 public boolean resultSubtype(Type t, Type s, Warner warner) {
3096 List<Type> tvars = t.getTypeArguments();
3097 List<Type> svars = s.getTypeArguments();
3098 Type tres = t.getReturnType();
3099 Type sres = subst(s.getReturnType(), svars, tvars);
3100 return covariantReturnType(tres, sres, warner);
3101 }
3103 /**
3104 * Return-Type-Substitutable.
3105 * @jls section 8.4.5
3106 */
3107 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3108 if (hasSameArgs(r1, r2))
3109 return resultSubtype(r1, r2, Warner.noWarnings);
3110 else
3111 return covariantReturnType(r1.getReturnType(),
3112 erasure(r2.getReturnType()),
3113 Warner.noWarnings);
3114 }
3116 public boolean returnTypeSubstitutable(Type r1,
3117 Type r2, Type r2res,
3118 Warner warner) {
3119 if (isSameType(r1.getReturnType(), r2res))
3120 return true;
3121 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3122 return false;
3124 if (hasSameArgs(r1, r2))
3125 return covariantReturnType(r1.getReturnType(), r2res, warner);
3126 if (!allowCovariantReturns)
3127 return false;
3128 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3129 return true;
3130 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3131 return false;
3132 warner.warn(LintCategory.UNCHECKED);
3133 return true;
3134 }
3136 /**
3137 * Is t an appropriate return type in an overrider for a
3138 * method that returns s?
3139 */
3140 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3141 return
3142 isSameType(t, s) ||
3143 allowCovariantReturns &&
3144 !t.isPrimitive() &&
3145 !s.isPrimitive() &&
3146 isAssignable(t, s, warner);
3147 }
3148 // </editor-fold>
3150 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3151 /**
3152 * Return the class that boxes the given primitive.
3153 */
3154 public ClassSymbol boxedClass(Type t) {
3155 return reader.enterClass(syms.boxedName[t.tag]);
3156 }
3158 /**
3159 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3160 */
3161 public Type boxedTypeOrType(Type t) {
3162 return t.isPrimitive() ?
3163 boxedClass(t).type :
3164 t;
3165 }
3167 /**
3168 * Return the primitive type corresponding to a boxed type.
3169 */
3170 public Type unboxedType(Type t) {
3171 if (allowBoxing) {
3172 for (int i=0; i<syms.boxedName.length; i++) {
3173 Name box = syms.boxedName[i];
3174 if (box != null &&
3175 asSuper(t, reader.enterClass(box)) != null)
3176 return syms.typeOfTag[i];
3177 }
3178 }
3179 return Type.noType;
3180 }
3181 // </editor-fold>
3183 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3184 /*
3185 * JLS 5.1.10 Capture Conversion:
3186 *
3187 * Let G name a generic type declaration with n formal type
3188 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3189 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3190 * where, for 1 <= i <= n:
3191 *
3192 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3193 * Si is a fresh type variable whose upper bound is
3194 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3195 * type.
3196 *
3197 * + If Ti is a wildcard type argument of the form ? extends Bi,
3198 * then Si is a fresh type variable whose upper bound is
3199 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3200 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3201 * a compile-time error if for any two classes (not interfaces)
3202 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3203 *
3204 * + If Ti is a wildcard type argument of the form ? super Bi,
3205 * then Si is a fresh type variable whose upper bound is
3206 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3207 *
3208 * + Otherwise, Si = Ti.
3209 *
3210 * Capture conversion on any type other than a parameterized type
3211 * (4.5) acts as an identity conversion (5.1.1). Capture
3212 * conversions never require a special action at run time and
3213 * therefore never throw an exception at run time.
3214 *
3215 * Capture conversion is not applied recursively.
3216 */
3217 /**
3218 * Capture conversion as specified by the JLS.
3219 */
3221 public List<Type> capture(List<Type> ts) {
3222 List<Type> buf = List.nil();
3223 for (Type t : ts) {
3224 buf = buf.prepend(capture(t));
3225 }
3226 return buf.reverse();
3227 }
3228 public Type capture(Type t) {
3229 if (t.tag != CLASS)
3230 return t;
3231 if (t.getEnclosingType() != Type.noType) {
3232 Type capturedEncl = capture(t.getEnclosingType());
3233 if (capturedEncl != t.getEnclosingType()) {
3234 Type type1 = memberType(capturedEncl, t.tsym);
3235 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3236 }
3237 }
3238 ClassType cls = (ClassType)t;
3239 if (cls.isRaw() || !cls.isParameterized())
3240 return cls;
3242 ClassType G = (ClassType)cls.asElement().asType();
3243 List<Type> A = G.getTypeArguments();
3244 List<Type> T = cls.getTypeArguments();
3245 List<Type> S = freshTypeVariables(T);
3247 List<Type> currentA = A;
3248 List<Type> currentT = T;
3249 List<Type> currentS = S;
3250 boolean captured = false;
3251 while (!currentA.isEmpty() &&
3252 !currentT.isEmpty() &&
3253 !currentS.isEmpty()) {
3254 if (currentS.head != currentT.head) {
3255 captured = true;
3256 WildcardType Ti = (WildcardType)currentT.head;
3257 Type Ui = currentA.head.getUpperBound();
3258 CapturedType Si = (CapturedType)currentS.head;
3259 if (Ui == null)
3260 Ui = syms.objectType;
3261 switch (Ti.kind) {
3262 case UNBOUND:
3263 Si.bound = subst(Ui, A, S);
3264 Si.lower = syms.botType;
3265 break;
3266 case EXTENDS:
3267 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3268 Si.lower = syms.botType;
3269 break;
3270 case SUPER:
3271 Si.bound = subst(Ui, A, S);
3272 Si.lower = Ti.getSuperBound();
3273 break;
3274 }
3275 if (Si.bound == Si.lower)
3276 currentS.head = Si.bound;
3277 }
3278 currentA = currentA.tail;
3279 currentT = currentT.tail;
3280 currentS = currentS.tail;
3281 }
3282 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3283 return erasure(t); // some "rare" type involved
3285 if (captured)
3286 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3287 else
3288 return t;
3289 }
3290 // where
3291 public List<Type> freshTypeVariables(List<Type> types) {
3292 ListBuffer<Type> result = lb();
3293 for (Type t : types) {
3294 if (t.tag == WILDCARD) {
3295 Type bound = ((WildcardType)t).getExtendsBound();
3296 if (bound == null)
3297 bound = syms.objectType;
3298 result.append(new CapturedType(capturedName,
3299 syms.noSymbol,
3300 bound,
3301 syms.botType,
3302 (WildcardType)t));
3303 } else {
3304 result.append(t);
3305 }
3306 }
3307 return result.toList();
3308 }
3309 // </editor-fold>
3311 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3312 private List<Type> upperBounds(List<Type> ss) {
3313 if (ss.isEmpty()) return ss;
3314 Type head = upperBound(ss.head);
3315 List<Type> tail = upperBounds(ss.tail);
3316 if (head != ss.head || tail != ss.tail)
3317 return tail.prepend(head);
3318 else
3319 return ss;
3320 }
3322 private boolean sideCast(Type from, Type to, Warner warn) {
3323 // We are casting from type $from$ to type $to$, which are
3324 // non-final unrelated types. This method
3325 // tries to reject a cast by transferring type parameters
3326 // from $to$ to $from$ by common superinterfaces.
3327 boolean reverse = false;
3328 Type target = to;
3329 if ((to.tsym.flags() & INTERFACE) == 0) {
3330 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3331 reverse = true;
3332 to = from;
3333 from = target;
3334 }
3335 List<Type> commonSupers = superClosure(to, erasure(from));
3336 boolean giveWarning = commonSupers.isEmpty();
3337 // The arguments to the supers could be unified here to
3338 // get a more accurate analysis
3339 while (commonSupers.nonEmpty()) {
3340 Type t1 = asSuper(from, commonSupers.head.tsym);
3341 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3342 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3343 return false;
3344 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3345 commonSupers = commonSupers.tail;
3346 }
3347 if (giveWarning && !isReifiable(reverse ? from : to))
3348 warn.warn(LintCategory.UNCHECKED);
3349 if (!allowCovariantReturns)
3350 // reject if there is a common method signature with
3351 // incompatible return types.
3352 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3353 return true;
3354 }
3356 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3357 // We are casting from type $from$ to type $to$, which are
3358 // unrelated types one of which is final and the other of
3359 // which is an interface. This method
3360 // tries to reject a cast by transferring type parameters
3361 // from the final class to the interface.
3362 boolean reverse = false;
3363 Type target = to;
3364 if ((to.tsym.flags() & INTERFACE) == 0) {
3365 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3366 reverse = true;
3367 to = from;
3368 from = target;
3369 }
3370 Assert.check((from.tsym.flags() & FINAL) != 0);
3371 Type t1 = asSuper(from, to.tsym);
3372 if (t1 == null) return false;
3373 Type t2 = to;
3374 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3375 return false;
3376 if (!allowCovariantReturns)
3377 // reject if there is a common method signature with
3378 // incompatible return types.
3379 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3380 if (!isReifiable(target) &&
3381 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3382 warn.warn(LintCategory.UNCHECKED);
3383 return true;
3384 }
3386 private boolean giveWarning(Type from, Type to) {
3387 Type subFrom = asSub(from, to.tsym);
3388 return to.isParameterized() &&
3389 (!(isUnbounded(to) ||
3390 isSubtype(from, to) ||
3391 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3392 }
3394 private List<Type> superClosure(Type t, Type s) {
3395 List<Type> cl = List.nil();
3396 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3397 if (isSubtype(s, erasure(l.head))) {
3398 cl = insert(cl, l.head);
3399 } else {
3400 cl = union(cl, superClosure(l.head, s));
3401 }
3402 }
3403 return cl;
3404 }
3406 private boolean containsTypeEquivalent(Type t, Type s) {
3407 return
3408 isSameType(t, s) || // shortcut
3409 containsType(t, s) && containsType(s, t);
3410 }
3412 // <editor-fold defaultstate="collapsed" desc="adapt">
3413 /**
3414 * Adapt a type by computing a substitution which maps a source
3415 * type to a target type.
3416 *
3417 * @param source the source type
3418 * @param target the target type
3419 * @param from the type variables of the computed substitution
3420 * @param to the types of the computed substitution.
3421 */
3422 public void adapt(Type source,
3423 Type target,
3424 ListBuffer<Type> from,
3425 ListBuffer<Type> to) throws AdaptFailure {
3426 new Adapter(from, to).adapt(source, target);
3427 }
3429 class Adapter extends SimpleVisitor<Void, Type> {
3431 ListBuffer<Type> from;
3432 ListBuffer<Type> to;
3433 Map<Symbol,Type> mapping;
3435 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3436 this.from = from;
3437 this.to = to;
3438 mapping = new HashMap<Symbol,Type>();
3439 }
3441 public void adapt(Type source, Type target) throws AdaptFailure {
3442 visit(source, target);
3443 List<Type> fromList = from.toList();
3444 List<Type> toList = to.toList();
3445 while (!fromList.isEmpty()) {
3446 Type val = mapping.get(fromList.head.tsym);
3447 if (toList.head != val)
3448 toList.head = val;
3449 fromList = fromList.tail;
3450 toList = toList.tail;
3451 }
3452 }
3454 @Override
3455 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3456 if (target.tag == CLASS)
3457 adaptRecursive(source.allparams(), target.allparams());
3458 return null;
3459 }
3461 @Override
3462 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3463 if (target.tag == ARRAY)
3464 adaptRecursive(elemtype(source), elemtype(target));
3465 return null;
3466 }
3468 @Override
3469 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3470 if (source.isExtendsBound())
3471 adaptRecursive(upperBound(source), upperBound(target));
3472 else if (source.isSuperBound())
3473 adaptRecursive(lowerBound(source), lowerBound(target));
3474 return null;
3475 }
3477 @Override
3478 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3479 // Check to see if there is
3480 // already a mapping for $source$, in which case
3481 // the old mapping will be merged with the new
3482 Type val = mapping.get(source.tsym);
3483 if (val != null) {
3484 if (val.isSuperBound() && target.isSuperBound()) {
3485 val = isSubtype(lowerBound(val), lowerBound(target))
3486 ? target : val;
3487 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3488 val = isSubtype(upperBound(val), upperBound(target))
3489 ? val : target;
3490 } else if (!isSameType(val, target)) {
3491 throw new AdaptFailure();
3492 }
3493 } else {
3494 val = target;
3495 from.append(source);
3496 to.append(target);
3497 }
3498 mapping.put(source.tsym, val);
3499 return null;
3500 }
3502 @Override
3503 public Void visitType(Type source, Type target) {
3504 return null;
3505 }
3507 private Set<TypePair> cache = new HashSet<TypePair>();
3509 private void adaptRecursive(Type source, Type target) {
3510 TypePair pair = new TypePair(source, target);
3511 if (cache.add(pair)) {
3512 try {
3513 visit(source, target);
3514 } finally {
3515 cache.remove(pair);
3516 }
3517 }
3518 }
3520 private void adaptRecursive(List<Type> source, List<Type> target) {
3521 if (source.length() == target.length()) {
3522 while (source.nonEmpty()) {
3523 adaptRecursive(source.head, target.head);
3524 source = source.tail;
3525 target = target.tail;
3526 }
3527 }
3528 }
3529 }
3531 public static class AdaptFailure extends RuntimeException {
3532 static final long serialVersionUID = -7490231548272701566L;
3533 }
3535 private void adaptSelf(Type t,
3536 ListBuffer<Type> from,
3537 ListBuffer<Type> to) {
3538 try {
3539 //if (t.tsym.type != t)
3540 adapt(t.tsym.type, t, from, to);
3541 } catch (AdaptFailure ex) {
3542 // Adapt should never fail calculating a mapping from
3543 // t.tsym.type to t as there can be no merge problem.
3544 throw new AssertionError(ex);
3545 }
3546 }
3547 // </editor-fold>
3549 /**
3550 * Rewrite all type variables (universal quantifiers) in the given
3551 * type to wildcards (existential quantifiers). This is used to
3552 * determine if a cast is allowed. For example, if high is true
3553 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3554 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3555 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3556 * List<Integer>} with a warning.
3557 * @param t a type
3558 * @param high if true return an upper bound; otherwise a lower
3559 * bound
3560 * @param rewriteTypeVars only rewrite captured wildcards if false;
3561 * otherwise rewrite all type variables
3562 * @return the type rewritten with wildcards (existential
3563 * quantifiers) only
3564 */
3565 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3566 return new Rewriter(high, rewriteTypeVars).visit(t);
3567 }
3569 class Rewriter extends UnaryVisitor<Type> {
3571 boolean high;
3572 boolean rewriteTypeVars;
3574 Rewriter(boolean high, boolean rewriteTypeVars) {
3575 this.high = high;
3576 this.rewriteTypeVars = rewriteTypeVars;
3577 }
3579 @Override
3580 public Type visitClassType(ClassType t, Void s) {
3581 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3582 boolean changed = false;
3583 for (Type arg : t.allparams()) {
3584 Type bound = visit(arg);
3585 if (arg != bound) {
3586 changed = true;
3587 }
3588 rewritten.append(bound);
3589 }
3590 if (changed)
3591 return subst(t.tsym.type,
3592 t.tsym.type.allparams(),
3593 rewritten.toList());
3594 else
3595 return t;
3596 }
3598 public Type visitType(Type t, Void s) {
3599 return high ? upperBound(t) : lowerBound(t);
3600 }
3602 @Override
3603 public Type visitCapturedType(CapturedType t, Void s) {
3604 Type bound = visitWildcardType(t.wildcard, null);
3605 return (bound.contains(t)) ?
3606 erasure(bound) :
3607 bound;
3608 }
3610 @Override
3611 public Type visitTypeVar(TypeVar t, Void s) {
3612 if (rewriteTypeVars) {
3613 Type bound = high ?
3614 (t.bound.contains(t) ?
3615 erasure(t.bound) :
3616 visit(t.bound)) :
3617 syms.botType;
3618 return rewriteAsWildcardType(bound, t);
3619 }
3620 else
3621 return t;
3622 }
3624 @Override
3625 public Type visitWildcardType(WildcardType t, Void s) {
3626 Type bound = high ? t.getExtendsBound() :
3627 t.getSuperBound();
3628 if (bound == null)
3629 bound = high ? syms.objectType : syms.botType;
3630 return rewriteAsWildcardType(visit(bound), t.bound);
3631 }
3633 private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
3634 return high ?
3635 makeExtendsWildcard(B(bound), formal) :
3636 makeSuperWildcard(B(bound), formal);
3637 }
3639 Type B(Type t) {
3640 while (t.tag == WILDCARD) {
3641 WildcardType w = (WildcardType)t;
3642 t = high ?
3643 w.getExtendsBound() :
3644 w.getSuperBound();
3645 if (t == null) {
3646 t = high ? syms.objectType : syms.botType;
3647 }
3648 }
3649 return t;
3650 }
3651 }
3654 /**
3655 * Create a wildcard with the given upper (extends) bound; create
3656 * an unbounded wildcard if bound is Object.
3657 *
3658 * @param bound the upper bound
3659 * @param formal the formal type parameter that will be
3660 * substituted by the wildcard
3661 */
3662 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3663 if (bound == syms.objectType) {
3664 return new WildcardType(syms.objectType,
3665 BoundKind.UNBOUND,
3666 syms.boundClass,
3667 formal);
3668 } else {
3669 return new WildcardType(bound,
3670 BoundKind.EXTENDS,
3671 syms.boundClass,
3672 formal);
3673 }
3674 }
3676 /**
3677 * Create a wildcard with the given lower (super) bound; create an
3678 * unbounded wildcard if bound is bottom (type of {@code null}).
3679 *
3680 * @param bound the lower bound
3681 * @param formal the formal type parameter that will be
3682 * substituted by the wildcard
3683 */
3684 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3685 if (bound.tag == BOT) {
3686 return new WildcardType(syms.objectType,
3687 BoundKind.UNBOUND,
3688 syms.boundClass,
3689 formal);
3690 } else {
3691 return new WildcardType(bound,
3692 BoundKind.SUPER,
3693 syms.boundClass,
3694 formal);
3695 }
3696 }
3698 /**
3699 * A wrapper for a type that allows use in sets.
3700 */
3701 class SingletonType {
3702 final Type t;
3703 SingletonType(Type t) {
3704 this.t = t;
3705 }
3706 public int hashCode() {
3707 return Types.hashCode(t);
3708 }
3709 public boolean equals(Object obj) {
3710 return (obj instanceof SingletonType) &&
3711 isSameType(t, ((SingletonType)obj).t);
3712 }
3713 public String toString() {
3714 return t.toString();
3715 }
3716 }
3717 // </editor-fold>
3719 // <editor-fold defaultstate="collapsed" desc="Visitors">
3720 /**
3721 * A default visitor for types. All visitor methods except
3722 * visitType are implemented by delegating to visitType. Concrete
3723 * subclasses must provide an implementation of visitType and can
3724 * override other methods as needed.
3725 *
3726 * @param <R> the return type of the operation implemented by this
3727 * visitor; use Void if no return type is needed.
3728 * @param <S> the type of the second argument (the first being the
3729 * type itself) of the operation implemented by this visitor; use
3730 * Void if a second argument is not needed.
3731 */
3732 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3733 final public R visit(Type t, S s) { return t.accept(this, s); }
3734 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3735 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3736 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3737 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3738 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3739 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3740 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3741 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3742 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3743 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3744 }
3746 /**
3747 * A default visitor for symbols. All visitor methods except
3748 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3749 * subclasses must provide an implementation of visitSymbol and can
3750 * override other methods as needed.
3751 *
3752 * @param <R> the return type of the operation implemented by this
3753 * visitor; use Void if no return type is needed.
3754 * @param <S> the type of the second argument (the first being the
3755 * symbol itself) of the operation implemented by this visitor; use
3756 * Void if a second argument is not needed.
3757 */
3758 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3759 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3760 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3761 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3762 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3763 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3764 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3765 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3766 }
3768 /**
3769 * A <em>simple</em> visitor for types. This visitor is simple as
3770 * captured wildcards, for-all types (generic methods), and
3771 * undetermined type variables (part of inference) are hidden.
3772 * Captured wildcards are hidden by treating them as type
3773 * variables and the rest are hidden by visiting their qtypes.
3774 *
3775 * @param <R> the return type of the operation implemented by this
3776 * visitor; use Void if no return type is needed.
3777 * @param <S> the type of the second argument (the first being the
3778 * type itself) of the operation implemented by this visitor; use
3779 * Void if a second argument is not needed.
3780 */
3781 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3782 @Override
3783 public R visitCapturedType(CapturedType t, S s) {
3784 return visitTypeVar(t, s);
3785 }
3786 @Override
3787 public R visitForAll(ForAll t, S s) {
3788 return visit(t.qtype, s);
3789 }
3790 @Override
3791 public R visitUndetVar(UndetVar t, S s) {
3792 return visit(t.qtype, s);
3793 }
3794 }
3796 /**
3797 * A plain relation on types. That is a 2-ary function on the
3798 * form Type × Type → Boolean.
3799 * <!-- In plain text: Type x Type -> Boolean -->
3800 */
3801 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3803 /**
3804 * A convenience visitor for implementing operations that only
3805 * require one argument (the type itself), that is, unary
3806 * operations.
3807 *
3808 * @param <R> the return type of the operation implemented by this
3809 * visitor; use Void if no return type is needed.
3810 */
3811 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3812 final public R visit(Type t) { return t.accept(this, null); }
3813 }
3815 /**
3816 * A visitor for implementing a mapping from types to types. The
3817 * default behavior of this class is to implement the identity
3818 * mapping (mapping a type to itself). This can be overridden in
3819 * subclasses.
3820 *
3821 * @param <S> the type of the second argument (the first being the
3822 * type itself) of this mapping; use Void if a second argument is
3823 * not needed.
3824 */
3825 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3826 final public Type visit(Type t) { return t.accept(this, null); }
3827 public Type visitType(Type t, S s) { return t; }
3828 }
3829 // </editor-fold>
3832 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3834 public RetentionPolicy getRetention(Attribute.Compound a) {
3835 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3836 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3837 if (c != null) {
3838 Attribute value = c.member(names.value);
3839 if (value != null && value instanceof Attribute.Enum) {
3840 Name levelName = ((Attribute.Enum)value).value.name;
3841 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3842 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3843 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3844 else ;// /* fail soft */ throw new AssertionError(levelName);
3845 }
3846 }
3847 return vis;
3848 }
3849 // </editor-fold>
3850 }