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