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