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