Mon, 09 Mar 2009 23:53:41 -0700
Merge
1 /*
2 * Copyright 2003-2009 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.code;
28 import java.util.*;
30 import com.sun.tools.javac.api.Messages;
32 import com.sun.tools.javac.util.*;
33 import com.sun.tools.javac.util.List;
35 import com.sun.tools.javac.jvm.ClassReader;
36 import com.sun.tools.javac.comp.Check;
38 import static com.sun.tools.javac.code.Type.*;
39 import static com.sun.tools.javac.code.TypeTags.*;
40 import static com.sun.tools.javac.code.Symbol.*;
41 import static com.sun.tools.javac.code.Flags.*;
42 import static com.sun.tools.javac.code.BoundKind.*;
43 import static com.sun.tools.javac.util.ListBuffer.lb;
45 /**
46 * Utility class containing various operations on types.
47 *
48 * <p>Unless other names are more illustrative, the following naming
49 * conventions should be observed in this file:
50 *
51 * <dl>
52 * <dt>t</dt>
53 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
54 * <dt>s</dt>
55 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
56 * <dt>ts</dt>
57 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
58 * <dt>ss</dt>
59 * <dd>A second list of types should be named ss.</dd>
60 * </dl>
61 *
62 * <p><b>This is NOT part of any API supported by Sun Microsystems.
63 * If you write code that depends on this, you do so at your own risk.
64 * This code and its internal interfaces are subject to change or
65 * deletion without notice.</b>
66 */
67 public class Types {
68 protected static final Context.Key<Types> typesKey =
69 new Context.Key<Types>();
71 final Symtab syms;
72 final JavacMessages messages;
73 final Names names;
74 final boolean allowBoxing;
75 final ClassReader reader;
76 final Source source;
77 final Check chk;
78 List<Warner> warnStack = List.nil();
79 final Name capturedName;
81 // <editor-fold defaultstate="collapsed" desc="Instantiating">
82 public static Types instance(Context context) {
83 Types instance = context.get(typesKey);
84 if (instance == null)
85 instance = new Types(context);
86 return instance;
87 }
89 protected Types(Context context) {
90 context.put(typesKey, this);
91 syms = Symtab.instance(context);
92 names = Names.instance(context);
93 allowBoxing = Source.instance(context).allowBoxing();
94 reader = ClassReader.instance(context);
95 source = Source.instance(context);
96 chk = Check.instance(context);
97 capturedName = names.fromString("<captured wildcard>");
98 messages = JavacMessages.instance(context);
99 }
100 // </editor-fold>
102 // <editor-fold defaultstate="collapsed" desc="upperBound">
103 /**
104 * The "rvalue conversion".<br>
105 * The upper bound of most types is the type
106 * itself. Wildcards, on the other hand have upper
107 * and lower bounds.
108 * @param t a type
109 * @return the upper bound of the given type
110 */
111 public Type upperBound(Type t) {
112 return upperBound.visit(t);
113 }
114 // where
115 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
117 @Override
118 public Type visitWildcardType(WildcardType t, Void ignored) {
119 if (t.isSuperBound())
120 return t.bound == null ? syms.objectType : t.bound.bound;
121 else
122 return visit(t.type);
123 }
125 @Override
126 public Type visitCapturedType(CapturedType t, Void ignored) {
127 return visit(t.bound);
128 }
129 };
130 // </editor-fold>
132 // <editor-fold defaultstate="collapsed" desc="lowerBound">
133 /**
134 * The "lvalue conversion".<br>
135 * The lower bound of most types is the type
136 * itself. Wildcards, on the other hand have upper
137 * and lower bounds.
138 * @param t a type
139 * @return the lower bound of the given type
140 */
141 public Type lowerBound(Type t) {
142 return lowerBound.visit(t);
143 }
144 // where
145 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
147 @Override
148 public Type visitWildcardType(WildcardType t, Void ignored) {
149 return t.isExtendsBound() ? syms.botType : visit(t.type);
150 }
152 @Override
153 public Type visitCapturedType(CapturedType t, Void ignored) {
154 return visit(t.getLowerBound());
155 }
156 };
157 // </editor-fold>
159 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
160 /**
161 * Checks that all the arguments to a class are unbounded
162 * wildcards or something else that doesn't make any restrictions
163 * on the arguments. If a class isUnbounded, a raw super- or
164 * subclass can be cast to it without a warning.
165 * @param t a type
166 * @return true iff the given type is unbounded or raw
167 */
168 public boolean isUnbounded(Type t) {
169 return isUnbounded.visit(t);
170 }
171 // where
172 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
174 public Boolean visitType(Type t, Void ignored) {
175 return true;
176 }
178 @Override
179 public Boolean visitClassType(ClassType t, Void ignored) {
180 List<Type> parms = t.tsym.type.allparams();
181 List<Type> args = t.allparams();
182 while (parms.nonEmpty()) {
183 WildcardType unb = new WildcardType(syms.objectType,
184 BoundKind.UNBOUND,
185 syms.boundClass,
186 (TypeVar)parms.head);
187 if (!containsType(args.head, unb))
188 return false;
189 parms = parms.tail;
190 args = args.tail;
191 }
192 return true;
193 }
194 };
195 // </editor-fold>
197 // <editor-fold defaultstate="collapsed" desc="asSub">
198 /**
199 * Return the least specific subtype of t that starts with symbol
200 * sym. If none exists, return null. The least specific subtype
201 * is determined as follows:
202 *
203 * <p>If there is exactly one parameterized instance of sym that is a
204 * subtype of t, that parameterized instance is returned.<br>
205 * Otherwise, if the plain type or raw type `sym' is a subtype of
206 * type t, the type `sym' itself is returned. Otherwise, null is
207 * returned.
208 */
209 public Type asSub(Type t, Symbol sym) {
210 return asSub.visit(t, sym);
211 }
212 // where
213 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
215 public Type visitType(Type t, Symbol sym) {
216 return null;
217 }
219 @Override
220 public Type visitClassType(ClassType t, Symbol sym) {
221 if (t.tsym == sym)
222 return t;
223 Type base = asSuper(sym.type, t.tsym);
224 if (base == null)
225 return null;
226 ListBuffer<Type> from = new ListBuffer<Type>();
227 ListBuffer<Type> to = new ListBuffer<Type>();
228 try {
229 adapt(base, t, from, to);
230 } catch (AdaptFailure ex) {
231 return null;
232 }
233 Type res = subst(sym.type, from.toList(), to.toList());
234 if (!isSubtype(res, t))
235 return null;
236 ListBuffer<Type> openVars = new ListBuffer<Type>();
237 for (List<Type> l = sym.type.allparams();
238 l.nonEmpty(); l = l.tail)
239 if (res.contains(l.head) && !t.contains(l.head))
240 openVars.append(l.head);
241 if (openVars.nonEmpty()) {
242 if (t.isRaw()) {
243 // The subtype of a raw type is raw
244 res = erasure(res);
245 } else {
246 // Unbound type arguments default to ?
247 List<Type> opens = openVars.toList();
248 ListBuffer<Type> qs = new ListBuffer<Type>();
249 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
250 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
251 }
252 res = subst(res, opens, qs.toList());
253 }
254 }
255 return res;
256 }
258 @Override
259 public Type visitErrorType(ErrorType t, Symbol sym) {
260 return t;
261 }
262 };
263 // </editor-fold>
265 // <editor-fold defaultstate="collapsed" desc="isConvertible">
266 /**
267 * Is t a subtype of or convertiable via boxing/unboxing
268 * convertions to s?
269 */
270 public boolean isConvertible(Type t, Type s, Warner warn) {
271 boolean tPrimitive = t.isPrimitive();
272 boolean sPrimitive = s.isPrimitive();
273 if (tPrimitive == sPrimitive)
274 return isSubtypeUnchecked(t, s, warn);
275 if (!allowBoxing) return false;
276 return tPrimitive
277 ? isSubtype(boxedClass(t).type, s)
278 : isSubtype(unboxedType(t), s);
279 }
281 /**
282 * Is t a subtype of or convertiable via boxing/unboxing
283 * convertions to s?
284 */
285 public boolean isConvertible(Type t, Type s) {
286 return isConvertible(t, s, Warner.noWarnings);
287 }
288 // </editor-fold>
290 // <editor-fold defaultstate="collapsed" desc="isSubtype">
291 /**
292 * Is t an unchecked subtype of s?
293 */
294 public boolean isSubtypeUnchecked(Type t, Type s) {
295 return isSubtypeUnchecked(t, s, Warner.noWarnings);
296 }
297 /**
298 * Is t an unchecked subtype of s?
299 */
300 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
301 if (t.tag == ARRAY && s.tag == ARRAY) {
302 return (((ArrayType)t).elemtype.tag <= lastBaseTag)
303 ? isSameType(elemtype(t), elemtype(s))
304 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
305 } else if (isSubtype(t, s)) {
306 return true;
307 }
308 else if (t.tag == TYPEVAR) {
309 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
310 }
311 else if (s.tag == UNDETVAR) {
312 UndetVar uv = (UndetVar)s;
313 if (uv.inst != null)
314 return isSubtypeUnchecked(t, uv.inst, warn);
315 }
316 else if (!s.isRaw()) {
317 Type t2 = asSuper(t, s.tsym);
318 if (t2 != null && t2.isRaw()) {
319 if (isReifiable(s))
320 warn.silentUnchecked();
321 else
322 warn.warnUnchecked();
323 return true;
324 }
325 }
326 return false;
327 }
329 /**
330 * Is t a subtype of s?<br>
331 * (not defined for Method and ForAll types)
332 */
333 final public boolean isSubtype(Type t, Type s) {
334 return isSubtype(t, s, true);
335 }
336 final public boolean isSubtypeNoCapture(Type t, Type s) {
337 return isSubtype(t, s, false);
338 }
339 public boolean isSubtype(Type t, Type s, boolean capture) {
340 if (t == s)
341 return true;
343 if (s.tag >= firstPartialTag)
344 return isSuperType(s, t);
346 Type lower = lowerBound(s);
347 if (s != lower)
348 return isSubtype(capture ? capture(t) : t, lower, false);
350 return isSubtype.visit(capture ? capture(t) : t, s);
351 }
352 // where
353 private TypeRelation isSubtype = new TypeRelation()
354 {
355 public Boolean visitType(Type t, Type s) {
356 switch (t.tag) {
357 case BYTE: case CHAR:
358 return (t.tag == s.tag ||
359 t.tag + 2 <= s.tag && s.tag <= DOUBLE);
360 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
361 return t.tag <= s.tag && s.tag <= DOUBLE;
362 case BOOLEAN: case VOID:
363 return t.tag == s.tag;
364 case TYPEVAR:
365 return isSubtypeNoCapture(t.getUpperBound(), s);
366 case BOT:
367 return
368 s.tag == BOT || s.tag == CLASS ||
369 s.tag == ARRAY || s.tag == TYPEVAR;
370 case NONE:
371 return false;
372 default:
373 throw new AssertionError("isSubtype " + t.tag);
374 }
375 }
377 private Set<TypePair> cache = new HashSet<TypePair>();
379 private boolean containsTypeRecursive(Type t, Type s) {
380 TypePair pair = new TypePair(t, s);
381 if (cache.add(pair)) {
382 try {
383 return containsType(t.getTypeArguments(),
384 s.getTypeArguments());
385 } finally {
386 cache.remove(pair);
387 }
388 } else {
389 return containsType(t.getTypeArguments(),
390 rewriteSupers(s).getTypeArguments());
391 }
392 }
394 private Type rewriteSupers(Type t) {
395 if (!t.isParameterized())
396 return t;
397 ListBuffer<Type> from = lb();
398 ListBuffer<Type> to = lb();
399 adaptSelf(t, from, to);
400 if (from.isEmpty())
401 return t;
402 ListBuffer<Type> rewrite = lb();
403 boolean changed = false;
404 for (Type orig : to.toList()) {
405 Type s = rewriteSupers(orig);
406 if (s.isSuperBound() && !s.isExtendsBound()) {
407 s = new WildcardType(syms.objectType,
408 BoundKind.UNBOUND,
409 syms.boundClass);
410 changed = true;
411 } else if (s != orig) {
412 s = new WildcardType(upperBound(s),
413 BoundKind.EXTENDS,
414 syms.boundClass);
415 changed = true;
416 }
417 rewrite.append(s);
418 }
419 if (changed)
420 return subst(t.tsym.type, from.toList(), rewrite.toList());
421 else
422 return t;
423 }
425 @Override
426 public Boolean visitClassType(ClassType t, Type s) {
427 Type sup = asSuper(t, s.tsym);
428 return sup != null
429 && sup.tsym == s.tsym
430 // You're not allowed to write
431 // Vector<Object> vec = new Vector<String>();
432 // But with wildcards you can write
433 // Vector<? extends Object> vec = new Vector<String>();
434 // which means that subtype checking must be done
435 // here instead of same-type checking (via containsType).
436 && (!s.isParameterized() || containsTypeRecursive(s, sup))
437 && isSubtypeNoCapture(sup.getEnclosingType(),
438 s.getEnclosingType());
439 }
441 @Override
442 public Boolean visitArrayType(ArrayType t, Type s) {
443 if (s.tag == ARRAY) {
444 if (t.elemtype.tag <= lastBaseTag)
445 return isSameType(t.elemtype, elemtype(s));
446 else
447 return isSubtypeNoCapture(t.elemtype, elemtype(s));
448 }
450 if (s.tag == CLASS) {
451 Name sname = s.tsym.getQualifiedName();
452 return sname == names.java_lang_Object
453 || sname == names.java_lang_Cloneable
454 || sname == names.java_io_Serializable;
455 }
457 return false;
458 }
460 @Override
461 public Boolean visitUndetVar(UndetVar t, Type s) {
462 //todo: test against origin needed? or replace with substitution?
463 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
464 return true;
466 if (t.inst != null)
467 return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
469 t.hibounds = t.hibounds.prepend(s);
470 return true;
471 }
473 @Override
474 public Boolean visitErrorType(ErrorType t, Type s) {
475 return true;
476 }
477 };
479 /**
480 * Is t a subtype of every type in given list `ts'?<br>
481 * (not defined for Method and ForAll types)<br>
482 * Allows unchecked conversions.
483 */
484 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
485 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
486 if (!isSubtypeUnchecked(t, l.head, warn))
487 return false;
488 return true;
489 }
491 /**
492 * Are corresponding elements of ts subtypes of ss? If lists are
493 * of different length, return false.
494 */
495 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
496 while (ts.tail != null && ss.tail != null
497 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
498 isSubtype(ts.head, ss.head)) {
499 ts = ts.tail;
500 ss = ss.tail;
501 }
502 return ts.tail == null && ss.tail == null;
503 /*inlined: ts.isEmpty() && ss.isEmpty();*/
504 }
506 /**
507 * Are corresponding elements of ts subtypes of ss, allowing
508 * unchecked conversions? If lists are of different length,
509 * return false.
510 **/
511 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
512 while (ts.tail != null && ss.tail != null
513 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
514 isSubtypeUnchecked(ts.head, ss.head, warn)) {
515 ts = ts.tail;
516 ss = ss.tail;
517 }
518 return ts.tail == null && ss.tail == null;
519 /*inlined: ts.isEmpty() && ss.isEmpty();*/
520 }
521 // </editor-fold>
523 // <editor-fold defaultstate="collapsed" desc="isSuperType">
524 /**
525 * Is t a supertype of s?
526 */
527 public boolean isSuperType(Type t, Type s) {
528 switch (t.tag) {
529 case ERROR:
530 return true;
531 case UNDETVAR: {
532 UndetVar undet = (UndetVar)t;
533 if (t == s ||
534 undet.qtype == s ||
535 s.tag == ERROR ||
536 s.tag == BOT) return true;
537 if (undet.inst != null)
538 return isSubtype(s, undet.inst);
539 undet.lobounds = undet.lobounds.prepend(s);
540 return true;
541 }
542 default:
543 return isSubtype(s, t);
544 }
545 }
546 // </editor-fold>
548 // <editor-fold defaultstate="collapsed" desc="isSameType">
549 /**
550 * Are corresponding elements of the lists the same type? If
551 * lists are of different length, return false.
552 */
553 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
554 while (ts.tail != null && ss.tail != null
555 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
556 isSameType(ts.head, ss.head)) {
557 ts = ts.tail;
558 ss = ss.tail;
559 }
560 return ts.tail == null && ss.tail == null;
561 /*inlined: ts.isEmpty() && ss.isEmpty();*/
562 }
564 /**
565 * Is t the same type as s?
566 */
567 public boolean isSameType(Type t, Type s) {
568 return isSameType.visit(t, s);
569 }
570 // where
571 private TypeRelation isSameType = new TypeRelation() {
573 public Boolean visitType(Type t, Type s) {
574 if (t == s)
575 return true;
577 if (s.tag >= firstPartialTag)
578 return visit(s, t);
580 switch (t.tag) {
581 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
582 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
583 return t.tag == s.tag;
584 case TYPEVAR:
585 return s.isSuperBound()
586 && !s.isExtendsBound()
587 && visit(t, upperBound(s));
588 default:
589 throw new AssertionError("isSameType " + t.tag);
590 }
591 }
593 @Override
594 public Boolean visitWildcardType(WildcardType t, Type s) {
595 if (s.tag >= firstPartialTag)
596 return visit(s, t);
597 else
598 return false;
599 }
601 @Override
602 public Boolean visitClassType(ClassType t, Type s) {
603 if (t == s)
604 return true;
606 if (s.tag >= firstPartialTag)
607 return visit(s, t);
609 if (s.isSuperBound() && !s.isExtendsBound())
610 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
612 if (t.isCompound() && s.isCompound()) {
613 if (!visit(supertype(t), supertype(s)))
614 return false;
616 HashSet<SingletonType> set = new HashSet<SingletonType>();
617 for (Type x : interfaces(t))
618 set.add(new SingletonType(x));
619 for (Type x : interfaces(s)) {
620 if (!set.remove(new SingletonType(x)))
621 return false;
622 }
623 return (set.size() == 0);
624 }
625 return t.tsym == s.tsym
626 && visit(t.getEnclosingType(), s.getEnclosingType())
627 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
628 }
630 @Override
631 public Boolean visitArrayType(ArrayType t, Type s) {
632 if (t == s)
633 return true;
635 if (s.tag >= firstPartialTag)
636 return visit(s, t);
638 return s.tag == ARRAY
639 && containsTypeEquivalent(t.elemtype, elemtype(s));
640 }
642 @Override
643 public Boolean visitMethodType(MethodType t, Type s) {
644 // isSameType for methods does not take thrown
645 // exceptions into account!
646 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
647 }
649 @Override
650 public Boolean visitPackageType(PackageType t, Type s) {
651 return t == s;
652 }
654 @Override
655 public Boolean visitForAll(ForAll t, Type s) {
656 if (s.tag != FORALL)
657 return false;
659 ForAll forAll = (ForAll)s;
660 return hasSameBounds(t, forAll)
661 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
662 }
664 @Override
665 public Boolean visitUndetVar(UndetVar t, Type s) {
666 if (s.tag == WILDCARD)
667 // FIXME, this might be leftovers from before capture conversion
668 return false;
670 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
671 return true;
673 if (t.inst != null)
674 return visit(t.inst, s);
676 t.inst = fromUnknownFun.apply(s);
677 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
678 if (!isSubtype(l.head, t.inst))
679 return false;
680 }
681 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
682 if (!isSubtype(t.inst, l.head))
683 return false;
684 }
685 return true;
686 }
688 @Override
689 public Boolean visitErrorType(ErrorType t, Type s) {
690 return true;
691 }
692 };
693 // </editor-fold>
695 // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
696 /**
697 * A mapping that turns all unknown types in this type to fresh
698 * unknown variables.
699 */
700 public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
701 public Type apply(Type t) {
702 if (t.tag == UNKNOWN) return new UndetVar(t);
703 else return t.map(this);
704 }
705 };
706 // </editor-fold>
708 // <editor-fold defaultstate="collapsed" desc="Contains Type">
709 public boolean containedBy(Type t, Type s) {
710 switch (t.tag) {
711 case UNDETVAR:
712 if (s.tag == WILDCARD) {
713 UndetVar undetvar = (UndetVar)t;
714 WildcardType wt = (WildcardType)s;
715 switch(wt.kind) {
716 case UNBOUND: //similar to ? extends Object
717 case EXTENDS: {
718 Type bound = upperBound(s);
719 // We should check the new upper bound against any of the
720 // undetvar's lower bounds.
721 for (Type t2 : undetvar.lobounds) {
722 if (!isSubtype(t2, bound))
723 return false;
724 }
725 undetvar.hibounds = undetvar.hibounds.prepend(bound);
726 break;
727 }
728 case SUPER: {
729 Type bound = lowerBound(s);
730 // We should check the new lower bound against any of the
731 // undetvar's lower bounds.
732 for (Type t2 : undetvar.hibounds) {
733 if (!isSubtype(bound, t2))
734 return false;
735 }
736 undetvar.lobounds = undetvar.lobounds.prepend(bound);
737 break;
738 }
739 }
740 return true;
741 } else {
742 return isSameType(t, s);
743 }
744 case ERROR:
745 return true;
746 default:
747 return containsType(s, t);
748 }
749 }
751 boolean containsType(List<Type> ts, List<Type> ss) {
752 while (ts.nonEmpty() && ss.nonEmpty()
753 && containsType(ts.head, ss.head)) {
754 ts = ts.tail;
755 ss = ss.tail;
756 }
757 return ts.isEmpty() && ss.isEmpty();
758 }
760 /**
761 * Check if t contains s.
762 *
763 * <p>T contains S if:
764 *
765 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
766 *
767 * <p>This relation is only used by ClassType.isSubtype(), that
768 * is,
769 *
770 * <p>{@code C<S> <: C<T> if T contains S.}
771 *
772 * <p>Because of F-bounds, this relation can lead to infinite
773 * recursion. Thus we must somehow break that recursion. Notice
774 * that containsType() is only called from ClassType.isSubtype().
775 * Since the arguments have already been checked against their
776 * bounds, we know:
777 *
778 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
779 *
780 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
781 *
782 * @param t a type
783 * @param s a type
784 */
785 public boolean containsType(Type t, Type s) {
786 return containsType.visit(t, s);
787 }
788 // where
789 private TypeRelation containsType = new TypeRelation() {
791 private Type U(Type t) {
792 while (t.tag == WILDCARD) {
793 WildcardType w = (WildcardType)t;
794 if (w.isSuperBound())
795 return w.bound == null ? syms.objectType : w.bound.bound;
796 else
797 t = w.type;
798 }
799 return t;
800 }
802 private Type L(Type t) {
803 while (t.tag == WILDCARD) {
804 WildcardType w = (WildcardType)t;
805 if (w.isExtendsBound())
806 return syms.botType;
807 else
808 t = w.type;
809 }
810 return t;
811 }
813 public Boolean visitType(Type t, Type s) {
814 if (s.tag >= firstPartialTag)
815 return containedBy(s, t);
816 else
817 return isSameType(t, s);
818 }
820 void debugContainsType(WildcardType t, Type s) {
821 System.err.println();
822 System.err.format(" does %s contain %s?%n", t, s);
823 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
824 upperBound(s), s, t, U(t),
825 t.isSuperBound()
826 || isSubtypeNoCapture(upperBound(s), U(t)));
827 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
828 L(t), t, s, lowerBound(s),
829 t.isExtendsBound()
830 || isSubtypeNoCapture(L(t), lowerBound(s)));
831 System.err.println();
832 }
834 @Override
835 public Boolean visitWildcardType(WildcardType t, Type s) {
836 if (s.tag >= firstPartialTag)
837 return containedBy(s, t);
838 else {
839 // debugContainsType(t, s);
840 return isSameWildcard(t, s)
841 || isCaptureOf(s, t)
842 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
843 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
844 }
845 }
847 @Override
848 public Boolean visitUndetVar(UndetVar t, Type s) {
849 if (s.tag != WILDCARD)
850 return isSameType(t, s);
851 else
852 return false;
853 }
855 @Override
856 public Boolean visitErrorType(ErrorType t, Type s) {
857 return true;
858 }
859 };
861 public boolean isCaptureOf(Type s, WildcardType t) {
862 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
863 return false;
864 return isSameWildcard(t, ((CapturedType)s).wildcard);
865 }
867 public boolean isSameWildcard(WildcardType t, Type s) {
868 if (s.tag != WILDCARD)
869 return false;
870 WildcardType w = (WildcardType)s;
871 return w.kind == t.kind && w.type == t.type;
872 }
874 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
875 while (ts.nonEmpty() && ss.nonEmpty()
876 && containsTypeEquivalent(ts.head, ss.head)) {
877 ts = ts.tail;
878 ss = ss.tail;
879 }
880 return ts.isEmpty() && ss.isEmpty();
881 }
882 // </editor-fold>
884 // <editor-fold defaultstate="collapsed" desc="isCastable">
885 public boolean isCastable(Type t, Type s) {
886 return isCastable(t, s, Warner.noWarnings);
887 }
889 /**
890 * Is t is castable to s?<br>
891 * s is assumed to be an erased type.<br>
892 * (not defined for Method and ForAll types).
893 */
894 public boolean isCastable(Type t, Type s, Warner warn) {
895 if (t == s)
896 return true;
898 if (t.isPrimitive() != s.isPrimitive())
899 return allowBoxing && isConvertible(t, s, warn);
901 if (warn != warnStack.head) {
902 try {
903 warnStack = warnStack.prepend(warn);
904 return isCastable.visit(t,s);
905 } finally {
906 warnStack = warnStack.tail;
907 }
908 } else {
909 return isCastable.visit(t,s);
910 }
911 }
912 // where
913 private TypeRelation isCastable = new TypeRelation() {
915 public Boolean visitType(Type t, Type s) {
916 if (s.tag == ERROR)
917 return true;
919 switch (t.tag) {
920 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
921 case DOUBLE:
922 return s.tag <= DOUBLE;
923 case BOOLEAN:
924 return s.tag == BOOLEAN;
925 case VOID:
926 return false;
927 case BOT:
928 return isSubtype(t, s);
929 default:
930 throw new AssertionError();
931 }
932 }
934 @Override
935 public Boolean visitWildcardType(WildcardType t, Type s) {
936 return isCastable(upperBound(t), s, warnStack.head);
937 }
939 @Override
940 public Boolean visitClassType(ClassType t, Type s) {
941 if (s.tag == ERROR || s.tag == BOT)
942 return true;
944 if (s.tag == TYPEVAR) {
945 if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
946 warnStack.head.warnUnchecked();
947 return true;
948 } else {
949 return false;
950 }
951 }
953 if (t.isCompound()) {
954 Warner oldWarner = warnStack.head;
955 warnStack.head = Warner.noWarnings;
956 if (!visit(supertype(t), s))
957 return false;
958 for (Type intf : interfaces(t)) {
959 if (!visit(intf, s))
960 return false;
961 }
962 if (warnStack.head.unchecked == true)
963 oldWarner.warnUnchecked();
964 return true;
965 }
967 if (s.isCompound()) {
968 // call recursively to reuse the above code
969 return visitClassType((ClassType)s, t);
970 }
972 if (s.tag == CLASS || s.tag == ARRAY) {
973 boolean upcast;
974 if ((upcast = isSubtype(erasure(t), erasure(s)))
975 || isSubtype(erasure(s), erasure(t))) {
976 if (!upcast && s.tag == ARRAY) {
977 if (!isReifiable(s))
978 warnStack.head.warnUnchecked();
979 return true;
980 } else if (s.isRaw()) {
981 return true;
982 } else if (t.isRaw()) {
983 if (!isUnbounded(s))
984 warnStack.head.warnUnchecked();
985 return true;
986 }
987 // Assume |a| <: |b|
988 final Type a = upcast ? t : s;
989 final Type b = upcast ? s : t;
990 final boolean HIGH = true;
991 final boolean LOW = false;
992 final boolean DONT_REWRITE_TYPEVARS = false;
993 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
994 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
995 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
996 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
997 Type lowSub = asSub(bLow, aLow.tsym);
998 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
999 if (highSub == null) {
1000 final boolean REWRITE_TYPEVARS = true;
1001 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1002 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1003 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1004 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1005 lowSub = asSub(bLow, aLow.tsym);
1006 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1007 }
1008 if (highSub != null) {
1009 assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
1010 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
1011 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1012 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1013 && !disjointTypes(aLow.allparams(), highSub.allparams())
1014 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1015 if (upcast ? giveWarning(a, b) :
1016 giveWarning(b, a))
1017 warnStack.head.warnUnchecked();
1018 return true;
1019 }
1020 }
1021 if (isReifiable(s))
1022 return isSubtypeUnchecked(a, b);
1023 else
1024 return isSubtypeUnchecked(a, b, warnStack.head);
1025 }
1027 // Sidecast
1028 if (s.tag == CLASS) {
1029 if ((s.tsym.flags() & INTERFACE) != 0) {
1030 return ((t.tsym.flags() & FINAL) == 0)
1031 ? sideCast(t, s, warnStack.head)
1032 : sideCastFinal(t, s, warnStack.head);
1033 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1034 return ((s.tsym.flags() & FINAL) == 0)
1035 ? sideCast(t, s, warnStack.head)
1036 : sideCastFinal(t, s, warnStack.head);
1037 } else {
1038 // unrelated class types
1039 return false;
1040 }
1041 }
1042 }
1043 return false;
1044 }
1046 @Override
1047 public Boolean visitArrayType(ArrayType t, Type s) {
1048 switch (s.tag) {
1049 case ERROR:
1050 case BOT:
1051 return true;
1052 case TYPEVAR:
1053 if (isCastable(s, t, Warner.noWarnings)) {
1054 warnStack.head.warnUnchecked();
1055 return true;
1056 } else {
1057 return false;
1058 }
1059 case CLASS:
1060 return isSubtype(t, s);
1061 case ARRAY:
1062 if (elemtype(t).tag <= lastBaseTag) {
1063 return elemtype(t).tag == elemtype(s).tag;
1064 } else {
1065 return visit(elemtype(t), elemtype(s));
1066 }
1067 default:
1068 return false;
1069 }
1070 }
1072 @Override
1073 public Boolean visitTypeVar(TypeVar t, Type s) {
1074 switch (s.tag) {
1075 case ERROR:
1076 case BOT:
1077 return true;
1078 case TYPEVAR:
1079 if (isSubtype(t, s)) {
1080 return true;
1081 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1082 warnStack.head.warnUnchecked();
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 default:
1088 return isCastable(t.bound, s, warnStack.head);
1089 }
1090 }
1092 @Override
1093 public Boolean visitErrorType(ErrorType t, Type s) {
1094 return true;
1095 }
1096 };
1097 // </editor-fold>
1099 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1100 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1101 while (ts.tail != null && ss.tail != null) {
1102 if (disjointType(ts.head, ss.head)) return true;
1103 ts = ts.tail;
1104 ss = ss.tail;
1105 }
1106 return false;
1107 }
1109 /**
1110 * Two types or wildcards are considered disjoint if it can be
1111 * proven that no type can be contained in both. It is
1112 * conservative in that it is allowed to say that two types are
1113 * not disjoint, even though they actually are.
1114 *
1115 * The type C<X> is castable to C<Y> exactly if X and Y are not
1116 * disjoint.
1117 */
1118 public boolean disjointType(Type t, Type s) {
1119 return disjointType.visit(t, s);
1120 }
1121 // where
1122 private TypeRelation disjointType = new TypeRelation() {
1124 private Set<TypePair> cache = new HashSet<TypePair>();
1126 public Boolean visitType(Type t, Type s) {
1127 if (s.tag == WILDCARD)
1128 return visit(s, t);
1129 else
1130 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1131 }
1133 private boolean isCastableRecursive(Type t, Type s) {
1134 TypePair pair = new TypePair(t, s);
1135 if (cache.add(pair)) {
1136 try {
1137 return Types.this.isCastable(t, s);
1138 } finally {
1139 cache.remove(pair);
1140 }
1141 } else {
1142 return true;
1143 }
1144 }
1146 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1147 TypePair pair = new TypePair(t, s);
1148 if (cache.add(pair)) {
1149 try {
1150 return Types.this.notSoftSubtype(t, s);
1151 } finally {
1152 cache.remove(pair);
1153 }
1154 } else {
1155 return false;
1156 }
1157 }
1159 @Override
1160 public Boolean visitWildcardType(WildcardType t, Type s) {
1161 if (t.isUnbound())
1162 return false;
1164 if (s.tag != WILDCARD) {
1165 if (t.isExtendsBound())
1166 return notSoftSubtypeRecursive(s, t.type);
1167 else // isSuperBound()
1168 return notSoftSubtypeRecursive(t.type, s);
1169 }
1171 if (s.isUnbound())
1172 return false;
1174 if (t.isExtendsBound()) {
1175 if (s.isExtendsBound())
1176 return !isCastableRecursive(t.type, upperBound(s));
1177 else if (s.isSuperBound())
1178 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1179 } else if (t.isSuperBound()) {
1180 if (s.isExtendsBound())
1181 return notSoftSubtypeRecursive(t.type, upperBound(s));
1182 }
1183 return false;
1184 }
1185 };
1186 // </editor-fold>
1188 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1189 /**
1190 * Returns the lower bounds of the formals of a method.
1191 */
1192 public List<Type> lowerBoundArgtypes(Type t) {
1193 return map(t.getParameterTypes(), lowerBoundMapping);
1194 }
1195 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1196 public Type apply(Type t) {
1197 return lowerBound(t);
1198 }
1199 };
1200 // </editor-fold>
1202 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1203 /**
1204 * This relation answers the question: is impossible that
1205 * something of type `t' can be a subtype of `s'? This is
1206 * different from the question "is `t' not a subtype of `s'?"
1207 * when type variables are involved: Integer is not a subtype of T
1208 * where <T extends Number> but it is not true that Integer cannot
1209 * possibly be a subtype of T.
1210 */
1211 public boolean notSoftSubtype(Type t, Type s) {
1212 if (t == s) return false;
1213 if (t.tag == TYPEVAR) {
1214 TypeVar tv = (TypeVar) t;
1215 if (s.tag == TYPEVAR)
1216 s = s.getUpperBound();
1217 return !isCastable(tv.bound,
1218 s,
1219 Warner.noWarnings);
1220 }
1221 if (s.tag != WILDCARD)
1222 s = upperBound(s);
1223 if (s.tag == TYPEVAR)
1224 s = s.getUpperBound();
1226 return !isSubtype(t, s);
1227 }
1228 // </editor-fold>
1230 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1231 public boolean isReifiable(Type t) {
1232 return isReifiable.visit(t);
1233 }
1234 // where
1235 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1237 public Boolean visitType(Type t, Void ignored) {
1238 return true;
1239 }
1241 @Override
1242 public Boolean visitClassType(ClassType t, Void ignored) {
1243 if (!t.isParameterized())
1244 return true;
1246 for (Type param : t.allparams()) {
1247 if (!param.isUnbound())
1248 return false;
1249 }
1250 return true;
1251 }
1253 @Override
1254 public Boolean visitArrayType(ArrayType t, Void ignored) {
1255 return visit(t.elemtype);
1256 }
1258 @Override
1259 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1260 return false;
1261 }
1262 };
1263 // </editor-fold>
1265 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1266 public boolean isArray(Type t) {
1267 while (t.tag == WILDCARD)
1268 t = upperBound(t);
1269 return t.tag == ARRAY;
1270 }
1272 /**
1273 * The element type of an array.
1274 */
1275 public Type elemtype(Type t) {
1276 switch (t.tag) {
1277 case WILDCARD:
1278 return elemtype(upperBound(t));
1279 case ARRAY:
1280 return ((ArrayType)t).elemtype;
1281 case FORALL:
1282 return elemtype(((ForAll)t).qtype);
1283 case ERROR:
1284 return t;
1285 default:
1286 return null;
1287 }
1288 }
1290 /**
1291 * Mapping to take element type of an arraytype
1292 */
1293 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1294 public Type apply(Type t) { return elemtype(t); }
1295 };
1297 /**
1298 * The number of dimensions of an array type.
1299 */
1300 public int dimensions(Type t) {
1301 int result = 0;
1302 while (t.tag == ARRAY) {
1303 result++;
1304 t = elemtype(t);
1305 }
1306 return result;
1307 }
1308 // </editor-fold>
1310 // <editor-fold defaultstate="collapsed" desc="asSuper">
1311 /**
1312 * Return the (most specific) base type of t that starts with the
1313 * given symbol. If none exists, return null.
1314 *
1315 * @param t a type
1316 * @param sym a symbol
1317 */
1318 public Type asSuper(Type t, Symbol sym) {
1319 return asSuper.visit(t, sym);
1320 }
1321 // where
1322 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1324 public Type visitType(Type t, Symbol sym) {
1325 return null;
1326 }
1328 @Override
1329 public Type visitClassType(ClassType t, Symbol sym) {
1330 if (t.tsym == sym)
1331 return t;
1333 Type st = supertype(t);
1334 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1335 Type x = asSuper(st, sym);
1336 if (x != null)
1337 return x;
1338 }
1339 if ((sym.flags() & INTERFACE) != 0) {
1340 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1341 Type x = asSuper(l.head, sym);
1342 if (x != null)
1343 return x;
1344 }
1345 }
1346 return null;
1347 }
1349 @Override
1350 public Type visitArrayType(ArrayType t, Symbol sym) {
1351 return isSubtype(t, sym.type) ? sym.type : null;
1352 }
1354 @Override
1355 public Type visitTypeVar(TypeVar t, Symbol sym) {
1356 if (t.tsym == sym)
1357 return t;
1358 else
1359 return asSuper(t.bound, sym);
1360 }
1362 @Override
1363 public Type visitErrorType(ErrorType t, Symbol sym) {
1364 return t;
1365 }
1366 };
1368 /**
1369 * Return the base type of t or any of its outer types that starts
1370 * with the given symbol. If none exists, return null.
1371 *
1372 * @param t a type
1373 * @param sym a symbol
1374 */
1375 public Type asOuterSuper(Type t, Symbol sym) {
1376 switch (t.tag) {
1377 case CLASS:
1378 do {
1379 Type s = asSuper(t, sym);
1380 if (s != null) return s;
1381 t = t.getEnclosingType();
1382 } while (t.tag == CLASS);
1383 return null;
1384 case ARRAY:
1385 return isSubtype(t, sym.type) ? sym.type : null;
1386 case TYPEVAR:
1387 return asSuper(t, sym);
1388 case ERROR:
1389 return t;
1390 default:
1391 return null;
1392 }
1393 }
1395 /**
1396 * Return the base type of t or any of its enclosing types that
1397 * starts with the given symbol. If none exists, return null.
1398 *
1399 * @param t a type
1400 * @param sym a symbol
1401 */
1402 public Type asEnclosingSuper(Type t, Symbol sym) {
1403 switch (t.tag) {
1404 case CLASS:
1405 do {
1406 Type s = asSuper(t, sym);
1407 if (s != null) return s;
1408 Type outer = t.getEnclosingType();
1409 t = (outer.tag == CLASS) ? outer :
1410 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1411 Type.noType;
1412 } while (t.tag == CLASS);
1413 return null;
1414 case ARRAY:
1415 return isSubtype(t, sym.type) ? sym.type : null;
1416 case TYPEVAR:
1417 return asSuper(t, sym);
1418 case ERROR:
1419 return t;
1420 default:
1421 return null;
1422 }
1423 }
1424 // </editor-fold>
1426 // <editor-fold defaultstate="collapsed" desc="memberType">
1427 /**
1428 * The type of given symbol, seen as a member of t.
1429 *
1430 * @param t a type
1431 * @param sym a symbol
1432 */
1433 public Type memberType(Type t, Symbol sym) {
1434 return (sym.flags() & STATIC) != 0
1435 ? sym.type
1436 : memberType.visit(t, sym);
1437 }
1438 // where
1439 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1441 public Type visitType(Type t, Symbol sym) {
1442 return sym.type;
1443 }
1445 @Override
1446 public Type visitWildcardType(WildcardType t, Symbol sym) {
1447 return memberType(upperBound(t), sym);
1448 }
1450 @Override
1451 public Type visitClassType(ClassType t, Symbol sym) {
1452 Symbol owner = sym.owner;
1453 long flags = sym.flags();
1454 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1455 Type base = asOuterSuper(t, owner);
1456 //if t is an intersection type T = CT & I1 & I2 ... & In
1457 //its supertypes CT, I1, ... In might contain wildcards
1458 //so we need to go through capture conversion
1459 base = t.isCompound() ? capture(base) : base;
1460 if (base != null) {
1461 List<Type> ownerParams = owner.type.allparams();
1462 List<Type> baseParams = base.allparams();
1463 if (ownerParams.nonEmpty()) {
1464 if (baseParams.isEmpty()) {
1465 // then base is a raw type
1466 return erasure(sym.type);
1467 } else {
1468 return subst(sym.type, ownerParams, baseParams);
1469 }
1470 }
1471 }
1472 }
1473 return sym.type;
1474 }
1476 @Override
1477 public Type visitTypeVar(TypeVar t, Symbol sym) {
1478 return memberType(t.bound, sym);
1479 }
1481 @Override
1482 public Type visitErrorType(ErrorType t, Symbol sym) {
1483 return t;
1484 }
1485 };
1486 // </editor-fold>
1488 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1489 public boolean isAssignable(Type t, Type s) {
1490 return isAssignable(t, s, Warner.noWarnings);
1491 }
1493 /**
1494 * Is t assignable to s?<br>
1495 * Equivalent to subtype except for constant values and raw
1496 * types.<br>
1497 * (not defined for Method and ForAll types)
1498 */
1499 public boolean isAssignable(Type t, Type s, Warner warn) {
1500 if (t.tag == ERROR)
1501 return true;
1502 if (t.tag <= INT && t.constValue() != null) {
1503 int value = ((Number)t.constValue()).intValue();
1504 switch (s.tag) {
1505 case BYTE:
1506 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1507 return true;
1508 break;
1509 case CHAR:
1510 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1511 return true;
1512 break;
1513 case SHORT:
1514 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1515 return true;
1516 break;
1517 case INT:
1518 return true;
1519 case CLASS:
1520 switch (unboxedType(s).tag) {
1521 case BYTE:
1522 case CHAR:
1523 case SHORT:
1524 return isAssignable(t, unboxedType(s), warn);
1525 }
1526 break;
1527 }
1528 }
1529 return isConvertible(t, s, warn);
1530 }
1531 // </editor-fold>
1533 // <editor-fold defaultstate="collapsed" desc="erasure">
1534 /**
1535 * The erasure of t {@code |t|} -- the type that results when all
1536 * type parameters in t are deleted.
1537 */
1538 public Type erasure(Type t) {
1539 return erasure(t, false);
1540 }
1541 //where
1542 private Type erasure(Type t, boolean recurse) {
1543 if (t.tag <= lastBaseTag)
1544 return t; /* fast special case */
1545 else
1546 return erasure.visit(t, recurse);
1547 }
1548 // where
1549 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1550 public Type visitType(Type t, Boolean recurse) {
1551 if (t.tag <= lastBaseTag)
1552 return t; /*fast special case*/
1553 else
1554 return t.map(recurse ? erasureRecFun : erasureFun);
1555 }
1557 @Override
1558 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1559 return erasure(upperBound(t), recurse);
1560 }
1562 @Override
1563 public Type visitClassType(ClassType t, Boolean recurse) {
1564 Type erased = t.tsym.erasure(Types.this);
1565 if (recurse) {
1566 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1567 }
1568 return erased;
1569 }
1571 @Override
1572 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1573 return erasure(t.bound, recurse);
1574 }
1576 @Override
1577 public Type visitErrorType(ErrorType t, Boolean recurse) {
1578 return t;
1579 }
1580 };
1582 private Mapping erasureFun = new Mapping ("erasure") {
1583 public Type apply(Type t) { return erasure(t); }
1584 };
1586 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1587 public Type apply(Type t) { return erasureRecursive(t); }
1588 };
1590 public List<Type> erasure(List<Type> ts) {
1591 return Type.map(ts, erasureFun);
1592 }
1594 public Type erasureRecursive(Type t) {
1595 return erasure(t, true);
1596 }
1598 public List<Type> erasureRecursive(List<Type> ts) {
1599 return Type.map(ts, erasureRecFun);
1600 }
1601 // </editor-fold>
1603 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1604 /**
1605 * Make a compound type from non-empty list of types
1606 *
1607 * @param bounds the types from which the compound type is formed
1608 * @param supertype is objectType if all bounds are interfaces,
1609 * null otherwise.
1610 */
1611 public Type makeCompoundType(List<Type> bounds,
1612 Type supertype) {
1613 ClassSymbol bc =
1614 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1615 Type.moreInfo
1616 ? names.fromString(bounds.toString())
1617 : names.empty,
1618 syms.noSymbol);
1619 if (bounds.head.tag == TYPEVAR)
1620 // error condition, recover
1621 bc.erasure_field = syms.objectType;
1622 else
1623 bc.erasure_field = erasure(bounds.head);
1624 bc.members_field = new Scope(bc);
1625 ClassType bt = (ClassType)bc.type;
1626 bt.allparams_field = List.nil();
1627 if (supertype != null) {
1628 bt.supertype_field = supertype;
1629 bt.interfaces_field = bounds;
1630 } else {
1631 bt.supertype_field = bounds.head;
1632 bt.interfaces_field = bounds.tail;
1633 }
1634 assert bt.supertype_field.tsym.completer != null
1635 || !bt.supertype_field.isInterface()
1636 : bt.supertype_field;
1637 return bt;
1638 }
1640 /**
1641 * Same as {@link #makeCompoundType(List,Type)}, except that the
1642 * second parameter is computed directly. Note that this might
1643 * cause a symbol completion. Hence, this version of
1644 * makeCompoundType may not be called during a classfile read.
1645 */
1646 public Type makeCompoundType(List<Type> bounds) {
1647 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1648 supertype(bounds.head) : null;
1649 return makeCompoundType(bounds, supertype);
1650 }
1652 /**
1653 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1654 * arguments are converted to a list and passed to the other
1655 * method. Note that this might cause a symbol completion.
1656 * Hence, this version of makeCompoundType may not be called
1657 * during a classfile read.
1658 */
1659 public Type makeCompoundType(Type bound1, Type bound2) {
1660 return makeCompoundType(List.of(bound1, bound2));
1661 }
1662 // </editor-fold>
1664 // <editor-fold defaultstate="collapsed" desc="supertype">
1665 public Type supertype(Type t) {
1666 return supertype.visit(t);
1667 }
1668 // where
1669 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1671 public Type visitType(Type t, Void ignored) {
1672 // A note on wildcards: there is no good way to
1673 // determine a supertype for a super bounded wildcard.
1674 return null;
1675 }
1677 @Override
1678 public Type visitClassType(ClassType t, Void ignored) {
1679 if (t.supertype_field == null) {
1680 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1681 // An interface has no superclass; its supertype is Object.
1682 if (t.isInterface())
1683 supertype = ((ClassType)t.tsym.type).supertype_field;
1684 if (t.supertype_field == null) {
1685 List<Type> actuals = classBound(t).allparams();
1686 List<Type> formals = t.tsym.type.allparams();
1687 if (t.hasErasedSupertypes()) {
1688 t.supertype_field = erasureRecursive(supertype);
1689 } else if (formals.nonEmpty()) {
1690 t.supertype_field = subst(supertype, formals, actuals);
1691 }
1692 else {
1693 t.supertype_field = supertype;
1694 }
1695 }
1696 }
1697 return t.supertype_field;
1698 }
1700 /**
1701 * The supertype is always a class type. If the type
1702 * variable's bounds start with a class type, this is also
1703 * the supertype. Otherwise, the supertype is
1704 * java.lang.Object.
1705 */
1706 @Override
1707 public Type visitTypeVar(TypeVar t, Void ignored) {
1708 if (t.bound.tag == TYPEVAR ||
1709 (!t.bound.isCompound() && !t.bound.isInterface())) {
1710 return t.bound;
1711 } else {
1712 return supertype(t.bound);
1713 }
1714 }
1716 @Override
1717 public Type visitArrayType(ArrayType t, Void ignored) {
1718 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1719 return arraySuperType();
1720 else
1721 return new ArrayType(supertype(t.elemtype), t.tsym);
1722 }
1724 @Override
1725 public Type visitErrorType(ErrorType t, Void ignored) {
1726 return t;
1727 }
1728 };
1729 // </editor-fold>
1731 // <editor-fold defaultstate="collapsed" desc="interfaces">
1732 /**
1733 * Return the interfaces implemented by this class.
1734 */
1735 public List<Type> interfaces(Type t) {
1736 return interfaces.visit(t);
1737 }
1738 // where
1739 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1741 public List<Type> visitType(Type t, Void ignored) {
1742 return List.nil();
1743 }
1745 @Override
1746 public List<Type> visitClassType(ClassType t, Void ignored) {
1747 if (t.interfaces_field == null) {
1748 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1749 if (t.interfaces_field == null) {
1750 // If t.interfaces_field is null, then t must
1751 // be a parameterized type (not to be confused
1752 // with a generic type declaration).
1753 // Terminology:
1754 // Parameterized type: List<String>
1755 // Generic type declaration: class List<E> { ... }
1756 // So t corresponds to List<String> and
1757 // t.tsym.type corresponds to List<E>.
1758 // The reason t must be parameterized type is
1759 // that completion will happen as a side
1760 // effect of calling
1761 // ClassSymbol.getInterfaces. Since
1762 // t.interfaces_field is null after
1763 // completion, we can assume that t is not the
1764 // type of a class/interface declaration.
1765 assert t != t.tsym.type : t.toString();
1766 List<Type> actuals = t.allparams();
1767 List<Type> formals = t.tsym.type.allparams();
1768 if (t.hasErasedSupertypes()) {
1769 t.interfaces_field = erasureRecursive(interfaces);
1770 } else if (formals.nonEmpty()) {
1771 t.interfaces_field =
1772 upperBounds(subst(interfaces, formals, actuals));
1773 }
1774 else {
1775 t.interfaces_field = interfaces;
1776 }
1777 }
1778 }
1779 return t.interfaces_field;
1780 }
1782 @Override
1783 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1784 if (t.bound.isCompound())
1785 return interfaces(t.bound);
1787 if (t.bound.isInterface())
1788 return List.of(t.bound);
1790 return List.nil();
1791 }
1792 };
1793 // </editor-fold>
1795 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1796 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1798 public boolean isDerivedRaw(Type t) {
1799 Boolean result = isDerivedRawCache.get(t);
1800 if (result == null) {
1801 result = isDerivedRawInternal(t);
1802 isDerivedRawCache.put(t, result);
1803 }
1804 return result;
1805 }
1807 public boolean isDerivedRawInternal(Type t) {
1808 if (t.isErroneous())
1809 return false;
1810 return
1811 t.isRaw() ||
1812 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1813 isDerivedRaw(interfaces(t));
1814 }
1816 public boolean isDerivedRaw(List<Type> ts) {
1817 List<Type> l = ts;
1818 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1819 return l.nonEmpty();
1820 }
1821 // </editor-fold>
1823 // <editor-fold defaultstate="collapsed" desc="setBounds">
1824 /**
1825 * Set the bounds field of the given type variable to reflect a
1826 * (possibly multiple) list of bounds.
1827 * @param t a type variable
1828 * @param bounds the bounds, must be nonempty
1829 * @param supertype is objectType if all bounds are interfaces,
1830 * null otherwise.
1831 */
1832 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1833 if (bounds.tail.isEmpty())
1834 t.bound = bounds.head;
1835 else
1836 t.bound = makeCompoundType(bounds, supertype);
1837 t.rank_field = -1;
1838 }
1840 /**
1841 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1842 * third parameter is computed directly. Note that this test
1843 * might cause a symbol completion. Hence, this version of
1844 * setBounds may not be called during a classfile read.
1845 */
1846 public void setBounds(TypeVar t, List<Type> bounds) {
1847 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1848 supertype(bounds.head) : null;
1849 setBounds(t, bounds, supertype);
1850 t.rank_field = -1;
1851 }
1852 // </editor-fold>
1854 // <editor-fold defaultstate="collapsed" desc="getBounds">
1855 /**
1856 * Return list of bounds of the given type variable.
1857 */
1858 public List<Type> getBounds(TypeVar t) {
1859 if (t.bound.isErroneous() || !t.bound.isCompound())
1860 return List.of(t.bound);
1861 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1862 return interfaces(t).prepend(supertype(t));
1863 else
1864 // No superclass was given in bounds.
1865 // In this case, supertype is Object, erasure is first interface.
1866 return interfaces(t);
1867 }
1868 // </editor-fold>
1870 // <editor-fold defaultstate="collapsed" desc="classBound">
1871 /**
1872 * If the given type is a (possibly selected) type variable,
1873 * return the bounding class of this type, otherwise return the
1874 * type itself.
1875 */
1876 public Type classBound(Type t) {
1877 return classBound.visit(t);
1878 }
1879 // where
1880 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1882 public Type visitType(Type t, Void ignored) {
1883 return t;
1884 }
1886 @Override
1887 public Type visitClassType(ClassType t, Void ignored) {
1888 Type outer1 = classBound(t.getEnclosingType());
1889 if (outer1 != t.getEnclosingType())
1890 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1891 else
1892 return t;
1893 }
1895 @Override
1896 public Type visitTypeVar(TypeVar t, Void ignored) {
1897 return classBound(supertype(t));
1898 }
1900 @Override
1901 public Type visitErrorType(ErrorType t, Void ignored) {
1902 return t;
1903 }
1904 };
1905 // </editor-fold>
1907 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1908 /**
1909 * Returns true iff the first signature is a <em>sub
1910 * signature</em> of the other. This is <b>not</b> an equivalence
1911 * relation.
1912 *
1913 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1914 * @see #overrideEquivalent(Type t, Type s)
1915 * @param t first signature (possibly raw).
1916 * @param s second signature (could be subjected to erasure).
1917 * @return true if t is a sub signature of s.
1918 */
1919 public boolean isSubSignature(Type t, Type s) {
1920 return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
1921 }
1923 /**
1924 * Returns true iff these signatures are related by <em>override
1925 * equivalence</em>. This is the natural extension of
1926 * isSubSignature to an equivalence relation.
1927 *
1928 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1929 * @see #isSubSignature(Type t, Type s)
1930 * @param t a signature (possible raw, could be subjected to
1931 * erasure).
1932 * @param s a signature (possible raw, could be subjected to
1933 * erasure).
1934 * @return true if either argument is a sub signature of the other.
1935 */
1936 public boolean overrideEquivalent(Type t, Type s) {
1937 return hasSameArgs(t, s) ||
1938 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
1939 }
1941 /**
1942 * Does t have the same arguments as s? It is assumed that both
1943 * types are (possibly polymorphic) method types. Monomorphic
1944 * method types "have the same arguments", if their argument lists
1945 * are equal. Polymorphic method types "have the same arguments",
1946 * if they have the same arguments after renaming all type
1947 * variables of one to corresponding type variables in the other,
1948 * where correspondence is by position in the type parameter list.
1949 */
1950 public boolean hasSameArgs(Type t, Type s) {
1951 return hasSameArgs.visit(t, s);
1952 }
1953 // where
1954 private TypeRelation hasSameArgs = new TypeRelation() {
1956 public Boolean visitType(Type t, Type s) {
1957 throw new AssertionError();
1958 }
1960 @Override
1961 public Boolean visitMethodType(MethodType t, Type s) {
1962 return s.tag == METHOD
1963 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
1964 }
1966 @Override
1967 public Boolean visitForAll(ForAll t, Type s) {
1968 if (s.tag != FORALL)
1969 return false;
1971 ForAll forAll = (ForAll)s;
1972 return hasSameBounds(t, forAll)
1973 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1974 }
1976 @Override
1977 public Boolean visitErrorType(ErrorType t, Type s) {
1978 return false;
1979 }
1980 };
1981 // </editor-fold>
1983 // <editor-fold defaultstate="collapsed" desc="subst">
1984 public List<Type> subst(List<Type> ts,
1985 List<Type> from,
1986 List<Type> to) {
1987 return new Subst(from, to).subst(ts);
1988 }
1990 /**
1991 * Substitute all occurrences of a type in `from' with the
1992 * corresponding type in `to' in 't'. Match lists `from' and `to'
1993 * from the right: If lists have different length, discard leading
1994 * elements of the longer list.
1995 */
1996 public Type subst(Type t, List<Type> from, List<Type> to) {
1997 return new Subst(from, to).subst(t);
1998 }
2000 private class Subst extends UnaryVisitor<Type> {
2001 List<Type> from;
2002 List<Type> to;
2004 public Subst(List<Type> from, List<Type> to) {
2005 int fromLength = from.length();
2006 int toLength = to.length();
2007 while (fromLength > toLength) {
2008 fromLength--;
2009 from = from.tail;
2010 }
2011 while (fromLength < toLength) {
2012 toLength--;
2013 to = to.tail;
2014 }
2015 this.from = from;
2016 this.to = to;
2017 }
2019 Type subst(Type t) {
2020 if (from.tail == null)
2021 return t;
2022 else
2023 return visit(t);
2024 }
2026 List<Type> subst(List<Type> ts) {
2027 if (from.tail == null)
2028 return ts;
2029 boolean wild = false;
2030 if (ts.nonEmpty() && from.nonEmpty()) {
2031 Type head1 = subst(ts.head);
2032 List<Type> tail1 = subst(ts.tail);
2033 if (head1 != ts.head || tail1 != ts.tail)
2034 return tail1.prepend(head1);
2035 }
2036 return ts;
2037 }
2039 public Type visitType(Type t, Void ignored) {
2040 return t;
2041 }
2043 @Override
2044 public Type visitMethodType(MethodType t, Void ignored) {
2045 List<Type> argtypes = subst(t.argtypes);
2046 Type restype = subst(t.restype);
2047 List<Type> thrown = subst(t.thrown);
2048 if (argtypes == t.argtypes &&
2049 restype == t.restype &&
2050 thrown == t.thrown)
2051 return t;
2052 else
2053 return new MethodType(argtypes, restype, thrown, t.tsym);
2054 }
2056 @Override
2057 public Type visitTypeVar(TypeVar t, Void ignored) {
2058 for (List<Type> from = this.from, to = this.to;
2059 from.nonEmpty();
2060 from = from.tail, to = to.tail) {
2061 if (t == from.head) {
2062 return to.head.withTypeVar(t);
2063 }
2064 }
2065 return t;
2066 }
2068 @Override
2069 public Type visitClassType(ClassType t, Void ignored) {
2070 if (!t.isCompound()) {
2071 List<Type> typarams = t.getTypeArguments();
2072 List<Type> typarams1 = subst(typarams);
2073 Type outer = t.getEnclosingType();
2074 Type outer1 = subst(outer);
2075 if (typarams1 == typarams && outer1 == outer)
2076 return t;
2077 else
2078 return new ClassType(outer1, typarams1, t.tsym);
2079 } else {
2080 Type st = subst(supertype(t));
2081 List<Type> is = upperBounds(subst(interfaces(t)));
2082 if (st == supertype(t) && is == interfaces(t))
2083 return t;
2084 else
2085 return makeCompoundType(is.prepend(st));
2086 }
2087 }
2089 @Override
2090 public Type visitWildcardType(WildcardType t, Void ignored) {
2091 Type bound = t.type;
2092 if (t.kind != BoundKind.UNBOUND)
2093 bound = subst(bound);
2094 if (bound == t.type) {
2095 return t;
2096 } else {
2097 if (t.isExtendsBound() && bound.isExtendsBound())
2098 bound = upperBound(bound);
2099 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2100 }
2101 }
2103 @Override
2104 public Type visitArrayType(ArrayType t, Void ignored) {
2105 Type elemtype = subst(t.elemtype);
2106 if (elemtype == t.elemtype)
2107 return t;
2108 else
2109 return new ArrayType(upperBound(elemtype), t.tsym);
2110 }
2112 @Override
2113 public Type visitForAll(ForAll t, Void ignored) {
2114 List<Type> tvars1 = substBounds(t.tvars, from, to);
2115 Type qtype1 = subst(t.qtype);
2116 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2117 return t;
2118 } else if (tvars1 == t.tvars) {
2119 return new ForAll(tvars1, qtype1);
2120 } else {
2121 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2122 }
2123 }
2125 @Override
2126 public Type visitErrorType(ErrorType t, Void ignored) {
2127 return t;
2128 }
2129 }
2131 public List<Type> substBounds(List<Type> tvars,
2132 List<Type> from,
2133 List<Type> to) {
2134 if (tvars.isEmpty())
2135 return tvars;
2136 ListBuffer<Type> newBoundsBuf = lb();
2137 boolean changed = false;
2138 // calculate new bounds
2139 for (Type t : tvars) {
2140 TypeVar tv = (TypeVar) t;
2141 Type bound = subst(tv.bound, from, to);
2142 if (bound != tv.bound)
2143 changed = true;
2144 newBoundsBuf.append(bound);
2145 }
2146 if (!changed)
2147 return tvars;
2148 ListBuffer<Type> newTvars = lb();
2149 // create new type variables without bounds
2150 for (Type t : tvars) {
2151 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2152 }
2153 // the new bounds should use the new type variables in place
2154 // of the old
2155 List<Type> newBounds = newBoundsBuf.toList();
2156 from = tvars;
2157 to = newTvars.toList();
2158 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2159 newBounds.head = subst(newBounds.head, from, to);
2160 }
2161 newBounds = newBoundsBuf.toList();
2162 // set the bounds of new type variables to the new bounds
2163 for (Type t : newTvars.toList()) {
2164 TypeVar tv = (TypeVar) t;
2165 tv.bound = newBounds.head;
2166 newBounds = newBounds.tail;
2167 }
2168 return newTvars.toList();
2169 }
2171 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2172 Type bound1 = subst(t.bound, from, to);
2173 if (bound1 == t.bound)
2174 return t;
2175 else {
2176 // create new type variable without bounds
2177 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2178 // the new bound should use the new type variable in place
2179 // of the old
2180 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2181 return tv;
2182 }
2183 }
2184 // </editor-fold>
2186 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2187 /**
2188 * Does t have the same bounds for quantified variables as s?
2189 */
2190 boolean hasSameBounds(ForAll t, ForAll s) {
2191 List<Type> l1 = t.tvars;
2192 List<Type> l2 = s.tvars;
2193 while (l1.nonEmpty() && l2.nonEmpty() &&
2194 isSameType(l1.head.getUpperBound(),
2195 subst(l2.head.getUpperBound(),
2196 s.tvars,
2197 t.tvars))) {
2198 l1 = l1.tail;
2199 l2 = l2.tail;
2200 }
2201 return l1.isEmpty() && l2.isEmpty();
2202 }
2203 // </editor-fold>
2205 // <editor-fold defaultstate="collapsed" desc="newInstances">
2206 /** Create new vector of type variables from list of variables
2207 * changing all recursive bounds from old to new list.
2208 */
2209 public List<Type> newInstances(List<Type> tvars) {
2210 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2211 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2212 TypeVar tv = (TypeVar) l.head;
2213 tv.bound = subst(tv.bound, tvars, tvars1);
2214 }
2215 return tvars1;
2216 }
2217 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2218 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2219 };
2220 // </editor-fold>
2222 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2223 public Type createErrorType(Type originalType) {
2224 return new ErrorType(originalType, syms.errSymbol);
2225 }
2227 public Type createErrorType(ClassSymbol c, Type originalType) {
2228 return new ErrorType(c, originalType);
2229 }
2231 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2232 return new ErrorType(name, container, originalType);
2233 }
2234 // </editor-fold>
2236 // <editor-fold defaultstate="collapsed" desc="rank">
2237 /**
2238 * The rank of a class is the length of the longest path between
2239 * the class and java.lang.Object in the class inheritance
2240 * graph. Undefined for all but reference types.
2241 */
2242 public int rank(Type t) {
2243 switch(t.tag) {
2244 case CLASS: {
2245 ClassType cls = (ClassType)t;
2246 if (cls.rank_field < 0) {
2247 Name fullname = cls.tsym.getQualifiedName();
2248 if (fullname == names.java_lang_Object)
2249 cls.rank_field = 0;
2250 else {
2251 int r = rank(supertype(cls));
2252 for (List<Type> l = interfaces(cls);
2253 l.nonEmpty();
2254 l = l.tail) {
2255 if (rank(l.head) > r)
2256 r = rank(l.head);
2257 }
2258 cls.rank_field = r + 1;
2259 }
2260 }
2261 return cls.rank_field;
2262 }
2263 case TYPEVAR: {
2264 TypeVar tvar = (TypeVar)t;
2265 if (tvar.rank_field < 0) {
2266 int r = rank(supertype(tvar));
2267 for (List<Type> l = interfaces(tvar);
2268 l.nonEmpty();
2269 l = l.tail) {
2270 if (rank(l.head) > r) r = rank(l.head);
2271 }
2272 tvar.rank_field = r + 1;
2273 }
2274 return tvar.rank_field;
2275 }
2276 case ERROR:
2277 return 0;
2278 default:
2279 throw new AssertionError();
2280 }
2281 }
2282 // </editor-fold>
2284 /**
2285 * Helper method for generating a string representation of a given type
2286 * accordingly to a given locale
2287 */
2288 public String toString(Type t, Locale locale) {
2289 return Printer.createStandardPrinter(messages).visit(t, locale);
2290 }
2292 /**
2293 * Helper method for generating a string representation of a given type
2294 * accordingly to a given locale
2295 */
2296 public String toString(Symbol t, Locale locale) {
2297 return Printer.createStandardPrinter(messages).visit(t, locale);
2298 }
2300 // <editor-fold defaultstate="collapsed" desc="toString">
2301 /**
2302 * This toString is slightly more descriptive than the one on Type.
2303 *
2304 * @deprecated Types.toString(Type t, Locale l) provides better support
2305 * for localization
2306 */
2307 @Deprecated
2308 public String toString(Type t) {
2309 if (t.tag == FORALL) {
2310 ForAll forAll = (ForAll)t;
2311 return typaramsString(forAll.tvars) + forAll.qtype;
2312 }
2313 return "" + t;
2314 }
2315 // where
2316 private String typaramsString(List<Type> tvars) {
2317 StringBuffer s = new StringBuffer();
2318 s.append('<');
2319 boolean first = true;
2320 for (Type t : tvars) {
2321 if (!first) s.append(", ");
2322 first = false;
2323 appendTyparamString(((TypeVar)t), s);
2324 }
2325 s.append('>');
2326 return s.toString();
2327 }
2328 private void appendTyparamString(TypeVar t, StringBuffer buf) {
2329 buf.append(t);
2330 if (t.bound == null ||
2331 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2332 return;
2333 buf.append(" extends "); // Java syntax; no need for i18n
2334 Type bound = t.bound;
2335 if (!bound.isCompound()) {
2336 buf.append(bound);
2337 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2338 buf.append(supertype(t));
2339 for (Type intf : interfaces(t)) {
2340 buf.append('&');
2341 buf.append(intf);
2342 }
2343 } else {
2344 // No superclass was given in bounds.
2345 // In this case, supertype is Object, erasure is first interface.
2346 boolean first = true;
2347 for (Type intf : interfaces(t)) {
2348 if (!first) buf.append('&');
2349 first = false;
2350 buf.append(intf);
2351 }
2352 }
2353 }
2354 // </editor-fold>
2356 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2357 /**
2358 * A cache for closures.
2359 *
2360 * <p>A closure is a list of all the supertypes and interfaces of
2361 * a class or interface type, ordered by ClassSymbol.precedes
2362 * (that is, subclasses come first, arbitrary but fixed
2363 * otherwise).
2364 */
2365 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2367 /**
2368 * Returns the closure of a class or interface type.
2369 */
2370 public List<Type> closure(Type t) {
2371 List<Type> cl = closureCache.get(t);
2372 if (cl == null) {
2373 Type st = supertype(t);
2374 if (!t.isCompound()) {
2375 if (st.tag == CLASS) {
2376 cl = insert(closure(st), t);
2377 } else if (st.tag == TYPEVAR) {
2378 cl = closure(st).prepend(t);
2379 } else {
2380 cl = List.of(t);
2381 }
2382 } else {
2383 cl = closure(supertype(t));
2384 }
2385 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2386 cl = union(cl, closure(l.head));
2387 closureCache.put(t, cl);
2388 }
2389 return cl;
2390 }
2392 /**
2393 * Insert a type in a closure
2394 */
2395 public List<Type> insert(List<Type> cl, Type t) {
2396 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2397 return cl.prepend(t);
2398 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2399 return insert(cl.tail, t).prepend(cl.head);
2400 } else {
2401 return cl;
2402 }
2403 }
2405 /**
2406 * Form the union of two closures
2407 */
2408 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2409 if (cl1.isEmpty()) {
2410 return cl2;
2411 } else if (cl2.isEmpty()) {
2412 return cl1;
2413 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2414 return union(cl1.tail, cl2).prepend(cl1.head);
2415 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2416 return union(cl1, cl2.tail).prepend(cl2.head);
2417 } else {
2418 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2419 }
2420 }
2422 /**
2423 * Intersect two closures
2424 */
2425 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2426 if (cl1 == cl2)
2427 return cl1;
2428 if (cl1.isEmpty() || cl2.isEmpty())
2429 return List.nil();
2430 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2431 return intersect(cl1.tail, cl2);
2432 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2433 return intersect(cl1, cl2.tail);
2434 if (isSameType(cl1.head, cl2.head))
2435 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2436 if (cl1.head.tsym == cl2.head.tsym &&
2437 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2438 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2439 Type merge = merge(cl1.head,cl2.head);
2440 return intersect(cl1.tail, cl2.tail).prepend(merge);
2441 }
2442 if (cl1.head.isRaw() || cl2.head.isRaw())
2443 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2444 }
2445 return intersect(cl1.tail, cl2.tail);
2446 }
2447 // where
2448 class TypePair {
2449 final Type t1;
2450 final Type t2;
2451 TypePair(Type t1, Type t2) {
2452 this.t1 = t1;
2453 this.t2 = t2;
2454 }
2455 @Override
2456 public int hashCode() {
2457 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
2458 }
2459 @Override
2460 public boolean equals(Object obj) {
2461 if (!(obj instanceof TypePair))
2462 return false;
2463 TypePair typePair = (TypePair)obj;
2464 return isSameType(t1, typePair.t1)
2465 && isSameType(t2, typePair.t2);
2466 }
2467 }
2468 Set<TypePair> mergeCache = new HashSet<TypePair>();
2469 private Type merge(Type c1, Type c2) {
2470 ClassType class1 = (ClassType) c1;
2471 List<Type> act1 = class1.getTypeArguments();
2472 ClassType class2 = (ClassType) c2;
2473 List<Type> act2 = class2.getTypeArguments();
2474 ListBuffer<Type> merged = new ListBuffer<Type>();
2475 List<Type> typarams = class1.tsym.type.getTypeArguments();
2477 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2478 if (containsType(act1.head, act2.head)) {
2479 merged.append(act1.head);
2480 } else if (containsType(act2.head, act1.head)) {
2481 merged.append(act2.head);
2482 } else {
2483 TypePair pair = new TypePair(c1, c2);
2484 Type m;
2485 if (mergeCache.add(pair)) {
2486 m = new WildcardType(lub(upperBound(act1.head),
2487 upperBound(act2.head)),
2488 BoundKind.EXTENDS,
2489 syms.boundClass);
2490 mergeCache.remove(pair);
2491 } else {
2492 m = new WildcardType(syms.objectType,
2493 BoundKind.UNBOUND,
2494 syms.boundClass);
2495 }
2496 merged.append(m.withTypeVar(typarams.head));
2497 }
2498 act1 = act1.tail;
2499 act2 = act2.tail;
2500 typarams = typarams.tail;
2501 }
2502 assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2503 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2504 }
2506 /**
2507 * Return the minimum type of a closure, a compound type if no
2508 * unique minimum exists.
2509 */
2510 private Type compoundMin(List<Type> cl) {
2511 if (cl.isEmpty()) return syms.objectType;
2512 List<Type> compound = closureMin(cl);
2513 if (compound.isEmpty())
2514 return null;
2515 else if (compound.tail.isEmpty())
2516 return compound.head;
2517 else
2518 return makeCompoundType(compound);
2519 }
2521 /**
2522 * Return the minimum types of a closure, suitable for computing
2523 * compoundMin or glb.
2524 */
2525 private List<Type> closureMin(List<Type> cl) {
2526 ListBuffer<Type> classes = lb();
2527 ListBuffer<Type> interfaces = lb();
2528 while (!cl.isEmpty()) {
2529 Type current = cl.head;
2530 if (current.isInterface())
2531 interfaces.append(current);
2532 else
2533 classes.append(current);
2534 ListBuffer<Type> candidates = lb();
2535 for (Type t : cl.tail) {
2536 if (!isSubtypeNoCapture(current, t))
2537 candidates.append(t);
2538 }
2539 cl = candidates.toList();
2540 }
2541 return classes.appendList(interfaces).toList();
2542 }
2544 /**
2545 * Return the least upper bound of pair of types. if the lub does
2546 * not exist return null.
2547 */
2548 public Type lub(Type t1, Type t2) {
2549 return lub(List.of(t1, t2));
2550 }
2552 /**
2553 * Return the least upper bound (lub) of set of types. If the lub
2554 * does not exist return the type of null (bottom).
2555 */
2556 public Type lub(List<Type> ts) {
2557 final int ARRAY_BOUND = 1;
2558 final int CLASS_BOUND = 2;
2559 int boundkind = 0;
2560 for (Type t : ts) {
2561 switch (t.tag) {
2562 case CLASS:
2563 boundkind |= CLASS_BOUND;
2564 break;
2565 case ARRAY:
2566 boundkind |= ARRAY_BOUND;
2567 break;
2568 case TYPEVAR:
2569 do {
2570 t = t.getUpperBound();
2571 } while (t.tag == TYPEVAR);
2572 if (t.tag == ARRAY) {
2573 boundkind |= ARRAY_BOUND;
2574 } else {
2575 boundkind |= CLASS_BOUND;
2576 }
2577 break;
2578 default:
2579 if (t.isPrimitive())
2580 return syms.errType;
2581 }
2582 }
2583 switch (boundkind) {
2584 case 0:
2585 return syms.botType;
2587 case ARRAY_BOUND:
2588 // calculate lub(A[], B[])
2589 List<Type> elements = Type.map(ts, elemTypeFun);
2590 for (Type t : elements) {
2591 if (t.isPrimitive()) {
2592 // if a primitive type is found, then return
2593 // arraySuperType unless all the types are the
2594 // same
2595 Type first = ts.head;
2596 for (Type s : ts.tail) {
2597 if (!isSameType(first, s)) {
2598 // lub(int[], B[]) is Cloneable & Serializable
2599 return arraySuperType();
2600 }
2601 }
2602 // all the array types are the same, return one
2603 // lub(int[], int[]) is int[]
2604 return first;
2605 }
2606 }
2607 // lub(A[], B[]) is lub(A, B)[]
2608 return new ArrayType(lub(elements), syms.arrayClass);
2610 case CLASS_BOUND:
2611 // calculate lub(A, B)
2612 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2613 ts = ts.tail;
2614 assert !ts.isEmpty();
2615 List<Type> cl = closure(ts.head);
2616 for (Type t : ts.tail) {
2617 if (t.tag == CLASS || t.tag == TYPEVAR)
2618 cl = intersect(cl, closure(t));
2619 }
2620 return compoundMin(cl);
2622 default:
2623 // calculate lub(A, B[])
2624 List<Type> classes = List.of(arraySuperType());
2625 for (Type t : ts) {
2626 if (t.tag != ARRAY) // Filter out any arrays
2627 classes = classes.prepend(t);
2628 }
2629 // lub(A, B[]) is lub(A, arraySuperType)
2630 return lub(classes);
2631 }
2632 }
2633 // where
2634 private Type arraySuperType = null;
2635 private Type arraySuperType() {
2636 // initialized lazily to avoid problems during compiler startup
2637 if (arraySuperType == null) {
2638 synchronized (this) {
2639 if (arraySuperType == null) {
2640 // JLS 10.8: all arrays implement Cloneable and Serializable.
2641 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2642 syms.cloneableType),
2643 syms.objectType);
2644 }
2645 }
2646 }
2647 return arraySuperType;
2648 }
2649 // </editor-fold>
2651 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2652 public Type glb(List<Type> ts) {
2653 Type t1 = ts.head;
2654 for (Type t2 : ts.tail) {
2655 if (t1.isErroneous())
2656 return t1;
2657 t1 = glb(t1, t2);
2658 }
2659 return t1;
2660 }
2661 //where
2662 public Type glb(Type t, Type s) {
2663 if (s == null)
2664 return t;
2665 else if (isSubtypeNoCapture(t, s))
2666 return t;
2667 else if (isSubtypeNoCapture(s, t))
2668 return s;
2670 List<Type> closure = union(closure(t), closure(s));
2671 List<Type> bounds = closureMin(closure);
2673 if (bounds.isEmpty()) { // length == 0
2674 return syms.objectType;
2675 } else if (bounds.tail.isEmpty()) { // length == 1
2676 return bounds.head;
2677 } else { // length > 1
2678 int classCount = 0;
2679 for (Type bound : bounds)
2680 if (!bound.isInterface())
2681 classCount++;
2682 if (classCount > 1)
2683 return createErrorType(t);
2684 }
2685 return makeCompoundType(bounds);
2686 }
2687 // </editor-fold>
2689 // <editor-fold defaultstate="collapsed" desc="hashCode">
2690 /**
2691 * Compute a hash code on a type.
2692 */
2693 public static int hashCode(Type t) {
2694 return hashCode.visit(t);
2695 }
2696 // where
2697 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
2699 public Integer visitType(Type t, Void ignored) {
2700 return t.tag;
2701 }
2703 @Override
2704 public Integer visitClassType(ClassType t, Void ignored) {
2705 int result = visit(t.getEnclosingType());
2706 result *= 127;
2707 result += t.tsym.flatName().hashCode();
2708 for (Type s : t.getTypeArguments()) {
2709 result *= 127;
2710 result += visit(s);
2711 }
2712 return result;
2713 }
2715 @Override
2716 public Integer visitWildcardType(WildcardType t, Void ignored) {
2717 int result = t.kind.hashCode();
2718 if (t.type != null) {
2719 result *= 127;
2720 result += visit(t.type);
2721 }
2722 return result;
2723 }
2725 @Override
2726 public Integer visitArrayType(ArrayType t, Void ignored) {
2727 return visit(t.elemtype) + 12;
2728 }
2730 @Override
2731 public Integer visitTypeVar(TypeVar t, Void ignored) {
2732 return System.identityHashCode(t.tsym);
2733 }
2735 @Override
2736 public Integer visitUndetVar(UndetVar t, Void ignored) {
2737 return System.identityHashCode(t);
2738 }
2740 @Override
2741 public Integer visitErrorType(ErrorType t, Void ignored) {
2742 return 0;
2743 }
2744 };
2745 // </editor-fold>
2747 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
2748 /**
2749 * Does t have a result that is a subtype of the result type of s,
2750 * suitable for covariant returns? It is assumed that both types
2751 * are (possibly polymorphic) method types. Monomorphic method
2752 * types are handled in the obvious way. Polymorphic method types
2753 * require renaming all type variables of one to corresponding
2754 * type variables in the other, where correspondence is by
2755 * position in the type parameter list. */
2756 public boolean resultSubtype(Type t, Type s, Warner warner) {
2757 List<Type> tvars = t.getTypeArguments();
2758 List<Type> svars = s.getTypeArguments();
2759 Type tres = t.getReturnType();
2760 Type sres = subst(s.getReturnType(), svars, tvars);
2761 return covariantReturnType(tres, sres, warner);
2762 }
2764 /**
2765 * Return-Type-Substitutable.
2766 * @see <a href="http://java.sun.com/docs/books/jls/">The Java
2767 * Language Specification, Third Ed. (8.4.5)</a>
2768 */
2769 public boolean returnTypeSubstitutable(Type r1, Type r2) {
2770 if (hasSameArgs(r1, r2))
2771 return resultSubtype(r1, r2, Warner.noWarnings);
2772 else
2773 return covariantReturnType(r1.getReturnType(),
2774 erasure(r2.getReturnType()),
2775 Warner.noWarnings);
2776 }
2778 public boolean returnTypeSubstitutable(Type r1,
2779 Type r2, Type r2res,
2780 Warner warner) {
2781 if (isSameType(r1.getReturnType(), r2res))
2782 return true;
2783 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
2784 return false;
2786 if (hasSameArgs(r1, r2))
2787 return covariantReturnType(r1.getReturnType(), r2res, warner);
2788 if (!source.allowCovariantReturns())
2789 return false;
2790 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
2791 return true;
2792 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
2793 return false;
2794 warner.warnUnchecked();
2795 return true;
2796 }
2798 /**
2799 * Is t an appropriate return type in an overrider for a
2800 * method that returns s?
2801 */
2802 public boolean covariantReturnType(Type t, Type s, Warner warner) {
2803 return
2804 isSameType(t, s) ||
2805 source.allowCovariantReturns() &&
2806 !t.isPrimitive() &&
2807 !s.isPrimitive() &&
2808 isAssignable(t, s, warner);
2809 }
2810 // </editor-fold>
2812 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
2813 /**
2814 * Return the class that boxes the given primitive.
2815 */
2816 public ClassSymbol boxedClass(Type t) {
2817 return reader.enterClass(syms.boxedName[t.tag]);
2818 }
2820 /**
2821 * Return the primitive type corresponding to a boxed type.
2822 */
2823 public Type unboxedType(Type t) {
2824 if (allowBoxing) {
2825 for (int i=0; i<syms.boxedName.length; i++) {
2826 Name box = syms.boxedName[i];
2827 if (box != null &&
2828 asSuper(t, reader.enterClass(box)) != null)
2829 return syms.typeOfTag[i];
2830 }
2831 }
2832 return Type.noType;
2833 }
2834 // </editor-fold>
2836 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
2837 /*
2838 * JLS 3rd Ed. 5.1.10 Capture Conversion:
2839 *
2840 * Let G name a generic type declaration with n formal type
2841 * parameters A1 ... An with corresponding bounds U1 ... Un. There
2842 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
2843 * where, for 1 <= i <= n:
2844 *
2845 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
2846 * Si is a fresh type variable whose upper bound is
2847 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
2848 * type.
2849 *
2850 * + If Ti is a wildcard type argument of the form ? extends Bi,
2851 * then Si is a fresh type variable whose upper bound is
2852 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
2853 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
2854 * a compile-time error if for any two classes (not interfaces)
2855 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
2856 *
2857 * + If Ti is a wildcard type argument of the form ? super Bi,
2858 * then Si is a fresh type variable whose upper bound is
2859 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
2860 *
2861 * + Otherwise, Si = Ti.
2862 *
2863 * Capture conversion on any type other than a parameterized type
2864 * (4.5) acts as an identity conversion (5.1.1). Capture
2865 * conversions never require a special action at run time and
2866 * therefore never throw an exception at run time.
2867 *
2868 * Capture conversion is not applied recursively.
2869 */
2870 /**
2871 * Capture conversion as specified by JLS 3rd Ed.
2872 */
2873 public Type capture(Type t) {
2874 if (t.tag != CLASS)
2875 return t;
2876 ClassType cls = (ClassType)t;
2877 if (cls.isRaw() || !cls.isParameterized())
2878 return cls;
2880 ClassType G = (ClassType)cls.asElement().asType();
2881 List<Type> A = G.getTypeArguments();
2882 List<Type> T = cls.getTypeArguments();
2883 List<Type> S = freshTypeVariables(T);
2885 List<Type> currentA = A;
2886 List<Type> currentT = T;
2887 List<Type> currentS = S;
2888 boolean captured = false;
2889 while (!currentA.isEmpty() &&
2890 !currentT.isEmpty() &&
2891 !currentS.isEmpty()) {
2892 if (currentS.head != currentT.head) {
2893 captured = true;
2894 WildcardType Ti = (WildcardType)currentT.head;
2895 Type Ui = currentA.head.getUpperBound();
2896 CapturedType Si = (CapturedType)currentS.head;
2897 if (Ui == null)
2898 Ui = syms.objectType;
2899 switch (Ti.kind) {
2900 case UNBOUND:
2901 Si.bound = subst(Ui, A, S);
2902 Si.lower = syms.botType;
2903 break;
2904 case EXTENDS:
2905 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
2906 Si.lower = syms.botType;
2907 break;
2908 case SUPER:
2909 Si.bound = subst(Ui, A, S);
2910 Si.lower = Ti.getSuperBound();
2911 break;
2912 }
2913 if (Si.bound == Si.lower)
2914 currentS.head = Si.bound;
2915 }
2916 currentA = currentA.tail;
2917 currentT = currentT.tail;
2918 currentS = currentS.tail;
2919 }
2920 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
2921 return erasure(t); // some "rare" type involved
2923 if (captured)
2924 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
2925 else
2926 return t;
2927 }
2928 // where
2929 public List<Type> freshTypeVariables(List<Type> types) {
2930 ListBuffer<Type> result = lb();
2931 for (Type t : types) {
2932 if (t.tag == WILDCARD) {
2933 Type bound = ((WildcardType)t).getExtendsBound();
2934 if (bound == null)
2935 bound = syms.objectType;
2936 result.append(new CapturedType(capturedName,
2937 syms.noSymbol,
2938 bound,
2939 syms.botType,
2940 (WildcardType)t));
2941 } else {
2942 result.append(t);
2943 }
2944 }
2945 return result.toList();
2946 }
2947 // </editor-fold>
2949 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
2950 private List<Type> upperBounds(List<Type> ss) {
2951 if (ss.isEmpty()) return ss;
2952 Type head = upperBound(ss.head);
2953 List<Type> tail = upperBounds(ss.tail);
2954 if (head != ss.head || tail != ss.tail)
2955 return tail.prepend(head);
2956 else
2957 return ss;
2958 }
2960 private boolean sideCast(Type from, Type to, Warner warn) {
2961 // We are casting from type $from$ to type $to$, which are
2962 // non-final unrelated types. This method
2963 // tries to reject a cast by transferring type parameters
2964 // from $to$ to $from$ by common superinterfaces.
2965 boolean reverse = false;
2966 Type target = to;
2967 if ((to.tsym.flags() & INTERFACE) == 0) {
2968 assert (from.tsym.flags() & INTERFACE) != 0;
2969 reverse = true;
2970 to = from;
2971 from = target;
2972 }
2973 List<Type> commonSupers = superClosure(to, erasure(from));
2974 boolean giveWarning = commonSupers.isEmpty();
2975 // The arguments to the supers could be unified here to
2976 // get a more accurate analysis
2977 while (commonSupers.nonEmpty()) {
2978 Type t1 = asSuper(from, commonSupers.head.tsym);
2979 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
2980 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
2981 return false;
2982 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
2983 commonSupers = commonSupers.tail;
2984 }
2985 if (giveWarning && !isReifiable(reverse ? from : to))
2986 warn.warnUnchecked();
2987 if (!source.allowCovariantReturns())
2988 // reject if there is a common method signature with
2989 // incompatible return types.
2990 chk.checkCompatibleAbstracts(warn.pos(), from, to);
2991 return true;
2992 }
2994 private boolean sideCastFinal(Type from, Type to, Warner warn) {
2995 // We are casting from type $from$ to type $to$, which are
2996 // unrelated types one of which is final and the other of
2997 // which is an interface. This method
2998 // tries to reject a cast by transferring type parameters
2999 // from the final class to the interface.
3000 boolean reverse = false;
3001 Type target = to;
3002 if ((to.tsym.flags() & INTERFACE) == 0) {
3003 assert (from.tsym.flags() & INTERFACE) != 0;
3004 reverse = true;
3005 to = from;
3006 from = target;
3007 }
3008 assert (from.tsym.flags() & FINAL) != 0;
3009 Type t1 = asSuper(from, to.tsym);
3010 if (t1 == null) return false;
3011 Type t2 = to;
3012 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3013 return false;
3014 if (!source.allowCovariantReturns())
3015 // reject if there is a common method signature with
3016 // incompatible return types.
3017 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3018 if (!isReifiable(target) &&
3019 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3020 warn.warnUnchecked();
3021 return true;
3022 }
3024 private boolean giveWarning(Type from, Type to) {
3025 Type subFrom = asSub(from, to.tsym);
3026 return to.isParameterized() &&
3027 (!(isUnbounded(to) ||
3028 isSubtype(from, to) ||
3029 ((subFrom != null) && isSameType(subFrom, to))));
3030 }
3032 private List<Type> superClosure(Type t, Type s) {
3033 List<Type> cl = List.nil();
3034 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3035 if (isSubtype(s, erasure(l.head))) {
3036 cl = insert(cl, l.head);
3037 } else {
3038 cl = union(cl, superClosure(l.head, s));
3039 }
3040 }
3041 return cl;
3042 }
3044 private boolean containsTypeEquivalent(Type t, Type s) {
3045 return
3046 isSameType(t, s) || // shortcut
3047 containsType(t, s) && containsType(s, t);
3048 }
3050 // <editor-fold defaultstate="collapsed" desc="adapt">
3051 /**
3052 * Adapt a type by computing a substitution which maps a source
3053 * type to a target type.
3054 *
3055 * @param source the source type
3056 * @param target the target type
3057 * @param from the type variables of the computed substitution
3058 * @param to the types of the computed substitution.
3059 */
3060 public void adapt(Type source,
3061 Type target,
3062 ListBuffer<Type> from,
3063 ListBuffer<Type> to) throws AdaptFailure {
3064 new Adapter(from, to).adapt(source, target);
3065 }
3067 class Adapter extends SimpleVisitor<Void, Type> {
3069 ListBuffer<Type> from;
3070 ListBuffer<Type> to;
3071 Map<Symbol,Type> mapping;
3073 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3074 this.from = from;
3075 this.to = to;
3076 mapping = new HashMap<Symbol,Type>();
3077 }
3079 public void adapt(Type source, Type target) throws AdaptFailure {
3080 visit(source, target);
3081 List<Type> fromList = from.toList();
3082 List<Type> toList = to.toList();
3083 while (!fromList.isEmpty()) {
3084 Type val = mapping.get(fromList.head.tsym);
3085 if (toList.head != val)
3086 toList.head = val;
3087 fromList = fromList.tail;
3088 toList = toList.tail;
3089 }
3090 }
3092 @Override
3093 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3094 if (target.tag == CLASS)
3095 adaptRecursive(source.allparams(), target.allparams());
3096 return null;
3097 }
3099 @Override
3100 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3101 if (target.tag == ARRAY)
3102 adaptRecursive(elemtype(source), elemtype(target));
3103 return null;
3104 }
3106 @Override
3107 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3108 if (source.isExtendsBound())
3109 adaptRecursive(upperBound(source), upperBound(target));
3110 else if (source.isSuperBound())
3111 adaptRecursive(lowerBound(source), lowerBound(target));
3112 return null;
3113 }
3115 @Override
3116 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3117 // Check to see if there is
3118 // already a mapping for $source$, in which case
3119 // the old mapping will be merged with the new
3120 Type val = mapping.get(source.tsym);
3121 if (val != null) {
3122 if (val.isSuperBound() && target.isSuperBound()) {
3123 val = isSubtype(lowerBound(val), lowerBound(target))
3124 ? target : val;
3125 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3126 val = isSubtype(upperBound(val), upperBound(target))
3127 ? val : target;
3128 } else if (!isSameType(val, target)) {
3129 throw new AdaptFailure();
3130 }
3131 } else {
3132 val = target;
3133 from.append(source);
3134 to.append(target);
3135 }
3136 mapping.put(source.tsym, val);
3137 return null;
3138 }
3140 @Override
3141 public Void visitType(Type source, Type target) {
3142 return null;
3143 }
3145 private Set<TypePair> cache = new HashSet<TypePair>();
3147 private void adaptRecursive(Type source, Type target) {
3148 TypePair pair = new TypePair(source, target);
3149 if (cache.add(pair)) {
3150 try {
3151 visit(source, target);
3152 } finally {
3153 cache.remove(pair);
3154 }
3155 }
3156 }
3158 private void adaptRecursive(List<Type> source, List<Type> target) {
3159 if (source.length() == target.length()) {
3160 while (source.nonEmpty()) {
3161 adaptRecursive(source.head, target.head);
3162 source = source.tail;
3163 target = target.tail;
3164 }
3165 }
3166 }
3167 }
3169 public static class AdaptFailure extends RuntimeException {
3170 static final long serialVersionUID = -7490231548272701566L;
3171 }
3173 private void adaptSelf(Type t,
3174 ListBuffer<Type> from,
3175 ListBuffer<Type> to) {
3176 try {
3177 //if (t.tsym.type != t)
3178 adapt(t.tsym.type, t, from, to);
3179 } catch (AdaptFailure ex) {
3180 // Adapt should never fail calculating a mapping from
3181 // t.tsym.type to t as there can be no merge problem.
3182 throw new AssertionError(ex);
3183 }
3184 }
3185 // </editor-fold>
3187 /**
3188 * Rewrite all type variables (universal quantifiers) in the given
3189 * type to wildcards (existential quantifiers). This is used to
3190 * determine if a cast is allowed. For example, if high is true
3191 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3192 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3193 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3194 * List<Integer>} with a warning.
3195 * @param t a type
3196 * @param high if true return an upper bound; otherwise a lower
3197 * bound
3198 * @param rewriteTypeVars only rewrite captured wildcards if false;
3199 * otherwise rewrite all type variables
3200 * @return the type rewritten with wildcards (existential
3201 * quantifiers) only
3202 */
3203 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3204 return new Rewriter(high, rewriteTypeVars).rewrite(t);
3205 }
3207 class Rewriter extends UnaryVisitor<Type> {
3209 boolean high;
3210 boolean rewriteTypeVars;
3212 Rewriter(boolean high, boolean rewriteTypeVars) {
3213 this.high = high;
3214 this.rewriteTypeVars = rewriteTypeVars;
3215 }
3217 Type rewrite(Type t) {
3218 ListBuffer<Type> from = new ListBuffer<Type>();
3219 ListBuffer<Type> to = new ListBuffer<Type>();
3220 adaptSelf(t, from, to);
3221 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3222 List<Type> formals = from.toList();
3223 boolean changed = false;
3224 for (Type arg : to.toList()) {
3225 Type bound = visit(arg);
3226 if (arg != bound) {
3227 changed = true;
3228 bound = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
3229 : makeSuperWildcard(bound, (TypeVar)formals.head);
3230 }
3231 rewritten.append(bound);
3232 formals = formals.tail;
3233 }
3234 if (changed)
3235 return subst(t.tsym.type, from.toList(), rewritten.toList());
3236 else
3237 return t;
3238 }
3240 public Type visitType(Type t, Void s) {
3241 return high ? upperBound(t) : lowerBound(t);
3242 }
3244 @Override
3245 public Type visitCapturedType(CapturedType t, Void s) {
3246 return visitWildcardType(t.wildcard, null);
3247 }
3249 @Override
3250 public Type visitTypeVar(TypeVar t, Void s) {
3251 if (rewriteTypeVars)
3252 return high ? t.bound : syms.botType;
3253 else
3254 return t;
3255 }
3257 @Override
3258 public Type visitWildcardType(WildcardType t, Void s) {
3259 Type bound = high ? t.getExtendsBound() :
3260 t.getSuperBound();
3261 if (bound == null)
3262 bound = high ? syms.objectType : syms.botType;
3263 return bound;
3264 }
3265 }
3267 /**
3268 * Create a wildcard with the given upper (extends) bound; create
3269 * an unbounded wildcard if bound is Object.
3270 *
3271 * @param bound the upper bound
3272 * @param formal the formal type parameter that will be
3273 * substituted by the wildcard
3274 */
3275 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3276 if (bound == syms.objectType) {
3277 return new WildcardType(syms.objectType,
3278 BoundKind.UNBOUND,
3279 syms.boundClass,
3280 formal);
3281 } else {
3282 return new WildcardType(bound,
3283 BoundKind.EXTENDS,
3284 syms.boundClass,
3285 formal);
3286 }
3287 }
3289 /**
3290 * Create a wildcard with the given lower (super) bound; create an
3291 * unbounded wildcard if bound is bottom (type of {@code null}).
3292 *
3293 * @param bound the lower bound
3294 * @param formal the formal type parameter that will be
3295 * substituted by the wildcard
3296 */
3297 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3298 if (bound.tag == BOT) {
3299 return new WildcardType(syms.objectType,
3300 BoundKind.UNBOUND,
3301 syms.boundClass,
3302 formal);
3303 } else {
3304 return new WildcardType(bound,
3305 BoundKind.SUPER,
3306 syms.boundClass,
3307 formal);
3308 }
3309 }
3311 /**
3312 * A wrapper for a type that allows use in sets.
3313 */
3314 class SingletonType {
3315 final Type t;
3316 SingletonType(Type t) {
3317 this.t = t;
3318 }
3319 public int hashCode() {
3320 return Types.this.hashCode(t);
3321 }
3322 public boolean equals(Object obj) {
3323 return (obj instanceof SingletonType) &&
3324 isSameType(t, ((SingletonType)obj).t);
3325 }
3326 public String toString() {
3327 return t.toString();
3328 }
3329 }
3330 // </editor-fold>
3332 // <editor-fold defaultstate="collapsed" desc="Visitors">
3333 /**
3334 * A default visitor for types. All visitor methods except
3335 * visitType are implemented by delegating to visitType. Concrete
3336 * subclasses must provide an implementation of visitType and can
3337 * override other methods as needed.
3338 *
3339 * @param <R> the return type of the operation implemented by this
3340 * visitor; use Void if no return type is needed.
3341 * @param <S> the type of the second argument (the first being the
3342 * type itself) of the operation implemented by this visitor; use
3343 * Void if a second argument is not needed.
3344 */
3345 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3346 final public R visit(Type t, S s) { return t.accept(this, s); }
3347 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3348 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3349 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3350 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3351 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3352 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3353 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3354 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3355 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3356 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3357 }
3359 /**
3360 * A default visitor for symbols. All visitor methods except
3361 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3362 * subclasses must provide an implementation of visitSymbol and can
3363 * override other methods as needed.
3364 *
3365 * @param <R> the return type of the operation implemented by this
3366 * visitor; use Void if no return type is needed.
3367 * @param <S> the type of the second argument (the first being the
3368 * symbol itself) of the operation implemented by this visitor; use
3369 * Void if a second argument is not needed.
3370 */
3371 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3372 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3373 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3374 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3375 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3376 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3377 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3378 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3379 }
3381 /**
3382 * A <em>simple</em> visitor for types. This visitor is simple as
3383 * captured wildcards, for-all types (generic methods), and
3384 * undetermined type variables (part of inference) are hidden.
3385 * Captured wildcards are hidden by treating them as type
3386 * variables and the rest are hidden by visiting their qtypes.
3387 *
3388 * @param <R> the return type of the operation implemented by this
3389 * visitor; use Void if no return type is needed.
3390 * @param <S> the type of the second argument (the first being the
3391 * type itself) of the operation implemented by this visitor; use
3392 * Void if a second argument is not needed.
3393 */
3394 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3395 @Override
3396 public R visitCapturedType(CapturedType t, S s) {
3397 return visitTypeVar(t, s);
3398 }
3399 @Override
3400 public R visitForAll(ForAll t, S s) {
3401 return visit(t.qtype, s);
3402 }
3403 @Override
3404 public R visitUndetVar(UndetVar t, S s) {
3405 return visit(t.qtype, s);
3406 }
3407 }
3409 /**
3410 * A plain relation on types. That is a 2-ary function on the
3411 * form Type × Type → Boolean.
3412 * <!-- In plain text: Type x Type -> Boolean -->
3413 */
3414 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3416 /**
3417 * A convenience visitor for implementing operations that only
3418 * require one argument (the type itself), that is, unary
3419 * operations.
3420 *
3421 * @param <R> the return type of the operation implemented by this
3422 * visitor; use Void if no return type is needed.
3423 */
3424 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3425 final public R visit(Type t) { return t.accept(this, null); }
3426 }
3428 /**
3429 * A visitor for implementing a mapping from types to types. The
3430 * default behavior of this class is to implement the identity
3431 * mapping (mapping a type to itself). This can be overridden in
3432 * subclasses.
3433 *
3434 * @param <S> the type of the second argument (the first being the
3435 * type itself) of this mapping; use Void if a second argument is
3436 * not needed.
3437 */
3438 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3439 final public Type visit(Type t) { return t.accept(this, null); }
3440 public Type visitType(Type t, S s) { return t; }
3441 }
3442 // </editor-fold>
3443 }