Wed, 31 Aug 2011 16:11:28 +0100
7085024: internal error; cannot instantiate Foo
Summary: Types.isConvertible does not handle erroneous types correctly
Reviewed-by: jjg
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;
514 if (t.inst != null)
515 return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
517 t.hibounds = t.hibounds.prepend(s);
518 return true;
519 }
521 @Override
522 public Boolean visitErrorType(ErrorType t, Type s) {
523 return true;
524 }
525 };
527 /**
528 * Is t a subtype of every type in given list `ts'?<br>
529 * (not defined for Method and ForAll types)<br>
530 * Allows unchecked conversions.
531 */
532 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
533 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
534 if (!isSubtypeUnchecked(t, l.head, warn))
535 return false;
536 return true;
537 }
539 /**
540 * Are corresponding elements of ts subtypes of ss? If lists are
541 * of different length, return false.
542 */
543 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
544 while (ts.tail != null && ss.tail != null
545 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
546 isSubtype(ts.head, ss.head)) {
547 ts = ts.tail;
548 ss = ss.tail;
549 }
550 return ts.tail == null && ss.tail == null;
551 /*inlined: ts.isEmpty() && ss.isEmpty();*/
552 }
554 /**
555 * Are corresponding elements of ts subtypes of ss, allowing
556 * unchecked conversions? If lists are of different length,
557 * return false.
558 **/
559 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
560 while (ts.tail != null && ss.tail != null
561 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
562 isSubtypeUnchecked(ts.head, ss.head, warn)) {
563 ts = ts.tail;
564 ss = ss.tail;
565 }
566 return ts.tail == null && ss.tail == null;
567 /*inlined: ts.isEmpty() && ss.isEmpty();*/
568 }
569 // </editor-fold>
571 // <editor-fold defaultstate="collapsed" desc="isSuperType">
572 /**
573 * Is t a supertype of s?
574 */
575 public boolean isSuperType(Type t, Type s) {
576 switch (t.tag) {
577 case ERROR:
578 return true;
579 case UNDETVAR: {
580 UndetVar undet = (UndetVar)t;
581 if (t == s ||
582 undet.qtype == s ||
583 s.tag == ERROR ||
584 s.tag == BOT) return true;
585 if (undet.inst != null)
586 return isSubtype(s, undet.inst);
587 undet.lobounds = undet.lobounds.prepend(s);
588 return true;
589 }
590 default:
591 return isSubtype(s, t);
592 }
593 }
594 // </editor-fold>
596 // <editor-fold defaultstate="collapsed" desc="isSameType">
597 /**
598 * Are corresponding elements of the lists the same type? If
599 * lists are of different length, return false.
600 */
601 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
602 while (ts.tail != null && ss.tail != null
603 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
604 isSameType(ts.head, ss.head)) {
605 ts = ts.tail;
606 ss = ss.tail;
607 }
608 return ts.tail == null && ss.tail == null;
609 /*inlined: ts.isEmpty() && ss.isEmpty();*/
610 }
612 /**
613 * Is t the same type as s?
614 */
615 public boolean isSameType(Type t, Type s) {
616 return isSameType.visit(t, s);
617 }
618 // where
619 private TypeRelation isSameType = new TypeRelation() {
621 public Boolean visitType(Type t, Type s) {
622 if (t == s)
623 return true;
625 if (s.tag >= firstPartialTag)
626 return visit(s, t);
628 switch (t.tag) {
629 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
630 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
631 return t.tag == s.tag;
632 case TYPEVAR: {
633 if (s.tag == TYPEVAR) {
634 //type-substitution does not preserve type-var types
635 //check that type var symbols and bounds are indeed the same
636 return t.tsym == s.tsym &&
637 visit(t.getUpperBound(), s.getUpperBound());
638 }
639 else {
640 //special case for s == ? super X, where upper(s) = u
641 //check that u == t, where u has been set by Type.withTypeVar
642 return s.isSuperBound() &&
643 !s.isExtendsBound() &&
644 visit(t, upperBound(s));
645 }
646 }
647 default:
648 throw new AssertionError("isSameType " + t.tag);
649 }
650 }
652 @Override
653 public Boolean visitWildcardType(WildcardType t, Type s) {
654 if (s.tag >= firstPartialTag)
655 return visit(s, t);
656 else
657 return false;
658 }
660 @Override
661 public Boolean visitClassType(ClassType t, Type s) {
662 if (t == s)
663 return true;
665 if (s.tag >= firstPartialTag)
666 return visit(s, t);
668 if (s.isSuperBound() && !s.isExtendsBound())
669 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
671 if (t.isCompound() && s.isCompound()) {
672 if (!visit(supertype(t), supertype(s)))
673 return false;
675 HashSet<SingletonType> set = new HashSet<SingletonType>();
676 for (Type x : interfaces(t))
677 set.add(new SingletonType(x));
678 for (Type x : interfaces(s)) {
679 if (!set.remove(new SingletonType(x)))
680 return false;
681 }
682 return (set.isEmpty());
683 }
684 return t.tsym == s.tsym
685 && visit(t.getEnclosingType(), s.getEnclosingType())
686 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
687 }
689 @Override
690 public Boolean visitArrayType(ArrayType t, Type s) {
691 if (t == s)
692 return true;
694 if (s.tag >= firstPartialTag)
695 return visit(s, t);
697 return s.tag == ARRAY
698 && containsTypeEquivalent(t.elemtype, elemtype(s));
699 }
701 @Override
702 public Boolean visitMethodType(MethodType t, Type s) {
703 // isSameType for methods does not take thrown
704 // exceptions into account!
705 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
706 }
708 @Override
709 public Boolean visitPackageType(PackageType t, Type s) {
710 return t == s;
711 }
713 @Override
714 public Boolean visitForAll(ForAll t, Type s) {
715 if (s.tag != FORALL)
716 return false;
718 ForAll forAll = (ForAll)s;
719 return hasSameBounds(t, forAll)
720 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
721 }
723 @Override
724 public Boolean visitUndetVar(UndetVar t, Type s) {
725 if (s.tag == WILDCARD)
726 // FIXME, this might be leftovers from before capture conversion
727 return false;
729 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
730 return true;
732 if (t.inst != null)
733 return visit(t.inst, s);
735 t.inst = fromUnknownFun.apply(s);
736 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
737 if (!isSubtype(l.head, t.inst))
738 return false;
739 }
740 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
741 if (!isSubtype(t.inst, l.head))
742 return false;
743 }
744 return true;
745 }
747 @Override
748 public Boolean visitErrorType(ErrorType t, Type s) {
749 return true;
750 }
751 };
752 // </editor-fold>
754 // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
755 /**
756 * A mapping that turns all unknown types in this type to fresh
757 * unknown variables.
758 */
759 public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
760 public Type apply(Type t) {
761 if (t.tag == UNKNOWN) return new UndetVar(t);
762 else return t.map(this);
763 }
764 };
765 // </editor-fold>
767 // <editor-fold defaultstate="collapsed" desc="Contains Type">
768 public boolean containedBy(Type t, Type s) {
769 switch (t.tag) {
770 case UNDETVAR:
771 if (s.tag == WILDCARD) {
772 UndetVar undetvar = (UndetVar)t;
773 WildcardType wt = (WildcardType)s;
774 switch(wt.kind) {
775 case UNBOUND: //similar to ? extends Object
776 case EXTENDS: {
777 Type bound = upperBound(s);
778 // We should check the new upper bound against any of the
779 // undetvar's lower bounds.
780 for (Type t2 : undetvar.lobounds) {
781 if (!isSubtype(t2, bound))
782 return false;
783 }
784 undetvar.hibounds = undetvar.hibounds.prepend(bound);
785 break;
786 }
787 case SUPER: {
788 Type bound = lowerBound(s);
789 // We should check the new lower bound against any of the
790 // undetvar's lower bounds.
791 for (Type t2 : undetvar.hibounds) {
792 if (!isSubtype(bound, t2))
793 return false;
794 }
795 undetvar.lobounds = undetvar.lobounds.prepend(bound);
796 break;
797 }
798 }
799 return true;
800 } else {
801 return isSameType(t, s);
802 }
803 case ERROR:
804 return true;
805 default:
806 return containsType(s, t);
807 }
808 }
810 boolean containsType(List<Type> ts, List<Type> ss) {
811 while (ts.nonEmpty() && ss.nonEmpty()
812 && containsType(ts.head, ss.head)) {
813 ts = ts.tail;
814 ss = ss.tail;
815 }
816 return ts.isEmpty() && ss.isEmpty();
817 }
819 /**
820 * Check if t contains s.
821 *
822 * <p>T contains S if:
823 *
824 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
825 *
826 * <p>This relation is only used by ClassType.isSubtype(), that
827 * is,
828 *
829 * <p>{@code C<S> <: C<T> if T contains S.}
830 *
831 * <p>Because of F-bounds, this relation can lead to infinite
832 * recursion. Thus we must somehow break that recursion. Notice
833 * that containsType() is only called from ClassType.isSubtype().
834 * Since the arguments have already been checked against their
835 * bounds, we know:
836 *
837 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
838 *
839 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
840 *
841 * @param t a type
842 * @param s a type
843 */
844 public boolean containsType(Type t, Type s) {
845 return containsType.visit(t, s);
846 }
847 // where
848 private TypeRelation containsType = new TypeRelation() {
850 private Type U(Type t) {
851 while (t.tag == WILDCARD) {
852 WildcardType w = (WildcardType)t;
853 if (w.isSuperBound())
854 return w.bound == null ? syms.objectType : w.bound.bound;
855 else
856 t = w.type;
857 }
858 return t;
859 }
861 private Type L(Type t) {
862 while (t.tag == WILDCARD) {
863 WildcardType w = (WildcardType)t;
864 if (w.isExtendsBound())
865 return syms.botType;
866 else
867 t = w.type;
868 }
869 return t;
870 }
872 public Boolean visitType(Type t, Type s) {
873 if (s.tag >= firstPartialTag)
874 return containedBy(s, t);
875 else
876 return isSameType(t, s);
877 }
879 // void debugContainsType(WildcardType t, Type s) {
880 // System.err.println();
881 // System.err.format(" does %s contain %s?%n", t, s);
882 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
883 // upperBound(s), s, t, U(t),
884 // t.isSuperBound()
885 // || isSubtypeNoCapture(upperBound(s), U(t)));
886 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
887 // L(t), t, s, lowerBound(s),
888 // t.isExtendsBound()
889 // || isSubtypeNoCapture(L(t), lowerBound(s)));
890 // System.err.println();
891 // }
893 @Override
894 public Boolean visitWildcardType(WildcardType t, Type s) {
895 if (s.tag >= firstPartialTag)
896 return containedBy(s, t);
897 else {
898 // debugContainsType(t, s);
899 return isSameWildcard(t, s)
900 || isCaptureOf(s, t)
901 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
902 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
903 }
904 }
906 @Override
907 public Boolean visitUndetVar(UndetVar t, Type s) {
908 if (s.tag != WILDCARD)
909 return isSameType(t, s);
910 else
911 return false;
912 }
914 @Override
915 public Boolean visitErrorType(ErrorType t, Type s) {
916 return true;
917 }
918 };
920 public boolean isCaptureOf(Type s, WildcardType t) {
921 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
922 return false;
923 return isSameWildcard(t, ((CapturedType)s).wildcard);
924 }
926 public boolean isSameWildcard(WildcardType t, Type s) {
927 if (s.tag != WILDCARD)
928 return false;
929 WildcardType w = (WildcardType)s;
930 return w.kind == t.kind && w.type == t.type;
931 }
933 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
934 while (ts.nonEmpty() && ss.nonEmpty()
935 && containsTypeEquivalent(ts.head, ss.head)) {
936 ts = ts.tail;
937 ss = ss.tail;
938 }
939 return ts.isEmpty() && ss.isEmpty();
940 }
941 // </editor-fold>
943 // <editor-fold defaultstate="collapsed" desc="isCastable">
944 public boolean isCastable(Type t, Type s) {
945 return isCastable(t, s, Warner.noWarnings);
946 }
948 /**
949 * Is t is castable to s?<br>
950 * s is assumed to be an erased type.<br>
951 * (not defined for Method and ForAll types).
952 */
953 public boolean isCastable(Type t, Type s, Warner warn) {
954 if (t == s)
955 return true;
957 if (t.isPrimitive() != s.isPrimitive())
958 return allowBoxing && (
959 isConvertible(t, s, warn)
960 || (allowObjectToPrimitiveCast &&
961 s.isPrimitive() &&
962 isSubtype(boxedClass(s).type, t)));
963 if (warn != warnStack.head) {
964 try {
965 warnStack = warnStack.prepend(warn);
966 checkUnsafeVarargsConversion(t, s, warn);
967 return isCastable.visit(t,s);
968 } finally {
969 warnStack = warnStack.tail;
970 }
971 } else {
972 return isCastable.visit(t,s);
973 }
974 }
975 // where
976 private TypeRelation isCastable = new TypeRelation() {
978 public Boolean visitType(Type t, Type s) {
979 if (s.tag == ERROR)
980 return true;
982 switch (t.tag) {
983 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
984 case DOUBLE:
985 return s.tag <= DOUBLE;
986 case BOOLEAN:
987 return s.tag == BOOLEAN;
988 case VOID:
989 return false;
990 case BOT:
991 return isSubtype(t, s);
992 default:
993 throw new AssertionError();
994 }
995 }
997 @Override
998 public Boolean visitWildcardType(WildcardType t, Type s) {
999 return isCastable(upperBound(t), s, warnStack.head);
1000 }
1002 @Override
1003 public Boolean visitClassType(ClassType t, Type s) {
1004 if (s.tag == ERROR || s.tag == BOT)
1005 return true;
1007 if (s.tag == TYPEVAR) {
1008 if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
1009 warnStack.head.warn(LintCategory.UNCHECKED);
1010 return true;
1011 } else {
1012 return false;
1013 }
1014 }
1016 if (t.isCompound()) {
1017 Warner oldWarner = warnStack.head;
1018 warnStack.head = Warner.noWarnings;
1019 if (!visit(supertype(t), s))
1020 return false;
1021 for (Type intf : interfaces(t)) {
1022 if (!visit(intf, s))
1023 return false;
1024 }
1025 if (warnStack.head.hasLint(LintCategory.UNCHECKED))
1026 oldWarner.warn(LintCategory.UNCHECKED);
1027 return true;
1028 }
1030 if (s.isCompound()) {
1031 // call recursively to reuse the above code
1032 return visitClassType((ClassType)s, t);
1033 }
1035 if (s.tag == CLASS || s.tag == ARRAY) {
1036 boolean upcast;
1037 if ((upcast = isSubtype(erasure(t), erasure(s)))
1038 || isSubtype(erasure(s), erasure(t))) {
1039 if (!upcast && s.tag == ARRAY) {
1040 if (!isReifiable(s))
1041 warnStack.head.warn(LintCategory.UNCHECKED);
1042 return true;
1043 } else if (s.isRaw()) {
1044 return true;
1045 } else if (t.isRaw()) {
1046 if (!isUnbounded(s))
1047 warnStack.head.warn(LintCategory.UNCHECKED);
1048 return true;
1049 }
1050 // Assume |a| <: |b|
1051 final Type a = upcast ? t : s;
1052 final Type b = upcast ? s : t;
1053 final boolean HIGH = true;
1054 final boolean LOW = false;
1055 final boolean DONT_REWRITE_TYPEVARS = false;
1056 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1057 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1058 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1059 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1060 Type lowSub = asSub(bLow, aLow.tsym);
1061 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1062 if (highSub == null) {
1063 final boolean REWRITE_TYPEVARS = true;
1064 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1065 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1066 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1067 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1068 lowSub = asSub(bLow, aLow.tsym);
1069 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1070 }
1071 if (highSub != null) {
1072 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1073 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1074 }
1075 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1076 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1077 && !disjointTypes(aLow.allparams(), highSub.allparams())
1078 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1079 if (upcast ? giveWarning(a, b) :
1080 giveWarning(b, a))
1081 warnStack.head.warn(LintCategory.UNCHECKED);
1082 return true;
1083 }
1084 }
1085 if (isReifiable(s))
1086 return isSubtypeUnchecked(a, b);
1087 else
1088 return isSubtypeUnchecked(a, b, warnStack.head);
1089 }
1091 // Sidecast
1092 if (s.tag == CLASS) {
1093 if ((s.tsym.flags() & INTERFACE) != 0) {
1094 return ((t.tsym.flags() & FINAL) == 0)
1095 ? sideCast(t, s, warnStack.head)
1096 : sideCastFinal(t, s, warnStack.head);
1097 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1098 return ((s.tsym.flags() & FINAL) == 0)
1099 ? sideCast(t, s, warnStack.head)
1100 : sideCastFinal(t, s, warnStack.head);
1101 } else {
1102 // unrelated class types
1103 return false;
1104 }
1105 }
1106 }
1107 return false;
1108 }
1110 @Override
1111 public Boolean visitArrayType(ArrayType t, Type s) {
1112 switch (s.tag) {
1113 case ERROR:
1114 case BOT:
1115 return true;
1116 case TYPEVAR:
1117 if (isCastable(s, t, Warner.noWarnings)) {
1118 warnStack.head.warn(LintCategory.UNCHECKED);
1119 return true;
1120 } else {
1121 return false;
1122 }
1123 case CLASS:
1124 return isSubtype(t, s);
1125 case ARRAY:
1126 if (elemtype(t).tag <= lastBaseTag ||
1127 elemtype(s).tag <= lastBaseTag) {
1128 return elemtype(t).tag == elemtype(s).tag;
1129 } else {
1130 return visit(elemtype(t), elemtype(s));
1131 }
1132 default:
1133 return false;
1134 }
1135 }
1137 @Override
1138 public Boolean visitTypeVar(TypeVar t, Type s) {
1139 switch (s.tag) {
1140 case ERROR:
1141 case BOT:
1142 return true;
1143 case TYPEVAR:
1144 if (isSubtype(t, s)) {
1145 return true;
1146 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1147 warnStack.head.warn(LintCategory.UNCHECKED);
1148 return true;
1149 } else {
1150 return false;
1151 }
1152 default:
1153 return isCastable(t.bound, s, warnStack.head);
1154 }
1155 }
1157 @Override
1158 public Boolean visitErrorType(ErrorType t, Type s) {
1159 return true;
1160 }
1161 };
1162 // </editor-fold>
1164 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1165 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1166 while (ts.tail != null && ss.tail != null) {
1167 if (disjointType(ts.head, ss.head)) return true;
1168 ts = ts.tail;
1169 ss = ss.tail;
1170 }
1171 return false;
1172 }
1174 /**
1175 * Two types or wildcards are considered disjoint if it can be
1176 * proven that no type can be contained in both. It is
1177 * conservative in that it is allowed to say that two types are
1178 * not disjoint, even though they actually are.
1179 *
1180 * The type C<X> is castable to C<Y> exactly if X and Y are not
1181 * disjoint.
1182 */
1183 public boolean disjointType(Type t, Type s) {
1184 return disjointType.visit(t, s);
1185 }
1186 // where
1187 private TypeRelation disjointType = new TypeRelation() {
1189 private Set<TypePair> cache = new HashSet<TypePair>();
1191 public Boolean visitType(Type t, Type s) {
1192 if (s.tag == WILDCARD)
1193 return visit(s, t);
1194 else
1195 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1196 }
1198 private boolean isCastableRecursive(Type t, Type s) {
1199 TypePair pair = new TypePair(t, s);
1200 if (cache.add(pair)) {
1201 try {
1202 return Types.this.isCastable(t, s);
1203 } finally {
1204 cache.remove(pair);
1205 }
1206 } else {
1207 return true;
1208 }
1209 }
1211 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1212 TypePair pair = new TypePair(t, s);
1213 if (cache.add(pair)) {
1214 try {
1215 return Types.this.notSoftSubtype(t, s);
1216 } finally {
1217 cache.remove(pair);
1218 }
1219 } else {
1220 return false;
1221 }
1222 }
1224 @Override
1225 public Boolean visitWildcardType(WildcardType t, Type s) {
1226 if (t.isUnbound())
1227 return false;
1229 if (s.tag != WILDCARD) {
1230 if (t.isExtendsBound())
1231 return notSoftSubtypeRecursive(s, t.type);
1232 else // isSuperBound()
1233 return notSoftSubtypeRecursive(t.type, s);
1234 }
1236 if (s.isUnbound())
1237 return false;
1239 if (t.isExtendsBound()) {
1240 if (s.isExtendsBound())
1241 return !isCastableRecursive(t.type, upperBound(s));
1242 else if (s.isSuperBound())
1243 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1244 } else if (t.isSuperBound()) {
1245 if (s.isExtendsBound())
1246 return notSoftSubtypeRecursive(t.type, upperBound(s));
1247 }
1248 return false;
1249 }
1250 };
1251 // </editor-fold>
1253 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1254 /**
1255 * Returns the lower bounds of the formals of a method.
1256 */
1257 public List<Type> lowerBoundArgtypes(Type t) {
1258 return map(t.getParameterTypes(), lowerBoundMapping);
1259 }
1260 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1261 public Type apply(Type t) {
1262 return lowerBound(t);
1263 }
1264 };
1265 // </editor-fold>
1267 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1268 /**
1269 * This relation answers the question: is impossible that
1270 * something of type `t' can be a subtype of `s'? This is
1271 * different from the question "is `t' not a subtype of `s'?"
1272 * when type variables are involved: Integer is not a subtype of T
1273 * where <T extends Number> but it is not true that Integer cannot
1274 * possibly be a subtype of T.
1275 */
1276 public boolean notSoftSubtype(Type t, Type s) {
1277 if (t == s) return false;
1278 if (t.tag == TYPEVAR) {
1279 TypeVar tv = (TypeVar) t;
1280 return !isCastable(tv.bound,
1281 relaxBound(s),
1282 Warner.noWarnings);
1283 }
1284 if (s.tag != WILDCARD)
1285 s = upperBound(s);
1287 return !isSubtype(t, relaxBound(s));
1288 }
1290 private Type relaxBound(Type t) {
1291 if (t.tag == TYPEVAR) {
1292 while (t.tag == TYPEVAR)
1293 t = t.getUpperBound();
1294 t = rewriteQuantifiers(t, true, true);
1295 }
1296 return t;
1297 }
1298 // </editor-fold>
1300 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1301 public boolean isReifiable(Type t) {
1302 return isReifiable.visit(t);
1303 }
1304 // where
1305 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1307 public Boolean visitType(Type t, Void ignored) {
1308 return true;
1309 }
1311 @Override
1312 public Boolean visitClassType(ClassType t, Void ignored) {
1313 if (t.isCompound())
1314 return false;
1315 else {
1316 if (!t.isParameterized())
1317 return true;
1319 for (Type param : t.allparams()) {
1320 if (!param.isUnbound())
1321 return false;
1322 }
1323 return true;
1324 }
1325 }
1327 @Override
1328 public Boolean visitArrayType(ArrayType t, Void ignored) {
1329 return visit(t.elemtype);
1330 }
1332 @Override
1333 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1334 return false;
1335 }
1336 };
1337 // </editor-fold>
1339 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1340 public boolean isArray(Type t) {
1341 while (t.tag == WILDCARD)
1342 t = upperBound(t);
1343 return t.tag == ARRAY;
1344 }
1346 /**
1347 * The element type of an array.
1348 */
1349 public Type elemtype(Type t) {
1350 switch (t.tag) {
1351 case WILDCARD:
1352 return elemtype(upperBound(t));
1353 case ARRAY:
1354 return ((ArrayType)t).elemtype;
1355 case FORALL:
1356 return elemtype(((ForAll)t).qtype);
1357 case ERROR:
1358 return t;
1359 default:
1360 return null;
1361 }
1362 }
1364 public Type elemtypeOrType(Type t) {
1365 Type elemtype = elemtype(t);
1366 return elemtype != null ?
1367 elemtype :
1368 t;
1369 }
1371 /**
1372 * Mapping to take element type of an arraytype
1373 */
1374 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1375 public Type apply(Type t) { return elemtype(t); }
1376 };
1378 /**
1379 * The number of dimensions of an array type.
1380 */
1381 public int dimensions(Type t) {
1382 int result = 0;
1383 while (t.tag == ARRAY) {
1384 result++;
1385 t = elemtype(t);
1386 }
1387 return result;
1388 }
1389 // </editor-fold>
1391 // <editor-fold defaultstate="collapsed" desc="asSuper">
1392 /**
1393 * Return the (most specific) base type of t that starts with the
1394 * given symbol. If none exists, return null.
1395 *
1396 * @param t a type
1397 * @param sym a symbol
1398 */
1399 public Type asSuper(Type t, Symbol sym) {
1400 return asSuper.visit(t, sym);
1401 }
1402 // where
1403 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1405 public Type visitType(Type t, Symbol sym) {
1406 return null;
1407 }
1409 @Override
1410 public Type visitClassType(ClassType t, Symbol sym) {
1411 if (t.tsym == sym)
1412 return t;
1414 Type st = supertype(t);
1415 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1416 Type x = asSuper(st, sym);
1417 if (x != null)
1418 return x;
1419 }
1420 if ((sym.flags() & INTERFACE) != 0) {
1421 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1422 Type x = asSuper(l.head, sym);
1423 if (x != null)
1424 return x;
1425 }
1426 }
1427 return null;
1428 }
1430 @Override
1431 public Type visitArrayType(ArrayType t, Symbol sym) {
1432 return isSubtype(t, sym.type) ? sym.type : null;
1433 }
1435 @Override
1436 public Type visitTypeVar(TypeVar t, Symbol sym) {
1437 if (t.tsym == sym)
1438 return t;
1439 else
1440 return asSuper(t.bound, sym);
1441 }
1443 @Override
1444 public Type visitErrorType(ErrorType t, Symbol sym) {
1445 return t;
1446 }
1447 };
1449 /**
1450 * Return the base type of t or any of its outer types that starts
1451 * with the given symbol. If none exists, return null.
1452 *
1453 * @param t a type
1454 * @param sym a symbol
1455 */
1456 public Type asOuterSuper(Type t, Symbol sym) {
1457 switch (t.tag) {
1458 case CLASS:
1459 do {
1460 Type s = asSuper(t, sym);
1461 if (s != null) return s;
1462 t = t.getEnclosingType();
1463 } while (t.tag == CLASS);
1464 return null;
1465 case ARRAY:
1466 return isSubtype(t, sym.type) ? sym.type : null;
1467 case TYPEVAR:
1468 return asSuper(t, sym);
1469 case ERROR:
1470 return t;
1471 default:
1472 return null;
1473 }
1474 }
1476 /**
1477 * Return the base type of t or any of its enclosing types that
1478 * starts with the given symbol. If none exists, return null.
1479 *
1480 * @param t a type
1481 * @param sym a symbol
1482 */
1483 public Type asEnclosingSuper(Type t, Symbol sym) {
1484 switch (t.tag) {
1485 case CLASS:
1486 do {
1487 Type s = asSuper(t, sym);
1488 if (s != null) return s;
1489 Type outer = t.getEnclosingType();
1490 t = (outer.tag == CLASS) ? outer :
1491 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1492 Type.noType;
1493 } while (t.tag == CLASS);
1494 return null;
1495 case ARRAY:
1496 return isSubtype(t, sym.type) ? sym.type : null;
1497 case TYPEVAR:
1498 return asSuper(t, sym);
1499 case ERROR:
1500 return t;
1501 default:
1502 return null;
1503 }
1504 }
1505 // </editor-fold>
1507 // <editor-fold defaultstate="collapsed" desc="memberType">
1508 /**
1509 * The type of given symbol, seen as a member of t.
1510 *
1511 * @param t a type
1512 * @param sym a symbol
1513 */
1514 public Type memberType(Type t, Symbol sym) {
1515 return (sym.flags() & STATIC) != 0
1516 ? sym.type
1517 : memberType.visit(t, sym);
1518 }
1519 // where
1520 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1522 public Type visitType(Type t, Symbol sym) {
1523 return sym.type;
1524 }
1526 @Override
1527 public Type visitWildcardType(WildcardType t, Symbol sym) {
1528 return memberType(upperBound(t), sym);
1529 }
1531 @Override
1532 public Type visitClassType(ClassType t, Symbol sym) {
1533 Symbol owner = sym.owner;
1534 long flags = sym.flags();
1535 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1536 Type base = asOuterSuper(t, owner);
1537 //if t is an intersection type T = CT & I1 & I2 ... & In
1538 //its supertypes CT, I1, ... In might contain wildcards
1539 //so we need to go through capture conversion
1540 base = t.isCompound() ? capture(base) : base;
1541 if (base != null) {
1542 List<Type> ownerParams = owner.type.allparams();
1543 List<Type> baseParams = base.allparams();
1544 if (ownerParams.nonEmpty()) {
1545 if (baseParams.isEmpty()) {
1546 // then base is a raw type
1547 return erasure(sym.type);
1548 } else {
1549 return subst(sym.type, ownerParams, baseParams);
1550 }
1551 }
1552 }
1553 }
1554 return sym.type;
1555 }
1557 @Override
1558 public Type visitTypeVar(TypeVar t, Symbol sym) {
1559 return memberType(t.bound, sym);
1560 }
1562 @Override
1563 public Type visitErrorType(ErrorType t, Symbol sym) {
1564 return t;
1565 }
1566 };
1567 // </editor-fold>
1569 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1570 public boolean isAssignable(Type t, Type s) {
1571 return isAssignable(t, s, Warner.noWarnings);
1572 }
1574 /**
1575 * Is t assignable to s?<br>
1576 * Equivalent to subtype except for constant values and raw
1577 * types.<br>
1578 * (not defined for Method and ForAll types)
1579 */
1580 public boolean isAssignable(Type t, Type s, Warner warn) {
1581 if (t.tag == ERROR)
1582 return true;
1583 if (t.tag <= INT && t.constValue() != null) {
1584 int value = ((Number)t.constValue()).intValue();
1585 switch (s.tag) {
1586 case BYTE:
1587 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1588 return true;
1589 break;
1590 case CHAR:
1591 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1592 return true;
1593 break;
1594 case SHORT:
1595 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1596 return true;
1597 break;
1598 case INT:
1599 return true;
1600 case CLASS:
1601 switch (unboxedType(s).tag) {
1602 case BYTE:
1603 case CHAR:
1604 case SHORT:
1605 return isAssignable(t, unboxedType(s), warn);
1606 }
1607 break;
1608 }
1609 }
1610 return isConvertible(t, s, warn);
1611 }
1612 // </editor-fold>
1614 // <editor-fold defaultstate="collapsed" desc="erasure">
1615 /**
1616 * The erasure of t {@code |t|} -- the type that results when all
1617 * type parameters in t are deleted.
1618 */
1619 public Type erasure(Type t) {
1620 return erasure(t, false);
1621 }
1622 //where
1623 private Type erasure(Type t, boolean recurse) {
1624 if (t.tag <= lastBaseTag)
1625 return t; /* fast special case */
1626 else
1627 return erasure.visit(t, recurse);
1628 }
1629 // where
1630 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1631 public Type visitType(Type t, Boolean recurse) {
1632 if (t.tag <= lastBaseTag)
1633 return t; /*fast special case*/
1634 else
1635 return t.map(recurse ? erasureRecFun : erasureFun);
1636 }
1638 @Override
1639 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1640 return erasure(upperBound(t), recurse);
1641 }
1643 @Override
1644 public Type visitClassType(ClassType t, Boolean recurse) {
1645 Type erased = t.tsym.erasure(Types.this);
1646 if (recurse) {
1647 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1648 }
1649 return erased;
1650 }
1652 @Override
1653 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1654 return erasure(t.bound, recurse);
1655 }
1657 @Override
1658 public Type visitErrorType(ErrorType t, Boolean recurse) {
1659 return t;
1660 }
1661 };
1663 private Mapping erasureFun = new Mapping ("erasure") {
1664 public Type apply(Type t) { return erasure(t); }
1665 };
1667 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1668 public Type apply(Type t) { return erasureRecursive(t); }
1669 };
1671 public List<Type> erasure(List<Type> ts) {
1672 return Type.map(ts, erasureFun);
1673 }
1675 public Type erasureRecursive(Type t) {
1676 return erasure(t, true);
1677 }
1679 public List<Type> erasureRecursive(List<Type> ts) {
1680 return Type.map(ts, erasureRecFun);
1681 }
1682 // </editor-fold>
1684 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1685 /**
1686 * Make a compound type from non-empty list of types
1687 *
1688 * @param bounds the types from which the compound type is formed
1689 * @param supertype is objectType if all bounds are interfaces,
1690 * null otherwise.
1691 */
1692 public Type makeCompoundType(List<Type> bounds,
1693 Type supertype) {
1694 ClassSymbol bc =
1695 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1696 Type.moreInfo
1697 ? names.fromString(bounds.toString())
1698 : names.empty,
1699 syms.noSymbol);
1700 if (bounds.head.tag == TYPEVAR)
1701 // error condition, recover
1702 bc.erasure_field = syms.objectType;
1703 else
1704 bc.erasure_field = erasure(bounds.head);
1705 bc.members_field = new Scope(bc);
1706 ClassType bt = (ClassType)bc.type;
1707 bt.allparams_field = List.nil();
1708 if (supertype != null) {
1709 bt.supertype_field = supertype;
1710 bt.interfaces_field = bounds;
1711 } else {
1712 bt.supertype_field = bounds.head;
1713 bt.interfaces_field = bounds.tail;
1714 }
1715 Assert.check(bt.supertype_field.tsym.completer != null
1716 || !bt.supertype_field.isInterface(),
1717 bt.supertype_field);
1718 return bt;
1719 }
1721 /**
1722 * Same as {@link #makeCompoundType(List,Type)}, except that the
1723 * second parameter is computed directly. Note that this might
1724 * cause a symbol completion. Hence, this version of
1725 * makeCompoundType may not be called during a classfile read.
1726 */
1727 public Type makeCompoundType(List<Type> bounds) {
1728 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1729 supertype(bounds.head) : null;
1730 return makeCompoundType(bounds, supertype);
1731 }
1733 /**
1734 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1735 * arguments are converted to a list and passed to the other
1736 * method. Note that this might cause a symbol completion.
1737 * Hence, this version of makeCompoundType may not be called
1738 * during a classfile read.
1739 */
1740 public Type makeCompoundType(Type bound1, Type bound2) {
1741 return makeCompoundType(List.of(bound1, bound2));
1742 }
1743 // </editor-fold>
1745 // <editor-fold defaultstate="collapsed" desc="supertype">
1746 public Type supertype(Type t) {
1747 return supertype.visit(t);
1748 }
1749 // where
1750 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1752 public Type visitType(Type t, Void ignored) {
1753 // A note on wildcards: there is no good way to
1754 // determine a supertype for a super bounded wildcard.
1755 return null;
1756 }
1758 @Override
1759 public Type visitClassType(ClassType t, Void ignored) {
1760 if (t.supertype_field == null) {
1761 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1762 // An interface has no superclass; its supertype is Object.
1763 if (t.isInterface())
1764 supertype = ((ClassType)t.tsym.type).supertype_field;
1765 if (t.supertype_field == null) {
1766 List<Type> actuals = classBound(t).allparams();
1767 List<Type> formals = t.tsym.type.allparams();
1768 if (t.hasErasedSupertypes()) {
1769 t.supertype_field = erasureRecursive(supertype);
1770 } else if (formals.nonEmpty()) {
1771 t.supertype_field = subst(supertype, formals, actuals);
1772 }
1773 else {
1774 t.supertype_field = supertype;
1775 }
1776 }
1777 }
1778 return t.supertype_field;
1779 }
1781 /**
1782 * The supertype is always a class type. If the type
1783 * variable's bounds start with a class type, this is also
1784 * the supertype. Otherwise, the supertype is
1785 * java.lang.Object.
1786 */
1787 @Override
1788 public Type visitTypeVar(TypeVar t, Void ignored) {
1789 if (t.bound.tag == TYPEVAR ||
1790 (!t.bound.isCompound() && !t.bound.isInterface())) {
1791 return t.bound;
1792 } else {
1793 return supertype(t.bound);
1794 }
1795 }
1797 @Override
1798 public Type visitArrayType(ArrayType t, Void ignored) {
1799 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1800 return arraySuperType();
1801 else
1802 return new ArrayType(supertype(t.elemtype), t.tsym);
1803 }
1805 @Override
1806 public Type visitErrorType(ErrorType t, Void ignored) {
1807 return t;
1808 }
1809 };
1810 // </editor-fold>
1812 // <editor-fold defaultstate="collapsed" desc="interfaces">
1813 /**
1814 * Return the interfaces implemented by this class.
1815 */
1816 public List<Type> interfaces(Type t) {
1817 return interfaces.visit(t);
1818 }
1819 // where
1820 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1822 public List<Type> visitType(Type t, Void ignored) {
1823 return List.nil();
1824 }
1826 @Override
1827 public List<Type> visitClassType(ClassType t, Void ignored) {
1828 if (t.interfaces_field == null) {
1829 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1830 if (t.interfaces_field == null) {
1831 // If t.interfaces_field is null, then t must
1832 // be a parameterized type (not to be confused
1833 // with a generic type declaration).
1834 // Terminology:
1835 // Parameterized type: List<String>
1836 // Generic type declaration: class List<E> { ... }
1837 // So t corresponds to List<String> and
1838 // t.tsym.type corresponds to List<E>.
1839 // The reason t must be parameterized type is
1840 // that completion will happen as a side
1841 // effect of calling
1842 // ClassSymbol.getInterfaces. Since
1843 // t.interfaces_field is null after
1844 // completion, we can assume that t is not the
1845 // type of a class/interface declaration.
1846 Assert.check(t != t.tsym.type, t);
1847 List<Type> actuals = t.allparams();
1848 List<Type> formals = t.tsym.type.allparams();
1849 if (t.hasErasedSupertypes()) {
1850 t.interfaces_field = erasureRecursive(interfaces);
1851 } else if (formals.nonEmpty()) {
1852 t.interfaces_field =
1853 upperBounds(subst(interfaces, formals, actuals));
1854 }
1855 else {
1856 t.interfaces_field = interfaces;
1857 }
1858 }
1859 }
1860 return t.interfaces_field;
1861 }
1863 @Override
1864 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1865 if (t.bound.isCompound())
1866 return interfaces(t.bound);
1868 if (t.bound.isInterface())
1869 return List.of(t.bound);
1871 return List.nil();
1872 }
1873 };
1874 // </editor-fold>
1876 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1877 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1879 public boolean isDerivedRaw(Type t) {
1880 Boolean result = isDerivedRawCache.get(t);
1881 if (result == null) {
1882 result = isDerivedRawInternal(t);
1883 isDerivedRawCache.put(t, result);
1884 }
1885 return result;
1886 }
1888 public boolean isDerivedRawInternal(Type t) {
1889 if (t.isErroneous())
1890 return false;
1891 return
1892 t.isRaw() ||
1893 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1894 isDerivedRaw(interfaces(t));
1895 }
1897 public boolean isDerivedRaw(List<Type> ts) {
1898 List<Type> l = ts;
1899 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1900 return l.nonEmpty();
1901 }
1902 // </editor-fold>
1904 // <editor-fold defaultstate="collapsed" desc="setBounds">
1905 /**
1906 * Set the bounds field of the given type variable to reflect a
1907 * (possibly multiple) list of bounds.
1908 * @param t a type variable
1909 * @param bounds the bounds, must be nonempty
1910 * @param supertype is objectType if all bounds are interfaces,
1911 * null otherwise.
1912 */
1913 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1914 if (bounds.tail.isEmpty())
1915 t.bound = bounds.head;
1916 else
1917 t.bound = makeCompoundType(bounds, supertype);
1918 t.rank_field = -1;
1919 }
1921 /**
1922 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1923 * third parameter is computed directly, as follows: if all
1924 * all bounds are interface types, the computed supertype is Object,
1925 * otherwise the supertype is simply left null (in this case, the supertype
1926 * is assumed to be the head of the bound list passed as second argument).
1927 * Note that this check might cause a symbol completion. Hence, this version of
1928 * setBounds may not be called during a classfile read.
1929 */
1930 public void setBounds(TypeVar t, List<Type> bounds) {
1931 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1932 syms.objectType : null;
1933 setBounds(t, bounds, supertype);
1934 t.rank_field = -1;
1935 }
1936 // </editor-fold>
1938 // <editor-fold defaultstate="collapsed" desc="getBounds">
1939 /**
1940 * Return list of bounds of the given type variable.
1941 */
1942 public List<Type> getBounds(TypeVar t) {
1943 if (t.bound.isErroneous() || !t.bound.isCompound())
1944 return List.of(t.bound);
1945 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1946 return interfaces(t).prepend(supertype(t));
1947 else
1948 // No superclass was given in bounds.
1949 // In this case, supertype is Object, erasure is first interface.
1950 return interfaces(t);
1951 }
1952 // </editor-fold>
1954 // <editor-fold defaultstate="collapsed" desc="classBound">
1955 /**
1956 * If the given type is a (possibly selected) type variable,
1957 * return the bounding class of this type, otherwise return the
1958 * type itself.
1959 */
1960 public Type classBound(Type t) {
1961 return classBound.visit(t);
1962 }
1963 // where
1964 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1966 public Type visitType(Type t, Void ignored) {
1967 return t;
1968 }
1970 @Override
1971 public Type visitClassType(ClassType t, Void ignored) {
1972 Type outer1 = classBound(t.getEnclosingType());
1973 if (outer1 != t.getEnclosingType())
1974 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1975 else
1976 return t;
1977 }
1979 @Override
1980 public Type visitTypeVar(TypeVar t, Void ignored) {
1981 return classBound(supertype(t));
1982 }
1984 @Override
1985 public Type visitErrorType(ErrorType t, Void ignored) {
1986 return t;
1987 }
1988 };
1989 // </editor-fold>
1991 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1992 /**
1993 * Returns true iff the first signature is a <em>sub
1994 * signature</em> of the other. This is <b>not</b> an equivalence
1995 * relation.
1996 *
1997 * @jls section 8.4.2.
1998 * @see #overrideEquivalent(Type t, Type s)
1999 * @param t first signature (possibly raw).
2000 * @param s second signature (could be subjected to erasure).
2001 * @return true if t is a sub signature of s.
2002 */
2003 public boolean isSubSignature(Type t, Type s) {
2004 return isSubSignature(t, s, true);
2005 }
2007 public boolean isSubSignature(Type t, Type s, boolean strict) {
2008 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2009 }
2011 /**
2012 * Returns true iff these signatures are related by <em>override
2013 * equivalence</em>. This is the natural extension of
2014 * isSubSignature to an equivalence relation.
2015 *
2016 * @jls section 8.4.2.
2017 * @see #isSubSignature(Type t, Type s)
2018 * @param t a signature (possible raw, could be subjected to
2019 * erasure).
2020 * @param s a signature (possible raw, could be subjected to
2021 * erasure).
2022 * @return true if either argument is a sub signature of the other.
2023 */
2024 public boolean overrideEquivalent(Type t, Type s) {
2025 return hasSameArgs(t, s) ||
2026 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2027 }
2029 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2030 class ImplementationCache {
2032 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2033 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2035 class Entry {
2036 final MethodSymbol cachedImpl;
2037 final Filter<Symbol> implFilter;
2038 final boolean checkResult;
2039 final int prevMark;
2041 public Entry(MethodSymbol cachedImpl,
2042 Filter<Symbol> scopeFilter,
2043 boolean checkResult,
2044 int prevMark) {
2045 this.cachedImpl = cachedImpl;
2046 this.implFilter = scopeFilter;
2047 this.checkResult = checkResult;
2048 this.prevMark = prevMark;
2049 }
2051 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2052 return this.implFilter == scopeFilter &&
2053 this.checkResult == checkResult &&
2054 this.prevMark == mark;
2055 }
2056 }
2058 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2059 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2060 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2061 if (cache == null) {
2062 cache = new HashMap<TypeSymbol, Entry>();
2063 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2064 }
2065 Entry e = cache.get(origin);
2066 CompoundScope members = membersClosure(origin.type, true);
2067 if (e == null ||
2068 !e.matches(implFilter, checkResult, members.getMark())) {
2069 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2070 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2071 return impl;
2072 }
2073 else {
2074 return e.cachedImpl;
2075 }
2076 }
2078 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2079 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2080 while (t.tag == TYPEVAR)
2081 t = t.getUpperBound();
2082 TypeSymbol c = t.tsym;
2083 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2084 e.scope != null;
2085 e = e.next(implFilter)) {
2086 if (e.sym != null &&
2087 e.sym.overrides(ms, origin, Types.this, checkResult))
2088 return (MethodSymbol)e.sym;
2089 }
2090 }
2091 return null;
2092 }
2093 }
2095 private ImplementationCache implCache = new ImplementationCache();
2097 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2098 return implCache.get(ms, origin, checkResult, implFilter);
2099 }
2100 // </editor-fold>
2102 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2103 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2105 private WeakHashMap<TypeSymbol, Entry> _map =
2106 new WeakHashMap<TypeSymbol, Entry>();
2108 class Entry {
2109 final boolean skipInterfaces;
2110 final CompoundScope compoundScope;
2112 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2113 this.skipInterfaces = skipInterfaces;
2114 this.compoundScope = compoundScope;
2115 }
2117 boolean matches(boolean skipInterfaces) {
2118 return this.skipInterfaces == skipInterfaces;
2119 }
2120 }
2122 /** members closure visitor methods **/
2124 public CompoundScope visitType(Type t, Boolean skipInterface) {
2125 return null;
2126 }
2128 @Override
2129 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2130 ClassSymbol csym = (ClassSymbol)t.tsym;
2131 Entry e = _map.get(csym);
2132 if (e == null || !e.matches(skipInterface)) {
2133 CompoundScope membersClosure = new CompoundScope(csym);
2134 if (!skipInterface) {
2135 for (Type i : interfaces(t)) {
2136 membersClosure.addSubScope(visit(i, skipInterface));
2137 }
2138 }
2139 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2140 membersClosure.addSubScope(csym.members());
2141 e = new Entry(skipInterface, membersClosure);
2142 _map.put(csym, e);
2143 }
2144 return e.compoundScope;
2145 }
2147 @Override
2148 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2149 return visit(t.getUpperBound(), skipInterface);
2150 }
2151 }
2153 private MembersClosureCache membersCache = new MembersClosureCache();
2155 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2156 return membersCache.visit(site, skipInterface);
2157 }
2158 // </editor-fold>
2160 /**
2161 * Does t have the same arguments as s? It is assumed that both
2162 * types are (possibly polymorphic) method types. Monomorphic
2163 * method types "have the same arguments", if their argument lists
2164 * are equal. Polymorphic method types "have the same arguments",
2165 * if they have the same arguments after renaming all type
2166 * variables of one to corresponding type variables in the other,
2167 * where correspondence is by position in the type parameter list.
2168 */
2169 public boolean hasSameArgs(Type t, Type s) {
2170 return hasSameArgs(t, s, true);
2171 }
2173 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2174 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2175 }
2177 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2178 return hasSameArgs.visit(t, s);
2179 }
2180 // where
2181 private class HasSameArgs extends TypeRelation {
2183 boolean strict;
2185 public HasSameArgs(boolean strict) {
2186 this.strict = strict;
2187 }
2189 public Boolean visitType(Type t, Type s) {
2190 throw new AssertionError();
2191 }
2193 @Override
2194 public Boolean visitMethodType(MethodType t, Type s) {
2195 return s.tag == METHOD
2196 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2197 }
2199 @Override
2200 public Boolean visitForAll(ForAll t, Type s) {
2201 if (s.tag != FORALL)
2202 return strict ? false : visitMethodType(t.asMethodType(), s);
2204 ForAll forAll = (ForAll)s;
2205 return hasSameBounds(t, forAll)
2206 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2207 }
2209 @Override
2210 public Boolean visitErrorType(ErrorType t, Type s) {
2211 return false;
2212 }
2213 };
2215 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2216 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2218 // </editor-fold>
2220 // <editor-fold defaultstate="collapsed" desc="subst">
2221 public List<Type> subst(List<Type> ts,
2222 List<Type> from,
2223 List<Type> to) {
2224 return new Subst(from, to).subst(ts);
2225 }
2227 /**
2228 * Substitute all occurrences of a type in `from' with the
2229 * corresponding type in `to' in 't'. Match lists `from' and `to'
2230 * from the right: If lists have different length, discard leading
2231 * elements of the longer list.
2232 */
2233 public Type subst(Type t, List<Type> from, List<Type> to) {
2234 return new Subst(from, to).subst(t);
2235 }
2237 private class Subst extends UnaryVisitor<Type> {
2238 List<Type> from;
2239 List<Type> to;
2241 public Subst(List<Type> from, List<Type> to) {
2242 int fromLength = from.length();
2243 int toLength = to.length();
2244 while (fromLength > toLength) {
2245 fromLength--;
2246 from = from.tail;
2247 }
2248 while (fromLength < toLength) {
2249 toLength--;
2250 to = to.tail;
2251 }
2252 this.from = from;
2253 this.to = to;
2254 }
2256 Type subst(Type t) {
2257 if (from.tail == null)
2258 return t;
2259 else
2260 return visit(t);
2261 }
2263 List<Type> subst(List<Type> ts) {
2264 if (from.tail == null)
2265 return ts;
2266 boolean wild = false;
2267 if (ts.nonEmpty() && from.nonEmpty()) {
2268 Type head1 = subst(ts.head);
2269 List<Type> tail1 = subst(ts.tail);
2270 if (head1 != ts.head || tail1 != ts.tail)
2271 return tail1.prepend(head1);
2272 }
2273 return ts;
2274 }
2276 public Type visitType(Type t, Void ignored) {
2277 return t;
2278 }
2280 @Override
2281 public Type visitMethodType(MethodType t, Void ignored) {
2282 List<Type> argtypes = subst(t.argtypes);
2283 Type restype = subst(t.restype);
2284 List<Type> thrown = subst(t.thrown);
2285 if (argtypes == t.argtypes &&
2286 restype == t.restype &&
2287 thrown == t.thrown)
2288 return t;
2289 else
2290 return new MethodType(argtypes, restype, thrown, t.tsym);
2291 }
2293 @Override
2294 public Type visitTypeVar(TypeVar t, Void ignored) {
2295 for (List<Type> from = this.from, to = this.to;
2296 from.nonEmpty();
2297 from = from.tail, to = to.tail) {
2298 if (t == from.head) {
2299 return to.head.withTypeVar(t);
2300 }
2301 }
2302 return t;
2303 }
2305 @Override
2306 public Type visitClassType(ClassType t, Void ignored) {
2307 if (!t.isCompound()) {
2308 List<Type> typarams = t.getTypeArguments();
2309 List<Type> typarams1 = subst(typarams);
2310 Type outer = t.getEnclosingType();
2311 Type outer1 = subst(outer);
2312 if (typarams1 == typarams && outer1 == outer)
2313 return t;
2314 else
2315 return new ClassType(outer1, typarams1, t.tsym);
2316 } else {
2317 Type st = subst(supertype(t));
2318 List<Type> is = upperBounds(subst(interfaces(t)));
2319 if (st == supertype(t) && is == interfaces(t))
2320 return t;
2321 else
2322 return makeCompoundType(is.prepend(st));
2323 }
2324 }
2326 @Override
2327 public Type visitWildcardType(WildcardType t, Void ignored) {
2328 Type bound = t.type;
2329 if (t.kind != BoundKind.UNBOUND)
2330 bound = subst(bound);
2331 if (bound == t.type) {
2332 return t;
2333 } else {
2334 if (t.isExtendsBound() && bound.isExtendsBound())
2335 bound = upperBound(bound);
2336 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2337 }
2338 }
2340 @Override
2341 public Type visitArrayType(ArrayType t, Void ignored) {
2342 Type elemtype = subst(t.elemtype);
2343 if (elemtype == t.elemtype)
2344 return t;
2345 else
2346 return new ArrayType(upperBound(elemtype), t.tsym);
2347 }
2349 @Override
2350 public Type visitForAll(ForAll t, Void ignored) {
2351 if (Type.containsAny(to, t.tvars)) {
2352 //perform alpha-renaming of free-variables in 't'
2353 //if 'to' types contain variables that are free in 't'
2354 List<Type> freevars = newInstances(t.tvars);
2355 t = new ForAll(freevars,
2356 Types.this.subst(t.qtype, t.tvars, freevars));
2357 }
2358 List<Type> tvars1 = substBounds(t.tvars, from, to);
2359 Type qtype1 = subst(t.qtype);
2360 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2361 return t;
2362 } else if (tvars1 == t.tvars) {
2363 return new ForAll(tvars1, qtype1);
2364 } else {
2365 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2366 }
2367 }
2369 @Override
2370 public Type visitErrorType(ErrorType t, Void ignored) {
2371 return t;
2372 }
2373 }
2375 public List<Type> substBounds(List<Type> tvars,
2376 List<Type> from,
2377 List<Type> to) {
2378 if (tvars.isEmpty())
2379 return tvars;
2380 ListBuffer<Type> newBoundsBuf = lb();
2381 boolean changed = false;
2382 // calculate new bounds
2383 for (Type t : tvars) {
2384 TypeVar tv = (TypeVar) t;
2385 Type bound = subst(tv.bound, from, to);
2386 if (bound != tv.bound)
2387 changed = true;
2388 newBoundsBuf.append(bound);
2389 }
2390 if (!changed)
2391 return tvars;
2392 ListBuffer<Type> newTvars = lb();
2393 // create new type variables without bounds
2394 for (Type t : tvars) {
2395 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2396 }
2397 // the new bounds should use the new type variables in place
2398 // of the old
2399 List<Type> newBounds = newBoundsBuf.toList();
2400 from = tvars;
2401 to = newTvars.toList();
2402 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2403 newBounds.head = subst(newBounds.head, from, to);
2404 }
2405 newBounds = newBoundsBuf.toList();
2406 // set the bounds of new type variables to the new bounds
2407 for (Type t : newTvars.toList()) {
2408 TypeVar tv = (TypeVar) t;
2409 tv.bound = newBounds.head;
2410 newBounds = newBounds.tail;
2411 }
2412 return newTvars.toList();
2413 }
2415 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2416 Type bound1 = subst(t.bound, from, to);
2417 if (bound1 == t.bound)
2418 return t;
2419 else {
2420 // create new type variable without bounds
2421 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2422 // the new bound should use the new type variable in place
2423 // of the old
2424 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2425 return tv;
2426 }
2427 }
2428 // </editor-fold>
2430 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2431 /**
2432 * Does t have the same bounds for quantified variables as s?
2433 */
2434 boolean hasSameBounds(ForAll t, ForAll s) {
2435 List<Type> l1 = t.tvars;
2436 List<Type> l2 = s.tvars;
2437 while (l1.nonEmpty() && l2.nonEmpty() &&
2438 isSameType(l1.head.getUpperBound(),
2439 subst(l2.head.getUpperBound(),
2440 s.tvars,
2441 t.tvars))) {
2442 l1 = l1.tail;
2443 l2 = l2.tail;
2444 }
2445 return l1.isEmpty() && l2.isEmpty();
2446 }
2447 // </editor-fold>
2449 // <editor-fold defaultstate="collapsed" desc="newInstances">
2450 /** Create new vector of type variables from list of variables
2451 * changing all recursive bounds from old to new list.
2452 */
2453 public List<Type> newInstances(List<Type> tvars) {
2454 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2455 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2456 TypeVar tv = (TypeVar) l.head;
2457 tv.bound = subst(tv.bound, tvars, tvars1);
2458 }
2459 return tvars1;
2460 }
2461 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2462 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2463 };
2464 // </editor-fold>
2466 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2467 return original.accept(methodWithParameters, newParams);
2468 }
2469 // where
2470 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2471 public Type visitType(Type t, List<Type> newParams) {
2472 throw new IllegalArgumentException("Not a method type: " + t);
2473 }
2474 public Type visitMethodType(MethodType t, List<Type> newParams) {
2475 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2476 }
2477 public Type visitForAll(ForAll t, List<Type> newParams) {
2478 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2479 }
2480 };
2482 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2483 return original.accept(methodWithThrown, newThrown);
2484 }
2485 // where
2486 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2487 public Type visitType(Type t, List<Type> newThrown) {
2488 throw new IllegalArgumentException("Not a method type: " + t);
2489 }
2490 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2491 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2492 }
2493 public Type visitForAll(ForAll t, List<Type> newThrown) {
2494 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2495 }
2496 };
2498 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2499 return original.accept(methodWithReturn, newReturn);
2500 }
2501 // where
2502 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2503 public Type visitType(Type t, Type newReturn) {
2504 throw new IllegalArgumentException("Not a method type: " + t);
2505 }
2506 public Type visitMethodType(MethodType t, Type newReturn) {
2507 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2508 }
2509 public Type visitForAll(ForAll t, Type newReturn) {
2510 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2511 }
2512 };
2514 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2515 public Type createErrorType(Type originalType) {
2516 return new ErrorType(originalType, syms.errSymbol);
2517 }
2519 public Type createErrorType(ClassSymbol c, Type originalType) {
2520 return new ErrorType(c, originalType);
2521 }
2523 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2524 return new ErrorType(name, container, originalType);
2525 }
2526 // </editor-fold>
2528 // <editor-fold defaultstate="collapsed" desc="rank">
2529 /**
2530 * The rank of a class is the length of the longest path between
2531 * the class and java.lang.Object in the class inheritance
2532 * graph. Undefined for all but reference types.
2533 */
2534 public int rank(Type t) {
2535 switch(t.tag) {
2536 case CLASS: {
2537 ClassType cls = (ClassType)t;
2538 if (cls.rank_field < 0) {
2539 Name fullname = cls.tsym.getQualifiedName();
2540 if (fullname == names.java_lang_Object)
2541 cls.rank_field = 0;
2542 else {
2543 int r = rank(supertype(cls));
2544 for (List<Type> l = interfaces(cls);
2545 l.nonEmpty();
2546 l = l.tail) {
2547 if (rank(l.head) > r)
2548 r = rank(l.head);
2549 }
2550 cls.rank_field = r + 1;
2551 }
2552 }
2553 return cls.rank_field;
2554 }
2555 case TYPEVAR: {
2556 TypeVar tvar = (TypeVar)t;
2557 if (tvar.rank_field < 0) {
2558 int r = rank(supertype(tvar));
2559 for (List<Type> l = interfaces(tvar);
2560 l.nonEmpty();
2561 l = l.tail) {
2562 if (rank(l.head) > r) r = rank(l.head);
2563 }
2564 tvar.rank_field = r + 1;
2565 }
2566 return tvar.rank_field;
2567 }
2568 case ERROR:
2569 return 0;
2570 default:
2571 throw new AssertionError();
2572 }
2573 }
2574 // </editor-fold>
2576 /**
2577 * Helper method for generating a string representation of a given type
2578 * accordingly to a given locale
2579 */
2580 public String toString(Type t, Locale locale) {
2581 return Printer.createStandardPrinter(messages).visit(t, locale);
2582 }
2584 /**
2585 * Helper method for generating a string representation of a given type
2586 * accordingly to a given locale
2587 */
2588 public String toString(Symbol t, Locale locale) {
2589 return Printer.createStandardPrinter(messages).visit(t, locale);
2590 }
2592 // <editor-fold defaultstate="collapsed" desc="toString">
2593 /**
2594 * This toString is slightly more descriptive than the one on Type.
2595 *
2596 * @deprecated Types.toString(Type t, Locale l) provides better support
2597 * for localization
2598 */
2599 @Deprecated
2600 public String toString(Type t) {
2601 if (t.tag == FORALL) {
2602 ForAll forAll = (ForAll)t;
2603 return typaramsString(forAll.tvars) + forAll.qtype;
2604 }
2605 return "" + t;
2606 }
2607 // where
2608 private String typaramsString(List<Type> tvars) {
2609 StringBuilder s = new StringBuilder();
2610 s.append('<');
2611 boolean first = true;
2612 for (Type t : tvars) {
2613 if (!first) s.append(", ");
2614 first = false;
2615 appendTyparamString(((TypeVar)t), s);
2616 }
2617 s.append('>');
2618 return s.toString();
2619 }
2620 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2621 buf.append(t);
2622 if (t.bound == null ||
2623 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2624 return;
2625 buf.append(" extends "); // Java syntax; no need for i18n
2626 Type bound = t.bound;
2627 if (!bound.isCompound()) {
2628 buf.append(bound);
2629 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2630 buf.append(supertype(t));
2631 for (Type intf : interfaces(t)) {
2632 buf.append('&');
2633 buf.append(intf);
2634 }
2635 } else {
2636 // No superclass was given in bounds.
2637 // In this case, supertype is Object, erasure is first interface.
2638 boolean first = true;
2639 for (Type intf : interfaces(t)) {
2640 if (!first) buf.append('&');
2641 first = false;
2642 buf.append(intf);
2643 }
2644 }
2645 }
2646 // </editor-fold>
2648 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2649 /**
2650 * A cache for closures.
2651 *
2652 * <p>A closure is a list of all the supertypes and interfaces of
2653 * a class or interface type, ordered by ClassSymbol.precedes
2654 * (that is, subclasses come first, arbitrary but fixed
2655 * otherwise).
2656 */
2657 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2659 /**
2660 * Returns the closure of a class or interface type.
2661 */
2662 public List<Type> closure(Type t) {
2663 List<Type> cl = closureCache.get(t);
2664 if (cl == null) {
2665 Type st = supertype(t);
2666 if (!t.isCompound()) {
2667 if (st.tag == CLASS) {
2668 cl = insert(closure(st), t);
2669 } else if (st.tag == TYPEVAR) {
2670 cl = closure(st).prepend(t);
2671 } else {
2672 cl = List.of(t);
2673 }
2674 } else {
2675 cl = closure(supertype(t));
2676 }
2677 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2678 cl = union(cl, closure(l.head));
2679 closureCache.put(t, cl);
2680 }
2681 return cl;
2682 }
2684 /**
2685 * Insert a type in a closure
2686 */
2687 public List<Type> insert(List<Type> cl, Type t) {
2688 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2689 return cl.prepend(t);
2690 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2691 return insert(cl.tail, t).prepend(cl.head);
2692 } else {
2693 return cl;
2694 }
2695 }
2697 /**
2698 * Form the union of two closures
2699 */
2700 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2701 if (cl1.isEmpty()) {
2702 return cl2;
2703 } else if (cl2.isEmpty()) {
2704 return cl1;
2705 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2706 return union(cl1.tail, cl2).prepend(cl1.head);
2707 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2708 return union(cl1, cl2.tail).prepend(cl2.head);
2709 } else {
2710 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2711 }
2712 }
2714 /**
2715 * Intersect two closures
2716 */
2717 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2718 if (cl1 == cl2)
2719 return cl1;
2720 if (cl1.isEmpty() || cl2.isEmpty())
2721 return List.nil();
2722 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2723 return intersect(cl1.tail, cl2);
2724 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2725 return intersect(cl1, cl2.tail);
2726 if (isSameType(cl1.head, cl2.head))
2727 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2728 if (cl1.head.tsym == cl2.head.tsym &&
2729 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2730 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2731 Type merge = merge(cl1.head,cl2.head);
2732 return intersect(cl1.tail, cl2.tail).prepend(merge);
2733 }
2734 if (cl1.head.isRaw() || cl2.head.isRaw())
2735 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2736 }
2737 return intersect(cl1.tail, cl2.tail);
2738 }
2739 // where
2740 class TypePair {
2741 final Type t1;
2742 final Type t2;
2743 TypePair(Type t1, Type t2) {
2744 this.t1 = t1;
2745 this.t2 = t2;
2746 }
2747 @Override
2748 public int hashCode() {
2749 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2750 }
2751 @Override
2752 public boolean equals(Object obj) {
2753 if (!(obj instanceof TypePair))
2754 return false;
2755 TypePair typePair = (TypePair)obj;
2756 return isSameType(t1, typePair.t1)
2757 && isSameType(t2, typePair.t2);
2758 }
2759 }
2760 Set<TypePair> mergeCache = new HashSet<TypePair>();
2761 private Type merge(Type c1, Type c2) {
2762 ClassType class1 = (ClassType) c1;
2763 List<Type> act1 = class1.getTypeArguments();
2764 ClassType class2 = (ClassType) c2;
2765 List<Type> act2 = class2.getTypeArguments();
2766 ListBuffer<Type> merged = new ListBuffer<Type>();
2767 List<Type> typarams = class1.tsym.type.getTypeArguments();
2769 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2770 if (containsType(act1.head, act2.head)) {
2771 merged.append(act1.head);
2772 } else if (containsType(act2.head, act1.head)) {
2773 merged.append(act2.head);
2774 } else {
2775 TypePair pair = new TypePair(c1, c2);
2776 Type m;
2777 if (mergeCache.add(pair)) {
2778 m = new WildcardType(lub(upperBound(act1.head),
2779 upperBound(act2.head)),
2780 BoundKind.EXTENDS,
2781 syms.boundClass);
2782 mergeCache.remove(pair);
2783 } else {
2784 m = new WildcardType(syms.objectType,
2785 BoundKind.UNBOUND,
2786 syms.boundClass);
2787 }
2788 merged.append(m.withTypeVar(typarams.head));
2789 }
2790 act1 = act1.tail;
2791 act2 = act2.tail;
2792 typarams = typarams.tail;
2793 }
2794 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2795 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2796 }
2798 /**
2799 * Return the minimum type of a closure, a compound type if no
2800 * unique minimum exists.
2801 */
2802 private Type compoundMin(List<Type> cl) {
2803 if (cl.isEmpty()) return syms.objectType;
2804 List<Type> compound = closureMin(cl);
2805 if (compound.isEmpty())
2806 return null;
2807 else if (compound.tail.isEmpty())
2808 return compound.head;
2809 else
2810 return makeCompoundType(compound);
2811 }
2813 /**
2814 * Return the minimum types of a closure, suitable for computing
2815 * compoundMin or glb.
2816 */
2817 private List<Type> closureMin(List<Type> cl) {
2818 ListBuffer<Type> classes = lb();
2819 ListBuffer<Type> interfaces = lb();
2820 while (!cl.isEmpty()) {
2821 Type current = cl.head;
2822 if (current.isInterface())
2823 interfaces.append(current);
2824 else
2825 classes.append(current);
2826 ListBuffer<Type> candidates = lb();
2827 for (Type t : cl.tail) {
2828 if (!isSubtypeNoCapture(current, t))
2829 candidates.append(t);
2830 }
2831 cl = candidates.toList();
2832 }
2833 return classes.appendList(interfaces).toList();
2834 }
2836 /**
2837 * Return the least upper bound of pair of types. if the lub does
2838 * not exist return null.
2839 */
2840 public Type lub(Type t1, Type t2) {
2841 return lub(List.of(t1, t2));
2842 }
2844 /**
2845 * Return the least upper bound (lub) of set of types. If the lub
2846 * does not exist return the type of null (bottom).
2847 */
2848 public Type lub(List<Type> ts) {
2849 final int ARRAY_BOUND = 1;
2850 final int CLASS_BOUND = 2;
2851 int boundkind = 0;
2852 for (Type t : ts) {
2853 switch (t.tag) {
2854 case CLASS:
2855 boundkind |= CLASS_BOUND;
2856 break;
2857 case ARRAY:
2858 boundkind |= ARRAY_BOUND;
2859 break;
2860 case TYPEVAR:
2861 do {
2862 t = t.getUpperBound();
2863 } while (t.tag == TYPEVAR);
2864 if (t.tag == ARRAY) {
2865 boundkind |= ARRAY_BOUND;
2866 } else {
2867 boundkind |= CLASS_BOUND;
2868 }
2869 break;
2870 default:
2871 if (t.isPrimitive())
2872 return syms.errType;
2873 }
2874 }
2875 switch (boundkind) {
2876 case 0:
2877 return syms.botType;
2879 case ARRAY_BOUND:
2880 // calculate lub(A[], B[])
2881 List<Type> elements = Type.map(ts, elemTypeFun);
2882 for (Type t : elements) {
2883 if (t.isPrimitive()) {
2884 // if a primitive type is found, then return
2885 // arraySuperType unless all the types are the
2886 // same
2887 Type first = ts.head;
2888 for (Type s : ts.tail) {
2889 if (!isSameType(first, s)) {
2890 // lub(int[], B[]) is Cloneable & Serializable
2891 return arraySuperType();
2892 }
2893 }
2894 // all the array types are the same, return one
2895 // lub(int[], int[]) is int[]
2896 return first;
2897 }
2898 }
2899 // lub(A[], B[]) is lub(A, B)[]
2900 return new ArrayType(lub(elements), syms.arrayClass);
2902 case CLASS_BOUND:
2903 // calculate lub(A, B)
2904 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2905 ts = ts.tail;
2906 Assert.check(!ts.isEmpty());
2907 //step 1 - compute erased candidate set (EC)
2908 List<Type> cl = erasedSupertypes(ts.head);
2909 for (Type t : ts.tail) {
2910 if (t.tag == CLASS || t.tag == TYPEVAR)
2911 cl = intersect(cl, erasedSupertypes(t));
2912 }
2913 //step 2 - compute minimal erased candidate set (MEC)
2914 List<Type> mec = closureMin(cl);
2915 //step 3 - for each element G in MEC, compute lci(Inv(G))
2916 List<Type> candidates = List.nil();
2917 for (Type erasedSupertype : mec) {
2918 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
2919 for (Type t : ts) {
2920 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
2921 }
2922 candidates = candidates.appendList(lci);
2923 }
2924 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
2925 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
2926 return compoundMin(candidates);
2928 default:
2929 // calculate lub(A, B[])
2930 List<Type> classes = List.of(arraySuperType());
2931 for (Type t : ts) {
2932 if (t.tag != ARRAY) // Filter out any arrays
2933 classes = classes.prepend(t);
2934 }
2935 // lub(A, B[]) is lub(A, arraySuperType)
2936 return lub(classes);
2937 }
2938 }
2939 // where
2940 List<Type> erasedSupertypes(Type t) {
2941 ListBuffer<Type> buf = lb();
2942 for (Type sup : closure(t)) {
2943 if (sup.tag == TYPEVAR) {
2944 buf.append(sup);
2945 } else {
2946 buf.append(erasure(sup));
2947 }
2948 }
2949 return buf.toList();
2950 }
2952 private Type arraySuperType = null;
2953 private Type arraySuperType() {
2954 // initialized lazily to avoid problems during compiler startup
2955 if (arraySuperType == null) {
2956 synchronized (this) {
2957 if (arraySuperType == null) {
2958 // JLS 10.8: all arrays implement Cloneable and Serializable.
2959 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2960 syms.cloneableType),
2961 syms.objectType);
2962 }
2963 }
2964 }
2965 return arraySuperType;
2966 }
2967 // </editor-fold>
2969 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2970 public Type glb(List<Type> ts) {
2971 Type t1 = ts.head;
2972 for (Type t2 : ts.tail) {
2973 if (t1.isErroneous())
2974 return t1;
2975 t1 = glb(t1, t2);
2976 }
2977 return t1;
2978 }
2979 //where
2980 public Type glb(Type t, Type s) {
2981 if (s == null)
2982 return t;
2983 else if (t.isPrimitive() || s.isPrimitive())
2984 return syms.errType;
2985 else if (isSubtypeNoCapture(t, s))
2986 return t;
2987 else if (isSubtypeNoCapture(s, t))
2988 return s;
2990 List<Type> closure = union(closure(t), closure(s));
2991 List<Type> bounds = closureMin(closure);
2993 if (bounds.isEmpty()) { // length == 0
2994 return syms.objectType;
2995 } else if (bounds.tail.isEmpty()) { // length == 1
2996 return bounds.head;
2997 } else { // length > 1
2998 int classCount = 0;
2999 for (Type bound : bounds)
3000 if (!bound.isInterface())
3001 classCount++;
3002 if (classCount > 1)
3003 return createErrorType(t);
3004 }
3005 return makeCompoundType(bounds);
3006 }
3007 // </editor-fold>
3009 // <editor-fold defaultstate="collapsed" desc="hashCode">
3010 /**
3011 * Compute a hash code on a type.
3012 */
3013 public static int hashCode(Type t) {
3014 return hashCode.visit(t);
3015 }
3016 // where
3017 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3019 public Integer visitType(Type t, Void ignored) {
3020 return t.tag;
3021 }
3023 @Override
3024 public Integer visitClassType(ClassType t, Void ignored) {
3025 int result = visit(t.getEnclosingType());
3026 result *= 127;
3027 result += t.tsym.flatName().hashCode();
3028 for (Type s : t.getTypeArguments()) {
3029 result *= 127;
3030 result += visit(s);
3031 }
3032 return result;
3033 }
3035 @Override
3036 public Integer visitWildcardType(WildcardType t, Void ignored) {
3037 int result = t.kind.hashCode();
3038 if (t.type != null) {
3039 result *= 127;
3040 result += visit(t.type);
3041 }
3042 return result;
3043 }
3045 @Override
3046 public Integer visitArrayType(ArrayType t, Void ignored) {
3047 return visit(t.elemtype) + 12;
3048 }
3050 @Override
3051 public Integer visitTypeVar(TypeVar t, Void ignored) {
3052 return System.identityHashCode(t.tsym);
3053 }
3055 @Override
3056 public Integer visitUndetVar(UndetVar t, Void ignored) {
3057 return System.identityHashCode(t);
3058 }
3060 @Override
3061 public Integer visitErrorType(ErrorType t, Void ignored) {
3062 return 0;
3063 }
3064 };
3065 // </editor-fold>
3067 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3068 /**
3069 * Does t have a result that is a subtype of the result type of s,
3070 * suitable for covariant returns? It is assumed that both types
3071 * are (possibly polymorphic) method types. Monomorphic method
3072 * types are handled in the obvious way. Polymorphic method types
3073 * require renaming all type variables of one to corresponding
3074 * type variables in the other, where correspondence is by
3075 * position in the type parameter list. */
3076 public boolean resultSubtype(Type t, Type s, Warner warner) {
3077 List<Type> tvars = t.getTypeArguments();
3078 List<Type> svars = s.getTypeArguments();
3079 Type tres = t.getReturnType();
3080 Type sres = subst(s.getReturnType(), svars, tvars);
3081 return covariantReturnType(tres, sres, warner);
3082 }
3084 /**
3085 * Return-Type-Substitutable.
3086 * @jls section 8.4.5
3087 */
3088 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3089 if (hasSameArgs(r1, r2))
3090 return resultSubtype(r1, r2, Warner.noWarnings);
3091 else
3092 return covariantReturnType(r1.getReturnType(),
3093 erasure(r2.getReturnType()),
3094 Warner.noWarnings);
3095 }
3097 public boolean returnTypeSubstitutable(Type r1,
3098 Type r2, Type r2res,
3099 Warner warner) {
3100 if (isSameType(r1.getReturnType(), r2res))
3101 return true;
3102 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3103 return false;
3105 if (hasSameArgs(r1, r2))
3106 return covariantReturnType(r1.getReturnType(), r2res, warner);
3107 if (!allowCovariantReturns)
3108 return false;
3109 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3110 return true;
3111 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3112 return false;
3113 warner.warn(LintCategory.UNCHECKED);
3114 return true;
3115 }
3117 /**
3118 * Is t an appropriate return type in an overrider for a
3119 * method that returns s?
3120 */
3121 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3122 return
3123 isSameType(t, s) ||
3124 allowCovariantReturns &&
3125 !t.isPrimitive() &&
3126 !s.isPrimitive() &&
3127 isAssignable(t, s, warner);
3128 }
3129 // </editor-fold>
3131 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3132 /**
3133 * Return the class that boxes the given primitive.
3134 */
3135 public ClassSymbol boxedClass(Type t) {
3136 return reader.enterClass(syms.boxedName[t.tag]);
3137 }
3139 /**
3140 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3141 */
3142 public Type boxedTypeOrType(Type t) {
3143 return t.isPrimitive() ?
3144 boxedClass(t).type :
3145 t;
3146 }
3148 /**
3149 * Return the primitive type corresponding to a boxed type.
3150 */
3151 public Type unboxedType(Type t) {
3152 if (allowBoxing) {
3153 for (int i=0; i<syms.boxedName.length; i++) {
3154 Name box = syms.boxedName[i];
3155 if (box != null &&
3156 asSuper(t, reader.enterClass(box)) != null)
3157 return syms.typeOfTag[i];
3158 }
3159 }
3160 return Type.noType;
3161 }
3162 // </editor-fold>
3164 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3165 /*
3166 * JLS 5.1.10 Capture Conversion:
3167 *
3168 * Let G name a generic type declaration with n formal type
3169 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3170 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3171 * where, for 1 <= i <= n:
3172 *
3173 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3174 * Si is a fresh type variable whose upper bound is
3175 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3176 * type.
3177 *
3178 * + If Ti is a wildcard type argument of the form ? extends Bi,
3179 * then Si is a fresh type variable whose upper bound is
3180 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3181 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3182 * a compile-time error if for any two classes (not interfaces)
3183 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3184 *
3185 * + If Ti is a wildcard type argument of the form ? super Bi,
3186 * then Si is a fresh type variable whose upper bound is
3187 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3188 *
3189 * + Otherwise, Si = Ti.
3190 *
3191 * Capture conversion on any type other than a parameterized type
3192 * (4.5) acts as an identity conversion (5.1.1). Capture
3193 * conversions never require a special action at run time and
3194 * therefore never throw an exception at run time.
3195 *
3196 * Capture conversion is not applied recursively.
3197 */
3198 /**
3199 * Capture conversion as specified by the JLS.
3200 */
3202 public List<Type> capture(List<Type> ts) {
3203 List<Type> buf = List.nil();
3204 for (Type t : ts) {
3205 buf = buf.prepend(capture(t));
3206 }
3207 return buf.reverse();
3208 }
3209 public Type capture(Type t) {
3210 if (t.tag != CLASS)
3211 return t;
3212 if (t.getEnclosingType() != Type.noType) {
3213 Type capturedEncl = capture(t.getEnclosingType());
3214 if (capturedEncl != t.getEnclosingType()) {
3215 Type type1 = memberType(capturedEncl, t.tsym);
3216 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3217 }
3218 }
3219 ClassType cls = (ClassType)t;
3220 if (cls.isRaw() || !cls.isParameterized())
3221 return cls;
3223 ClassType G = (ClassType)cls.asElement().asType();
3224 List<Type> A = G.getTypeArguments();
3225 List<Type> T = cls.getTypeArguments();
3226 List<Type> S = freshTypeVariables(T);
3228 List<Type> currentA = A;
3229 List<Type> currentT = T;
3230 List<Type> currentS = S;
3231 boolean captured = false;
3232 while (!currentA.isEmpty() &&
3233 !currentT.isEmpty() &&
3234 !currentS.isEmpty()) {
3235 if (currentS.head != currentT.head) {
3236 captured = true;
3237 WildcardType Ti = (WildcardType)currentT.head;
3238 Type Ui = currentA.head.getUpperBound();
3239 CapturedType Si = (CapturedType)currentS.head;
3240 if (Ui == null)
3241 Ui = syms.objectType;
3242 switch (Ti.kind) {
3243 case UNBOUND:
3244 Si.bound = subst(Ui, A, S);
3245 Si.lower = syms.botType;
3246 break;
3247 case EXTENDS:
3248 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3249 Si.lower = syms.botType;
3250 break;
3251 case SUPER:
3252 Si.bound = subst(Ui, A, S);
3253 Si.lower = Ti.getSuperBound();
3254 break;
3255 }
3256 if (Si.bound == Si.lower)
3257 currentS.head = Si.bound;
3258 }
3259 currentA = currentA.tail;
3260 currentT = currentT.tail;
3261 currentS = currentS.tail;
3262 }
3263 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3264 return erasure(t); // some "rare" type involved
3266 if (captured)
3267 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3268 else
3269 return t;
3270 }
3271 // where
3272 public List<Type> freshTypeVariables(List<Type> types) {
3273 ListBuffer<Type> result = lb();
3274 for (Type t : types) {
3275 if (t.tag == WILDCARD) {
3276 Type bound = ((WildcardType)t).getExtendsBound();
3277 if (bound == null)
3278 bound = syms.objectType;
3279 result.append(new CapturedType(capturedName,
3280 syms.noSymbol,
3281 bound,
3282 syms.botType,
3283 (WildcardType)t));
3284 } else {
3285 result.append(t);
3286 }
3287 }
3288 return result.toList();
3289 }
3290 // </editor-fold>
3292 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3293 private List<Type> upperBounds(List<Type> ss) {
3294 if (ss.isEmpty()) return ss;
3295 Type head = upperBound(ss.head);
3296 List<Type> tail = upperBounds(ss.tail);
3297 if (head != ss.head || tail != ss.tail)
3298 return tail.prepend(head);
3299 else
3300 return ss;
3301 }
3303 private boolean sideCast(Type from, Type to, Warner warn) {
3304 // We are casting from type $from$ to type $to$, which are
3305 // non-final unrelated types. This method
3306 // tries to reject a cast by transferring type parameters
3307 // from $to$ to $from$ by common superinterfaces.
3308 boolean reverse = false;
3309 Type target = to;
3310 if ((to.tsym.flags() & INTERFACE) == 0) {
3311 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3312 reverse = true;
3313 to = from;
3314 from = target;
3315 }
3316 List<Type> commonSupers = superClosure(to, erasure(from));
3317 boolean giveWarning = commonSupers.isEmpty();
3318 // The arguments to the supers could be unified here to
3319 // get a more accurate analysis
3320 while (commonSupers.nonEmpty()) {
3321 Type t1 = asSuper(from, commonSupers.head.tsym);
3322 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3323 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3324 return false;
3325 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3326 commonSupers = commonSupers.tail;
3327 }
3328 if (giveWarning && !isReifiable(reverse ? from : to))
3329 warn.warn(LintCategory.UNCHECKED);
3330 if (!allowCovariantReturns)
3331 // reject if there is a common method signature with
3332 // incompatible return types.
3333 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3334 return true;
3335 }
3337 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3338 // We are casting from type $from$ to type $to$, which are
3339 // unrelated types one of which is final and the other of
3340 // which is an interface. This method
3341 // tries to reject a cast by transferring type parameters
3342 // from the final class to the interface.
3343 boolean reverse = false;
3344 Type target = to;
3345 if ((to.tsym.flags() & INTERFACE) == 0) {
3346 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3347 reverse = true;
3348 to = from;
3349 from = target;
3350 }
3351 Assert.check((from.tsym.flags() & FINAL) != 0);
3352 Type t1 = asSuper(from, to.tsym);
3353 if (t1 == null) return false;
3354 Type t2 = to;
3355 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3356 return false;
3357 if (!allowCovariantReturns)
3358 // reject if there is a common method signature with
3359 // incompatible return types.
3360 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3361 if (!isReifiable(target) &&
3362 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3363 warn.warn(LintCategory.UNCHECKED);
3364 return true;
3365 }
3367 private boolean giveWarning(Type from, Type to) {
3368 Type subFrom = asSub(from, to.tsym);
3369 return to.isParameterized() &&
3370 (!(isUnbounded(to) ||
3371 isSubtype(from, to) ||
3372 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3373 }
3375 private List<Type> superClosure(Type t, Type s) {
3376 List<Type> cl = List.nil();
3377 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3378 if (isSubtype(s, erasure(l.head))) {
3379 cl = insert(cl, l.head);
3380 } else {
3381 cl = union(cl, superClosure(l.head, s));
3382 }
3383 }
3384 return cl;
3385 }
3387 private boolean containsTypeEquivalent(Type t, Type s) {
3388 return
3389 isSameType(t, s) || // shortcut
3390 containsType(t, s) && containsType(s, t);
3391 }
3393 // <editor-fold defaultstate="collapsed" desc="adapt">
3394 /**
3395 * Adapt a type by computing a substitution which maps a source
3396 * type to a target type.
3397 *
3398 * @param source the source type
3399 * @param target the target type
3400 * @param from the type variables of the computed substitution
3401 * @param to the types of the computed substitution.
3402 */
3403 public void adapt(Type source,
3404 Type target,
3405 ListBuffer<Type> from,
3406 ListBuffer<Type> to) throws AdaptFailure {
3407 new Adapter(from, to).adapt(source, target);
3408 }
3410 class Adapter extends SimpleVisitor<Void, Type> {
3412 ListBuffer<Type> from;
3413 ListBuffer<Type> to;
3414 Map<Symbol,Type> mapping;
3416 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3417 this.from = from;
3418 this.to = to;
3419 mapping = new HashMap<Symbol,Type>();
3420 }
3422 public void adapt(Type source, Type target) throws AdaptFailure {
3423 visit(source, target);
3424 List<Type> fromList = from.toList();
3425 List<Type> toList = to.toList();
3426 while (!fromList.isEmpty()) {
3427 Type val = mapping.get(fromList.head.tsym);
3428 if (toList.head != val)
3429 toList.head = val;
3430 fromList = fromList.tail;
3431 toList = toList.tail;
3432 }
3433 }
3435 @Override
3436 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3437 if (target.tag == CLASS)
3438 adaptRecursive(source.allparams(), target.allparams());
3439 return null;
3440 }
3442 @Override
3443 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3444 if (target.tag == ARRAY)
3445 adaptRecursive(elemtype(source), elemtype(target));
3446 return null;
3447 }
3449 @Override
3450 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3451 if (source.isExtendsBound())
3452 adaptRecursive(upperBound(source), upperBound(target));
3453 else if (source.isSuperBound())
3454 adaptRecursive(lowerBound(source), lowerBound(target));
3455 return null;
3456 }
3458 @Override
3459 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3460 // Check to see if there is
3461 // already a mapping for $source$, in which case
3462 // the old mapping will be merged with the new
3463 Type val = mapping.get(source.tsym);
3464 if (val != null) {
3465 if (val.isSuperBound() && target.isSuperBound()) {
3466 val = isSubtype(lowerBound(val), lowerBound(target))
3467 ? target : val;
3468 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3469 val = isSubtype(upperBound(val), upperBound(target))
3470 ? val : target;
3471 } else if (!isSameType(val, target)) {
3472 throw new AdaptFailure();
3473 }
3474 } else {
3475 val = target;
3476 from.append(source);
3477 to.append(target);
3478 }
3479 mapping.put(source.tsym, val);
3480 return null;
3481 }
3483 @Override
3484 public Void visitType(Type source, Type target) {
3485 return null;
3486 }
3488 private Set<TypePair> cache = new HashSet<TypePair>();
3490 private void adaptRecursive(Type source, Type target) {
3491 TypePair pair = new TypePair(source, target);
3492 if (cache.add(pair)) {
3493 try {
3494 visit(source, target);
3495 } finally {
3496 cache.remove(pair);
3497 }
3498 }
3499 }
3501 private void adaptRecursive(List<Type> source, List<Type> target) {
3502 if (source.length() == target.length()) {
3503 while (source.nonEmpty()) {
3504 adaptRecursive(source.head, target.head);
3505 source = source.tail;
3506 target = target.tail;
3507 }
3508 }
3509 }
3510 }
3512 public static class AdaptFailure extends RuntimeException {
3513 static final long serialVersionUID = -7490231548272701566L;
3514 }
3516 private void adaptSelf(Type t,
3517 ListBuffer<Type> from,
3518 ListBuffer<Type> to) {
3519 try {
3520 //if (t.tsym.type != t)
3521 adapt(t.tsym.type, t, from, to);
3522 } catch (AdaptFailure ex) {
3523 // Adapt should never fail calculating a mapping from
3524 // t.tsym.type to t as there can be no merge problem.
3525 throw new AssertionError(ex);
3526 }
3527 }
3528 // </editor-fold>
3530 /**
3531 * Rewrite all type variables (universal quantifiers) in the given
3532 * type to wildcards (existential quantifiers). This is used to
3533 * determine if a cast is allowed. For example, if high is true
3534 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3535 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3536 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3537 * List<Integer>} with a warning.
3538 * @param t a type
3539 * @param high if true return an upper bound; otherwise a lower
3540 * bound
3541 * @param rewriteTypeVars only rewrite captured wildcards if false;
3542 * otherwise rewrite all type variables
3543 * @return the type rewritten with wildcards (existential
3544 * quantifiers) only
3545 */
3546 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3547 return new Rewriter(high, rewriteTypeVars).visit(t);
3548 }
3550 class Rewriter extends UnaryVisitor<Type> {
3552 boolean high;
3553 boolean rewriteTypeVars;
3555 Rewriter(boolean high, boolean rewriteTypeVars) {
3556 this.high = high;
3557 this.rewriteTypeVars = rewriteTypeVars;
3558 }
3560 @Override
3561 public Type visitClassType(ClassType t, Void s) {
3562 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3563 boolean changed = false;
3564 for (Type arg : t.allparams()) {
3565 Type bound = visit(arg);
3566 if (arg != bound) {
3567 changed = true;
3568 }
3569 rewritten.append(bound);
3570 }
3571 if (changed)
3572 return subst(t.tsym.type,
3573 t.tsym.type.allparams(),
3574 rewritten.toList());
3575 else
3576 return t;
3577 }
3579 public Type visitType(Type t, Void s) {
3580 return high ? upperBound(t) : lowerBound(t);
3581 }
3583 @Override
3584 public Type visitCapturedType(CapturedType t, Void s) {
3585 Type bound = visitWildcardType(t.wildcard, null);
3586 return (bound.contains(t)) ?
3587 erasure(bound) :
3588 bound;
3589 }
3591 @Override
3592 public Type visitTypeVar(TypeVar t, Void s) {
3593 if (rewriteTypeVars) {
3594 Type bound = high ?
3595 (t.bound.contains(t) ?
3596 erasure(t.bound) :
3597 visit(t.bound)) :
3598 syms.botType;
3599 return rewriteAsWildcardType(bound, t);
3600 }
3601 else
3602 return t;
3603 }
3605 @Override
3606 public Type visitWildcardType(WildcardType t, Void s) {
3607 Type bound = high ? t.getExtendsBound() :
3608 t.getSuperBound();
3609 if (bound == null)
3610 bound = high ? syms.objectType : syms.botType;
3611 return rewriteAsWildcardType(visit(bound), t.bound);
3612 }
3614 private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
3615 return high ?
3616 makeExtendsWildcard(B(bound), formal) :
3617 makeSuperWildcard(B(bound), formal);
3618 }
3620 Type B(Type t) {
3621 while (t.tag == WILDCARD) {
3622 WildcardType w = (WildcardType)t;
3623 t = high ?
3624 w.getExtendsBound() :
3625 w.getSuperBound();
3626 if (t == null) {
3627 t = high ? syms.objectType : syms.botType;
3628 }
3629 }
3630 return t;
3631 }
3632 }
3635 /**
3636 * Create a wildcard with the given upper (extends) bound; create
3637 * an unbounded wildcard if bound is Object.
3638 *
3639 * @param bound the upper bound
3640 * @param formal the formal type parameter that will be
3641 * substituted by the wildcard
3642 */
3643 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3644 if (bound == syms.objectType) {
3645 return new WildcardType(syms.objectType,
3646 BoundKind.UNBOUND,
3647 syms.boundClass,
3648 formal);
3649 } else {
3650 return new WildcardType(bound,
3651 BoundKind.EXTENDS,
3652 syms.boundClass,
3653 formal);
3654 }
3655 }
3657 /**
3658 * Create a wildcard with the given lower (super) bound; create an
3659 * unbounded wildcard if bound is bottom (type of {@code null}).
3660 *
3661 * @param bound the lower bound
3662 * @param formal the formal type parameter that will be
3663 * substituted by the wildcard
3664 */
3665 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3666 if (bound.tag == BOT) {
3667 return new WildcardType(syms.objectType,
3668 BoundKind.UNBOUND,
3669 syms.boundClass,
3670 formal);
3671 } else {
3672 return new WildcardType(bound,
3673 BoundKind.SUPER,
3674 syms.boundClass,
3675 formal);
3676 }
3677 }
3679 /**
3680 * A wrapper for a type that allows use in sets.
3681 */
3682 class SingletonType {
3683 final Type t;
3684 SingletonType(Type t) {
3685 this.t = t;
3686 }
3687 public int hashCode() {
3688 return Types.hashCode(t);
3689 }
3690 public boolean equals(Object obj) {
3691 return (obj instanceof SingletonType) &&
3692 isSameType(t, ((SingletonType)obj).t);
3693 }
3694 public String toString() {
3695 return t.toString();
3696 }
3697 }
3698 // </editor-fold>
3700 // <editor-fold defaultstate="collapsed" desc="Visitors">
3701 /**
3702 * A default visitor for types. All visitor methods except
3703 * visitType are implemented by delegating to visitType. Concrete
3704 * subclasses must provide an implementation of visitType and can
3705 * override other methods as needed.
3706 *
3707 * @param <R> the return type of the operation implemented by this
3708 * visitor; use Void if no return type is needed.
3709 * @param <S> the type of the second argument (the first being the
3710 * type itself) of the operation implemented by this visitor; use
3711 * Void if a second argument is not needed.
3712 */
3713 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3714 final public R visit(Type t, S s) { return t.accept(this, s); }
3715 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3716 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3717 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3718 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3719 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3720 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3721 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3722 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3723 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3724 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3725 }
3727 /**
3728 * A default visitor for symbols. All visitor methods except
3729 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3730 * subclasses must provide an implementation of visitSymbol and can
3731 * override other methods as needed.
3732 *
3733 * @param <R> the return type of the operation implemented by this
3734 * visitor; use Void if no return type is needed.
3735 * @param <S> the type of the second argument (the first being the
3736 * symbol itself) of the operation implemented by this visitor; use
3737 * Void if a second argument is not needed.
3738 */
3739 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3740 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3741 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3742 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3743 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3744 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3745 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3746 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3747 }
3749 /**
3750 * A <em>simple</em> visitor for types. This visitor is simple as
3751 * captured wildcards, for-all types (generic methods), and
3752 * undetermined type variables (part of inference) are hidden.
3753 * Captured wildcards are hidden by treating them as type
3754 * variables and the rest are hidden by visiting their qtypes.
3755 *
3756 * @param <R> the return type of the operation implemented by this
3757 * visitor; use Void if no return type is needed.
3758 * @param <S> the type of the second argument (the first being the
3759 * type itself) of the operation implemented by this visitor; use
3760 * Void if a second argument is not needed.
3761 */
3762 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3763 @Override
3764 public R visitCapturedType(CapturedType t, S s) {
3765 return visitTypeVar(t, s);
3766 }
3767 @Override
3768 public R visitForAll(ForAll t, S s) {
3769 return visit(t.qtype, s);
3770 }
3771 @Override
3772 public R visitUndetVar(UndetVar t, S s) {
3773 return visit(t.qtype, s);
3774 }
3775 }
3777 /**
3778 * A plain relation on types. That is a 2-ary function on the
3779 * form Type × Type → Boolean.
3780 * <!-- In plain text: Type x Type -> Boolean -->
3781 */
3782 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3784 /**
3785 * A convenience visitor for implementing operations that only
3786 * require one argument (the type itself), that is, unary
3787 * operations.
3788 *
3789 * @param <R> the return type of the operation implemented by this
3790 * visitor; use Void if no return type is needed.
3791 */
3792 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3793 final public R visit(Type t) { return t.accept(this, null); }
3794 }
3796 /**
3797 * A visitor for implementing a mapping from types to types. The
3798 * default behavior of this class is to implement the identity
3799 * mapping (mapping a type to itself). This can be overridden in
3800 * subclasses.
3801 *
3802 * @param <S> the type of the second argument (the first being the
3803 * type itself) of this mapping; use Void if a second argument is
3804 * not needed.
3805 */
3806 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3807 final public Type visit(Type t) { return t.accept(this, null); }
3808 public Type visitType(Type t, S s) { return t; }
3809 }
3810 // </editor-fold>
3813 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3815 public RetentionPolicy getRetention(Attribute.Compound a) {
3816 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3817 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3818 if (c != null) {
3819 Attribute value = c.member(names.value);
3820 if (value != null && value instanceof Attribute.Enum) {
3821 Name levelName = ((Attribute.Enum)value).value.name;
3822 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3823 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3824 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3825 else ;// /* fail soft */ throw new AssertionError(levelName);
3826 }
3827 }
3828 return vis;
3829 }
3830 // </editor-fold>
3831 }