Wed, 13 Apr 2011 11:35:43 -0700
7032975: API files in javax.annotation.processing need to be updated for references to JLS
7032972: API files in javax.tools need to updated for references to JVM Spec with editions/hyperlinks
7032978: API files in javax.tools need to be updated for references to JLS with editions/hyperlinks
Summary: Removed URLs and 'edition' references
Reviewed-by: jjg, darcy
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 * @jls section 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 isSubSignature(t, s, true);
1996 }
1998 public boolean isSubSignature(Type t, Type s, boolean strict) {
1999 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2000 }
2002 /**
2003 * Returns true iff these signatures are related by <em>override
2004 * equivalence</em>. This is the natural extension of
2005 * isSubSignature to an equivalence relation.
2006 *
2007 * @jls section 8.4.2.
2008 * @see #isSubSignature(Type t, Type s)
2009 * @param t a signature (possible raw, could be subjected to
2010 * erasure).
2011 * @param s a signature (possible raw, could be subjected to
2012 * erasure).
2013 * @return true if either argument is a sub signature of the other.
2014 */
2015 public boolean overrideEquivalent(Type t, Type s) {
2016 return hasSameArgs(t, s) ||
2017 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2018 }
2020 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2021 class ImplementationCache {
2023 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2024 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2026 class Entry {
2027 final MethodSymbol cachedImpl;
2028 final Filter<Symbol> implFilter;
2029 final boolean checkResult;
2030 final int prevMark;
2032 public Entry(MethodSymbol cachedImpl,
2033 Filter<Symbol> scopeFilter,
2034 boolean checkResult,
2035 int prevMark) {
2036 this.cachedImpl = cachedImpl;
2037 this.implFilter = scopeFilter;
2038 this.checkResult = checkResult;
2039 this.prevMark = prevMark;
2040 }
2042 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2043 return this.implFilter == scopeFilter &&
2044 this.checkResult == checkResult &&
2045 this.prevMark == mark;
2046 }
2047 }
2049 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2050 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2051 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2052 if (cache == null) {
2053 cache = new HashMap<TypeSymbol, Entry>();
2054 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2055 }
2056 Entry e = cache.get(origin);
2057 CompoundScope members = membersClosure(origin.type);
2058 if (e == null ||
2059 !e.matches(implFilter, checkResult, members.getMark())) {
2060 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2061 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2062 return impl;
2063 }
2064 else {
2065 return e.cachedImpl;
2066 }
2067 }
2069 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2070 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2071 while (t.tag == TYPEVAR)
2072 t = t.getUpperBound();
2073 TypeSymbol c = t.tsym;
2074 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2075 e.scope != null;
2076 e = e.next(implFilter)) {
2077 if (e.sym != null &&
2078 e.sym.overrides(ms, origin, Types.this, checkResult))
2079 return (MethodSymbol)e.sym;
2080 }
2081 }
2082 return null;
2083 }
2084 }
2086 private ImplementationCache implCache = new ImplementationCache();
2088 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2089 return implCache.get(ms, origin, checkResult, implFilter);
2090 }
2091 // </editor-fold>
2093 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2094 public CompoundScope membersClosure(Type site) {
2095 return membersClosure.visit(site);
2096 }
2098 UnaryVisitor<CompoundScope> membersClosure = new UnaryVisitor<CompoundScope>() {
2100 public CompoundScope visitType(Type t, Void s) {
2101 return null;
2102 }
2104 @Override
2105 public CompoundScope visitClassType(ClassType t, Void s) {
2106 ClassSymbol csym = (ClassSymbol)t.tsym;
2107 if (csym.membersClosure == null) {
2108 CompoundScope membersClosure = new CompoundScope(csym);
2109 for (Type i : interfaces(t)) {
2110 membersClosure.addSubScope(visit(i));
2111 }
2112 membersClosure.addSubScope(visit(supertype(t)));
2113 membersClosure.addSubScope(csym.members());
2114 csym.membersClosure = membersClosure;
2115 }
2116 return csym.membersClosure;
2117 }
2119 @Override
2120 public CompoundScope visitTypeVar(TypeVar t, Void s) {
2121 return visit(t.getUpperBound());
2122 }
2123 };
2124 // </editor-fold>
2126 /**
2127 * Does t have the same arguments as s? It is assumed that both
2128 * types are (possibly polymorphic) method types. Monomorphic
2129 * method types "have the same arguments", if their argument lists
2130 * are equal. Polymorphic method types "have the same arguments",
2131 * if they have the same arguments after renaming all type
2132 * variables of one to corresponding type variables in the other,
2133 * where correspondence is by position in the type parameter list.
2134 */
2135 public boolean hasSameArgs(Type t, Type s) {
2136 return hasSameArgs(t, s, true);
2137 }
2139 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2140 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2141 }
2143 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2144 return hasSameArgs.visit(t, s);
2145 }
2146 // where
2147 private class HasSameArgs extends TypeRelation {
2149 boolean strict;
2151 public HasSameArgs(boolean strict) {
2152 this.strict = strict;
2153 }
2155 public Boolean visitType(Type t, Type s) {
2156 throw new AssertionError();
2157 }
2159 @Override
2160 public Boolean visitMethodType(MethodType t, Type s) {
2161 return s.tag == METHOD
2162 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2163 }
2165 @Override
2166 public Boolean visitForAll(ForAll t, Type s) {
2167 if (s.tag != FORALL)
2168 return strict ? false : visitMethodType(t.asMethodType(), s);
2170 ForAll forAll = (ForAll)s;
2171 return hasSameBounds(t, forAll)
2172 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2173 }
2175 @Override
2176 public Boolean visitErrorType(ErrorType t, Type s) {
2177 return false;
2178 }
2179 };
2181 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2182 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2184 // </editor-fold>
2186 // <editor-fold defaultstate="collapsed" desc="subst">
2187 public List<Type> subst(List<Type> ts,
2188 List<Type> from,
2189 List<Type> to) {
2190 return new Subst(from, to).subst(ts);
2191 }
2193 /**
2194 * Substitute all occurrences of a type in `from' with the
2195 * corresponding type in `to' in 't'. Match lists `from' and `to'
2196 * from the right: If lists have different length, discard leading
2197 * elements of the longer list.
2198 */
2199 public Type subst(Type t, List<Type> from, List<Type> to) {
2200 return new Subst(from, to).subst(t);
2201 }
2203 private class Subst extends UnaryVisitor<Type> {
2204 List<Type> from;
2205 List<Type> to;
2207 public Subst(List<Type> from, List<Type> to) {
2208 int fromLength = from.length();
2209 int toLength = to.length();
2210 while (fromLength > toLength) {
2211 fromLength--;
2212 from = from.tail;
2213 }
2214 while (fromLength < toLength) {
2215 toLength--;
2216 to = to.tail;
2217 }
2218 this.from = from;
2219 this.to = to;
2220 }
2222 Type subst(Type t) {
2223 if (from.tail == null)
2224 return t;
2225 else
2226 return visit(t);
2227 }
2229 List<Type> subst(List<Type> ts) {
2230 if (from.tail == null)
2231 return ts;
2232 boolean wild = false;
2233 if (ts.nonEmpty() && from.nonEmpty()) {
2234 Type head1 = subst(ts.head);
2235 List<Type> tail1 = subst(ts.tail);
2236 if (head1 != ts.head || tail1 != ts.tail)
2237 return tail1.prepend(head1);
2238 }
2239 return ts;
2240 }
2242 public Type visitType(Type t, Void ignored) {
2243 return t;
2244 }
2246 @Override
2247 public Type visitMethodType(MethodType t, Void ignored) {
2248 List<Type> argtypes = subst(t.argtypes);
2249 Type restype = subst(t.restype);
2250 List<Type> thrown = subst(t.thrown);
2251 if (argtypes == t.argtypes &&
2252 restype == t.restype &&
2253 thrown == t.thrown)
2254 return t;
2255 else
2256 return new MethodType(argtypes, restype, thrown, t.tsym);
2257 }
2259 @Override
2260 public Type visitTypeVar(TypeVar t, Void ignored) {
2261 for (List<Type> from = this.from, to = this.to;
2262 from.nonEmpty();
2263 from = from.tail, to = to.tail) {
2264 if (t == from.head) {
2265 return to.head.withTypeVar(t);
2266 }
2267 }
2268 return t;
2269 }
2271 @Override
2272 public Type visitClassType(ClassType t, Void ignored) {
2273 if (!t.isCompound()) {
2274 List<Type> typarams = t.getTypeArguments();
2275 List<Type> typarams1 = subst(typarams);
2276 Type outer = t.getEnclosingType();
2277 Type outer1 = subst(outer);
2278 if (typarams1 == typarams && outer1 == outer)
2279 return t;
2280 else
2281 return new ClassType(outer1, typarams1, t.tsym);
2282 } else {
2283 Type st = subst(supertype(t));
2284 List<Type> is = upperBounds(subst(interfaces(t)));
2285 if (st == supertype(t) && is == interfaces(t))
2286 return t;
2287 else
2288 return makeCompoundType(is.prepend(st));
2289 }
2290 }
2292 @Override
2293 public Type visitWildcardType(WildcardType t, Void ignored) {
2294 Type bound = t.type;
2295 if (t.kind != BoundKind.UNBOUND)
2296 bound = subst(bound);
2297 if (bound == t.type) {
2298 return t;
2299 } else {
2300 if (t.isExtendsBound() && bound.isExtendsBound())
2301 bound = upperBound(bound);
2302 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2303 }
2304 }
2306 @Override
2307 public Type visitArrayType(ArrayType t, Void ignored) {
2308 Type elemtype = subst(t.elemtype);
2309 if (elemtype == t.elemtype)
2310 return t;
2311 else
2312 return new ArrayType(elemtype, t.tsym);
2313 }
2315 @Override
2316 public Type visitForAll(ForAll t, Void ignored) {
2317 if (Type.containsAny(to, t.tvars)) {
2318 //perform alpha-renaming of free-variables in 't'
2319 //if 'to' types contain variables that are free in 't'
2320 List<Type> freevars = newInstances(t.tvars);
2321 t = new ForAll(freevars,
2322 Types.this.subst(t.qtype, t.tvars, freevars));
2323 }
2324 List<Type> tvars1 = substBounds(t.tvars, from, to);
2325 Type qtype1 = subst(t.qtype);
2326 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2327 return t;
2328 } else if (tvars1 == t.tvars) {
2329 return new ForAll(tvars1, qtype1);
2330 } else {
2331 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2332 }
2333 }
2335 @Override
2336 public Type visitErrorType(ErrorType t, Void ignored) {
2337 return t;
2338 }
2339 }
2341 public List<Type> substBounds(List<Type> tvars,
2342 List<Type> from,
2343 List<Type> to) {
2344 if (tvars.isEmpty())
2345 return tvars;
2346 ListBuffer<Type> newBoundsBuf = lb();
2347 boolean changed = false;
2348 // calculate new bounds
2349 for (Type t : tvars) {
2350 TypeVar tv = (TypeVar) t;
2351 Type bound = subst(tv.bound, from, to);
2352 if (bound != tv.bound)
2353 changed = true;
2354 newBoundsBuf.append(bound);
2355 }
2356 if (!changed)
2357 return tvars;
2358 ListBuffer<Type> newTvars = lb();
2359 // create new type variables without bounds
2360 for (Type t : tvars) {
2361 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2362 }
2363 // the new bounds should use the new type variables in place
2364 // of the old
2365 List<Type> newBounds = newBoundsBuf.toList();
2366 from = tvars;
2367 to = newTvars.toList();
2368 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2369 newBounds.head = subst(newBounds.head, from, to);
2370 }
2371 newBounds = newBoundsBuf.toList();
2372 // set the bounds of new type variables to the new bounds
2373 for (Type t : newTvars.toList()) {
2374 TypeVar tv = (TypeVar) t;
2375 tv.bound = newBounds.head;
2376 newBounds = newBounds.tail;
2377 }
2378 return newTvars.toList();
2379 }
2381 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2382 Type bound1 = subst(t.bound, from, to);
2383 if (bound1 == t.bound)
2384 return t;
2385 else {
2386 // create new type variable without bounds
2387 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2388 // the new bound should use the new type variable in place
2389 // of the old
2390 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2391 return tv;
2392 }
2393 }
2394 // </editor-fold>
2396 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2397 /**
2398 * Does t have the same bounds for quantified variables as s?
2399 */
2400 boolean hasSameBounds(ForAll t, ForAll s) {
2401 List<Type> l1 = t.tvars;
2402 List<Type> l2 = s.tvars;
2403 while (l1.nonEmpty() && l2.nonEmpty() &&
2404 isSameType(l1.head.getUpperBound(),
2405 subst(l2.head.getUpperBound(),
2406 s.tvars,
2407 t.tvars))) {
2408 l1 = l1.tail;
2409 l2 = l2.tail;
2410 }
2411 return l1.isEmpty() && l2.isEmpty();
2412 }
2413 // </editor-fold>
2415 // <editor-fold defaultstate="collapsed" desc="newInstances">
2416 /** Create new vector of type variables from list of variables
2417 * changing all recursive bounds from old to new list.
2418 */
2419 public List<Type> newInstances(List<Type> tvars) {
2420 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2421 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2422 TypeVar tv = (TypeVar) l.head;
2423 tv.bound = subst(tv.bound, tvars, tvars1);
2424 }
2425 return tvars1;
2426 }
2427 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2428 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2429 };
2430 // </editor-fold>
2432 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2433 return original.accept(methodWithParameters, newParams);
2434 }
2435 // where
2436 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2437 public Type visitType(Type t, List<Type> newParams) {
2438 throw new IllegalArgumentException("Not a method type: " + t);
2439 }
2440 public Type visitMethodType(MethodType t, List<Type> newParams) {
2441 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2442 }
2443 public Type visitForAll(ForAll t, List<Type> newParams) {
2444 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2445 }
2446 };
2448 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2449 return original.accept(methodWithThrown, newThrown);
2450 }
2451 // where
2452 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2453 public Type visitType(Type t, List<Type> newThrown) {
2454 throw new IllegalArgumentException("Not a method type: " + t);
2455 }
2456 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2457 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2458 }
2459 public Type visitForAll(ForAll t, List<Type> newThrown) {
2460 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2461 }
2462 };
2464 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2465 return original.accept(methodWithReturn, newReturn);
2466 }
2467 // where
2468 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2469 public Type visitType(Type t, Type newReturn) {
2470 throw new IllegalArgumentException("Not a method type: " + t);
2471 }
2472 public Type visitMethodType(MethodType t, Type newReturn) {
2473 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2474 }
2475 public Type visitForAll(ForAll t, Type newReturn) {
2476 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2477 }
2478 };
2480 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2481 public Type createErrorType(Type originalType) {
2482 return new ErrorType(originalType, syms.errSymbol);
2483 }
2485 public Type createErrorType(ClassSymbol c, Type originalType) {
2486 return new ErrorType(c, originalType);
2487 }
2489 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2490 return new ErrorType(name, container, originalType);
2491 }
2492 // </editor-fold>
2494 // <editor-fold defaultstate="collapsed" desc="rank">
2495 /**
2496 * The rank of a class is the length of the longest path between
2497 * the class and java.lang.Object in the class inheritance
2498 * graph. Undefined for all but reference types.
2499 */
2500 public int rank(Type t) {
2501 switch(t.tag) {
2502 case CLASS: {
2503 ClassType cls = (ClassType)t;
2504 if (cls.rank_field < 0) {
2505 Name fullname = cls.tsym.getQualifiedName();
2506 if (fullname == names.java_lang_Object)
2507 cls.rank_field = 0;
2508 else {
2509 int r = rank(supertype(cls));
2510 for (List<Type> l = interfaces(cls);
2511 l.nonEmpty();
2512 l = l.tail) {
2513 if (rank(l.head) > r)
2514 r = rank(l.head);
2515 }
2516 cls.rank_field = r + 1;
2517 }
2518 }
2519 return cls.rank_field;
2520 }
2521 case TYPEVAR: {
2522 TypeVar tvar = (TypeVar)t;
2523 if (tvar.rank_field < 0) {
2524 int r = rank(supertype(tvar));
2525 for (List<Type> l = interfaces(tvar);
2526 l.nonEmpty();
2527 l = l.tail) {
2528 if (rank(l.head) > r) r = rank(l.head);
2529 }
2530 tvar.rank_field = r + 1;
2531 }
2532 return tvar.rank_field;
2533 }
2534 case ERROR:
2535 return 0;
2536 default:
2537 throw new AssertionError();
2538 }
2539 }
2540 // </editor-fold>
2542 /**
2543 * Helper method for generating a string representation of a given type
2544 * accordingly to a given locale
2545 */
2546 public String toString(Type t, Locale locale) {
2547 return Printer.createStandardPrinter(messages).visit(t, locale);
2548 }
2550 /**
2551 * Helper method for generating a string representation of a given type
2552 * accordingly to a given locale
2553 */
2554 public String toString(Symbol t, Locale locale) {
2555 return Printer.createStandardPrinter(messages).visit(t, locale);
2556 }
2558 // <editor-fold defaultstate="collapsed" desc="toString">
2559 /**
2560 * This toString is slightly more descriptive than the one on Type.
2561 *
2562 * @deprecated Types.toString(Type t, Locale l) provides better support
2563 * for localization
2564 */
2565 @Deprecated
2566 public String toString(Type t) {
2567 if (t.tag == FORALL) {
2568 ForAll forAll = (ForAll)t;
2569 return typaramsString(forAll.tvars) + forAll.qtype;
2570 }
2571 return "" + t;
2572 }
2573 // where
2574 private String typaramsString(List<Type> tvars) {
2575 StringBuilder s = new StringBuilder();
2576 s.append('<');
2577 boolean first = true;
2578 for (Type t : tvars) {
2579 if (!first) s.append(", ");
2580 first = false;
2581 appendTyparamString(((TypeVar)t), s);
2582 }
2583 s.append('>');
2584 return s.toString();
2585 }
2586 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2587 buf.append(t);
2588 if (t.bound == null ||
2589 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2590 return;
2591 buf.append(" extends "); // Java syntax; no need for i18n
2592 Type bound = t.bound;
2593 if (!bound.isCompound()) {
2594 buf.append(bound);
2595 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2596 buf.append(supertype(t));
2597 for (Type intf : interfaces(t)) {
2598 buf.append('&');
2599 buf.append(intf);
2600 }
2601 } else {
2602 // No superclass was given in bounds.
2603 // In this case, supertype is Object, erasure is first interface.
2604 boolean first = true;
2605 for (Type intf : interfaces(t)) {
2606 if (!first) buf.append('&');
2607 first = false;
2608 buf.append(intf);
2609 }
2610 }
2611 }
2612 // </editor-fold>
2614 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2615 /**
2616 * A cache for closures.
2617 *
2618 * <p>A closure is a list of all the supertypes and interfaces of
2619 * a class or interface type, ordered by ClassSymbol.precedes
2620 * (that is, subclasses come first, arbitrary but fixed
2621 * otherwise).
2622 */
2623 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2625 /**
2626 * Returns the closure of a class or interface type.
2627 */
2628 public List<Type> closure(Type t) {
2629 List<Type> cl = closureCache.get(t);
2630 if (cl == null) {
2631 Type st = supertype(t);
2632 if (!t.isCompound()) {
2633 if (st.tag == CLASS) {
2634 cl = insert(closure(st), t);
2635 } else if (st.tag == TYPEVAR) {
2636 cl = closure(st).prepend(t);
2637 } else {
2638 cl = List.of(t);
2639 }
2640 } else {
2641 cl = closure(supertype(t));
2642 }
2643 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2644 cl = union(cl, closure(l.head));
2645 closureCache.put(t, cl);
2646 }
2647 return cl;
2648 }
2650 /**
2651 * Insert a type in a closure
2652 */
2653 public List<Type> insert(List<Type> cl, Type t) {
2654 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2655 return cl.prepend(t);
2656 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2657 return insert(cl.tail, t).prepend(cl.head);
2658 } else {
2659 return cl;
2660 }
2661 }
2663 /**
2664 * Form the union of two closures
2665 */
2666 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2667 if (cl1.isEmpty()) {
2668 return cl2;
2669 } else if (cl2.isEmpty()) {
2670 return cl1;
2671 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2672 return union(cl1.tail, cl2).prepend(cl1.head);
2673 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2674 return union(cl1, cl2.tail).prepend(cl2.head);
2675 } else {
2676 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2677 }
2678 }
2680 /**
2681 * Intersect two closures
2682 */
2683 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2684 if (cl1 == cl2)
2685 return cl1;
2686 if (cl1.isEmpty() || cl2.isEmpty())
2687 return List.nil();
2688 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2689 return intersect(cl1.tail, cl2);
2690 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2691 return intersect(cl1, cl2.tail);
2692 if (isSameType(cl1.head, cl2.head))
2693 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2694 if (cl1.head.tsym == cl2.head.tsym &&
2695 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2696 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2697 Type merge = merge(cl1.head,cl2.head);
2698 return intersect(cl1.tail, cl2.tail).prepend(merge);
2699 }
2700 if (cl1.head.isRaw() || cl2.head.isRaw())
2701 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2702 }
2703 return intersect(cl1.tail, cl2.tail);
2704 }
2705 // where
2706 class TypePair {
2707 final Type t1;
2708 final Type t2;
2709 TypePair(Type t1, Type t2) {
2710 this.t1 = t1;
2711 this.t2 = t2;
2712 }
2713 @Override
2714 public int hashCode() {
2715 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2716 }
2717 @Override
2718 public boolean equals(Object obj) {
2719 if (!(obj instanceof TypePair))
2720 return false;
2721 TypePair typePair = (TypePair)obj;
2722 return isSameType(t1, typePair.t1)
2723 && isSameType(t2, typePair.t2);
2724 }
2725 }
2726 Set<TypePair> mergeCache = new HashSet<TypePair>();
2727 private Type merge(Type c1, Type c2) {
2728 ClassType class1 = (ClassType) c1;
2729 List<Type> act1 = class1.getTypeArguments();
2730 ClassType class2 = (ClassType) c2;
2731 List<Type> act2 = class2.getTypeArguments();
2732 ListBuffer<Type> merged = new ListBuffer<Type>();
2733 List<Type> typarams = class1.tsym.type.getTypeArguments();
2735 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2736 if (containsType(act1.head, act2.head)) {
2737 merged.append(act1.head);
2738 } else if (containsType(act2.head, act1.head)) {
2739 merged.append(act2.head);
2740 } else {
2741 TypePair pair = new TypePair(c1, c2);
2742 Type m;
2743 if (mergeCache.add(pair)) {
2744 m = new WildcardType(lub(upperBound(act1.head),
2745 upperBound(act2.head)),
2746 BoundKind.EXTENDS,
2747 syms.boundClass);
2748 mergeCache.remove(pair);
2749 } else {
2750 m = new WildcardType(syms.objectType,
2751 BoundKind.UNBOUND,
2752 syms.boundClass);
2753 }
2754 merged.append(m.withTypeVar(typarams.head));
2755 }
2756 act1 = act1.tail;
2757 act2 = act2.tail;
2758 typarams = typarams.tail;
2759 }
2760 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2761 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2762 }
2764 /**
2765 * Return the minimum type of a closure, a compound type if no
2766 * unique minimum exists.
2767 */
2768 private Type compoundMin(List<Type> cl) {
2769 if (cl.isEmpty()) return syms.objectType;
2770 List<Type> compound = closureMin(cl);
2771 if (compound.isEmpty())
2772 return null;
2773 else if (compound.tail.isEmpty())
2774 return compound.head;
2775 else
2776 return makeCompoundType(compound);
2777 }
2779 /**
2780 * Return the minimum types of a closure, suitable for computing
2781 * compoundMin or glb.
2782 */
2783 private List<Type> closureMin(List<Type> cl) {
2784 ListBuffer<Type> classes = lb();
2785 ListBuffer<Type> interfaces = lb();
2786 while (!cl.isEmpty()) {
2787 Type current = cl.head;
2788 if (current.isInterface())
2789 interfaces.append(current);
2790 else
2791 classes.append(current);
2792 ListBuffer<Type> candidates = lb();
2793 for (Type t : cl.tail) {
2794 if (!isSubtypeNoCapture(current, t))
2795 candidates.append(t);
2796 }
2797 cl = candidates.toList();
2798 }
2799 return classes.appendList(interfaces).toList();
2800 }
2802 /**
2803 * Return the least upper bound of pair of types. if the lub does
2804 * not exist return null.
2805 */
2806 public Type lub(Type t1, Type t2) {
2807 return lub(List.of(t1, t2));
2808 }
2810 /**
2811 * Return the least upper bound (lub) of set of types. If the lub
2812 * does not exist return the type of null (bottom).
2813 */
2814 public Type lub(List<Type> ts) {
2815 final int ARRAY_BOUND = 1;
2816 final int CLASS_BOUND = 2;
2817 int boundkind = 0;
2818 for (Type t : ts) {
2819 switch (t.tag) {
2820 case CLASS:
2821 boundkind |= CLASS_BOUND;
2822 break;
2823 case ARRAY:
2824 boundkind |= ARRAY_BOUND;
2825 break;
2826 case TYPEVAR:
2827 do {
2828 t = t.getUpperBound();
2829 } while (t.tag == TYPEVAR);
2830 if (t.tag == ARRAY) {
2831 boundkind |= ARRAY_BOUND;
2832 } else {
2833 boundkind |= CLASS_BOUND;
2834 }
2835 break;
2836 default:
2837 if (t.isPrimitive())
2838 return syms.errType;
2839 }
2840 }
2841 switch (boundkind) {
2842 case 0:
2843 return syms.botType;
2845 case ARRAY_BOUND:
2846 // calculate lub(A[], B[])
2847 List<Type> elements = Type.map(ts, elemTypeFun);
2848 for (Type t : elements) {
2849 if (t.isPrimitive()) {
2850 // if a primitive type is found, then return
2851 // arraySuperType unless all the types are the
2852 // same
2853 Type first = ts.head;
2854 for (Type s : ts.tail) {
2855 if (!isSameType(first, s)) {
2856 // lub(int[], B[]) is Cloneable & Serializable
2857 return arraySuperType();
2858 }
2859 }
2860 // all the array types are the same, return one
2861 // lub(int[], int[]) is int[]
2862 return first;
2863 }
2864 }
2865 // lub(A[], B[]) is lub(A, B)[]
2866 return new ArrayType(lub(elements), syms.arrayClass);
2868 case CLASS_BOUND:
2869 // calculate lub(A, B)
2870 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2871 ts = ts.tail;
2872 Assert.check(!ts.isEmpty());
2873 //step 1 - compute erased candidate set (EC)
2874 List<Type> cl = erasedSupertypes(ts.head);
2875 for (Type t : ts.tail) {
2876 if (t.tag == CLASS || t.tag == TYPEVAR)
2877 cl = intersect(cl, erasedSupertypes(t));
2878 }
2879 //step 2 - compute minimal erased candidate set (MEC)
2880 List<Type> mec = closureMin(cl);
2881 //step 3 - for each element G in MEC, compute lci(Inv(G))
2882 List<Type> candidates = List.nil();
2883 for (Type erasedSupertype : mec) {
2884 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
2885 for (Type t : ts) {
2886 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
2887 }
2888 candidates = candidates.appendList(lci);
2889 }
2890 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
2891 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
2892 return compoundMin(candidates);
2894 default:
2895 // calculate lub(A, B[])
2896 List<Type> classes = List.of(arraySuperType());
2897 for (Type t : ts) {
2898 if (t.tag != ARRAY) // Filter out any arrays
2899 classes = classes.prepend(t);
2900 }
2901 // lub(A, B[]) is lub(A, arraySuperType)
2902 return lub(classes);
2903 }
2904 }
2905 // where
2906 List<Type> erasedSupertypes(Type t) {
2907 ListBuffer<Type> buf = lb();
2908 for (Type sup : closure(t)) {
2909 if (sup.tag == TYPEVAR) {
2910 buf.append(sup);
2911 } else {
2912 buf.append(erasure(sup));
2913 }
2914 }
2915 return buf.toList();
2916 }
2918 private Type arraySuperType = null;
2919 private Type arraySuperType() {
2920 // initialized lazily to avoid problems during compiler startup
2921 if (arraySuperType == null) {
2922 synchronized (this) {
2923 if (arraySuperType == null) {
2924 // JLS 10.8: all arrays implement Cloneable and Serializable.
2925 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2926 syms.cloneableType),
2927 syms.objectType);
2928 }
2929 }
2930 }
2931 return arraySuperType;
2932 }
2933 // </editor-fold>
2935 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2936 public Type glb(List<Type> ts) {
2937 Type t1 = ts.head;
2938 for (Type t2 : ts.tail) {
2939 if (t1.isErroneous())
2940 return t1;
2941 t1 = glb(t1, t2);
2942 }
2943 return t1;
2944 }
2945 //where
2946 public Type glb(Type t, Type s) {
2947 if (s == null)
2948 return t;
2949 else if (t.isPrimitive() || s.isPrimitive())
2950 return syms.errType;
2951 else if (isSubtypeNoCapture(t, s))
2952 return t;
2953 else if (isSubtypeNoCapture(s, t))
2954 return s;
2956 List<Type> closure = union(closure(t), closure(s));
2957 List<Type> bounds = closureMin(closure);
2959 if (bounds.isEmpty()) { // length == 0
2960 return syms.objectType;
2961 } else if (bounds.tail.isEmpty()) { // length == 1
2962 return bounds.head;
2963 } else { // length > 1
2964 int classCount = 0;
2965 for (Type bound : bounds)
2966 if (!bound.isInterface())
2967 classCount++;
2968 if (classCount > 1)
2969 return createErrorType(t);
2970 }
2971 return makeCompoundType(bounds);
2972 }
2973 // </editor-fold>
2975 // <editor-fold defaultstate="collapsed" desc="hashCode">
2976 /**
2977 * Compute a hash code on a type.
2978 */
2979 public static int hashCode(Type t) {
2980 return hashCode.visit(t);
2981 }
2982 // where
2983 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
2985 public Integer visitType(Type t, Void ignored) {
2986 return t.tag;
2987 }
2989 @Override
2990 public Integer visitClassType(ClassType t, Void ignored) {
2991 int result = visit(t.getEnclosingType());
2992 result *= 127;
2993 result += t.tsym.flatName().hashCode();
2994 for (Type s : t.getTypeArguments()) {
2995 result *= 127;
2996 result += visit(s);
2997 }
2998 return result;
2999 }
3001 @Override
3002 public Integer visitWildcardType(WildcardType t, Void ignored) {
3003 int result = t.kind.hashCode();
3004 if (t.type != null) {
3005 result *= 127;
3006 result += visit(t.type);
3007 }
3008 return result;
3009 }
3011 @Override
3012 public Integer visitArrayType(ArrayType t, Void ignored) {
3013 return visit(t.elemtype) + 12;
3014 }
3016 @Override
3017 public Integer visitTypeVar(TypeVar t, Void ignored) {
3018 return System.identityHashCode(t.tsym);
3019 }
3021 @Override
3022 public Integer visitUndetVar(UndetVar t, Void ignored) {
3023 return System.identityHashCode(t);
3024 }
3026 @Override
3027 public Integer visitErrorType(ErrorType t, Void ignored) {
3028 return 0;
3029 }
3030 };
3031 // </editor-fold>
3033 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3034 /**
3035 * Does t have a result that is a subtype of the result type of s,
3036 * suitable for covariant returns? It is assumed that both types
3037 * are (possibly polymorphic) method types. Monomorphic method
3038 * types are handled in the obvious way. Polymorphic method types
3039 * require renaming all type variables of one to corresponding
3040 * type variables in the other, where correspondence is by
3041 * position in the type parameter list. */
3042 public boolean resultSubtype(Type t, Type s, Warner warner) {
3043 List<Type> tvars = t.getTypeArguments();
3044 List<Type> svars = s.getTypeArguments();
3045 Type tres = t.getReturnType();
3046 Type sres = subst(s.getReturnType(), svars, tvars);
3047 return covariantReturnType(tres, sres, warner);
3048 }
3050 /**
3051 * Return-Type-Substitutable.
3052 * @jls section 8.4.5
3053 */
3054 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3055 if (hasSameArgs(r1, r2))
3056 return resultSubtype(r1, r2, Warner.noWarnings);
3057 else
3058 return covariantReturnType(r1.getReturnType(),
3059 erasure(r2.getReturnType()),
3060 Warner.noWarnings);
3061 }
3063 public boolean returnTypeSubstitutable(Type r1,
3064 Type r2, Type r2res,
3065 Warner warner) {
3066 if (isSameType(r1.getReturnType(), r2res))
3067 return true;
3068 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3069 return false;
3071 if (hasSameArgs(r1, r2))
3072 return covariantReturnType(r1.getReturnType(), r2res, warner);
3073 if (!source.allowCovariantReturns())
3074 return false;
3075 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3076 return true;
3077 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3078 return false;
3079 warner.warn(LintCategory.UNCHECKED);
3080 return true;
3081 }
3083 /**
3084 * Is t an appropriate return type in an overrider for a
3085 * method that returns s?
3086 */
3087 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3088 return
3089 isSameType(t, s) ||
3090 source.allowCovariantReturns() &&
3091 !t.isPrimitive() &&
3092 !s.isPrimitive() &&
3093 isAssignable(t, s, warner);
3094 }
3095 // </editor-fold>
3097 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3098 /**
3099 * Return the class that boxes the given primitive.
3100 */
3101 public ClassSymbol boxedClass(Type t) {
3102 return reader.enterClass(syms.boxedName[t.tag]);
3103 }
3105 /**
3106 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3107 */
3108 public Type boxedTypeOrType(Type t) {
3109 return t.isPrimitive() ?
3110 boxedClass(t).type :
3111 t;
3112 }
3114 /**
3115 * Return the primitive type corresponding to a boxed type.
3116 */
3117 public Type unboxedType(Type t) {
3118 if (allowBoxing) {
3119 for (int i=0; i<syms.boxedName.length; i++) {
3120 Name box = syms.boxedName[i];
3121 if (box != null &&
3122 asSuper(t, reader.enterClass(box)) != null)
3123 return syms.typeOfTag[i];
3124 }
3125 }
3126 return Type.noType;
3127 }
3128 // </editor-fold>
3130 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3131 /*
3132 * JLS 5.1.10 Capture Conversion:
3133 *
3134 * Let G name a generic type declaration with n formal type
3135 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3136 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3137 * where, for 1 <= i <= n:
3138 *
3139 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3140 * Si is a fresh type variable whose upper bound is
3141 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3142 * type.
3143 *
3144 * + If Ti is a wildcard type argument of the form ? extends Bi,
3145 * then Si is a fresh type variable whose upper bound is
3146 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3147 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3148 * a compile-time error if for any two classes (not interfaces)
3149 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3150 *
3151 * + If Ti is a wildcard type argument of the form ? super Bi,
3152 * then Si is a fresh type variable whose upper bound is
3153 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3154 *
3155 * + Otherwise, Si = Ti.
3156 *
3157 * Capture conversion on any type other than a parameterized type
3158 * (4.5) acts as an identity conversion (5.1.1). Capture
3159 * conversions never require a special action at run time and
3160 * therefore never throw an exception at run time.
3161 *
3162 * Capture conversion is not applied recursively.
3163 */
3164 /**
3165 * Capture conversion as specified by the JLS.
3166 */
3168 public List<Type> capture(List<Type> ts) {
3169 List<Type> buf = List.nil();
3170 for (Type t : ts) {
3171 buf = buf.prepend(capture(t));
3172 }
3173 return buf.reverse();
3174 }
3175 public Type capture(Type t) {
3176 if (t.tag != CLASS)
3177 return t;
3178 if (t.getEnclosingType() != Type.noType) {
3179 Type capturedEncl = capture(t.getEnclosingType());
3180 if (capturedEncl != t.getEnclosingType()) {
3181 Type type1 = memberType(capturedEncl, t.tsym);
3182 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3183 }
3184 }
3185 ClassType cls = (ClassType)t;
3186 if (cls.isRaw() || !cls.isParameterized())
3187 return cls;
3189 ClassType G = (ClassType)cls.asElement().asType();
3190 List<Type> A = G.getTypeArguments();
3191 List<Type> T = cls.getTypeArguments();
3192 List<Type> S = freshTypeVariables(T);
3194 List<Type> currentA = A;
3195 List<Type> currentT = T;
3196 List<Type> currentS = S;
3197 boolean captured = false;
3198 while (!currentA.isEmpty() &&
3199 !currentT.isEmpty() &&
3200 !currentS.isEmpty()) {
3201 if (currentS.head != currentT.head) {
3202 captured = true;
3203 WildcardType Ti = (WildcardType)currentT.head;
3204 Type Ui = currentA.head.getUpperBound();
3205 CapturedType Si = (CapturedType)currentS.head;
3206 if (Ui == null)
3207 Ui = syms.objectType;
3208 switch (Ti.kind) {
3209 case UNBOUND:
3210 Si.bound = subst(Ui, A, S);
3211 Si.lower = syms.botType;
3212 break;
3213 case EXTENDS:
3214 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3215 Si.lower = syms.botType;
3216 break;
3217 case SUPER:
3218 Si.bound = subst(Ui, A, S);
3219 Si.lower = Ti.getSuperBound();
3220 break;
3221 }
3222 if (Si.bound == Si.lower)
3223 currentS.head = Si.bound;
3224 }
3225 currentA = currentA.tail;
3226 currentT = currentT.tail;
3227 currentS = currentS.tail;
3228 }
3229 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3230 return erasure(t); // some "rare" type involved
3232 if (captured)
3233 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3234 else
3235 return t;
3236 }
3237 // where
3238 public List<Type> freshTypeVariables(List<Type> types) {
3239 ListBuffer<Type> result = lb();
3240 for (Type t : types) {
3241 if (t.tag == WILDCARD) {
3242 Type bound = ((WildcardType)t).getExtendsBound();
3243 if (bound == null)
3244 bound = syms.objectType;
3245 result.append(new CapturedType(capturedName,
3246 syms.noSymbol,
3247 bound,
3248 syms.botType,
3249 (WildcardType)t));
3250 } else {
3251 result.append(t);
3252 }
3253 }
3254 return result.toList();
3255 }
3256 // </editor-fold>
3258 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3259 private List<Type> upperBounds(List<Type> ss) {
3260 if (ss.isEmpty()) return ss;
3261 Type head = upperBound(ss.head);
3262 List<Type> tail = upperBounds(ss.tail);
3263 if (head != ss.head || tail != ss.tail)
3264 return tail.prepend(head);
3265 else
3266 return ss;
3267 }
3269 private boolean sideCast(Type from, Type to, Warner warn) {
3270 // We are casting from type $from$ to type $to$, which are
3271 // non-final unrelated types. This method
3272 // tries to reject a cast by transferring type parameters
3273 // from $to$ to $from$ by common superinterfaces.
3274 boolean reverse = false;
3275 Type target = to;
3276 if ((to.tsym.flags() & INTERFACE) == 0) {
3277 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3278 reverse = true;
3279 to = from;
3280 from = target;
3281 }
3282 List<Type> commonSupers = superClosure(to, erasure(from));
3283 boolean giveWarning = commonSupers.isEmpty();
3284 // The arguments to the supers could be unified here to
3285 // get a more accurate analysis
3286 while (commonSupers.nonEmpty()) {
3287 Type t1 = asSuper(from, commonSupers.head.tsym);
3288 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3289 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3290 return false;
3291 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3292 commonSupers = commonSupers.tail;
3293 }
3294 if (giveWarning && !isReifiable(reverse ? from : to))
3295 warn.warn(LintCategory.UNCHECKED);
3296 if (!source.allowCovariantReturns())
3297 // reject if there is a common method signature with
3298 // incompatible return types.
3299 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3300 return true;
3301 }
3303 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3304 // We are casting from type $from$ to type $to$, which are
3305 // unrelated types one of which is final and the other of
3306 // which is an interface. This method
3307 // tries to reject a cast by transferring type parameters
3308 // from the final class to the interface.
3309 boolean reverse = false;
3310 Type target = to;
3311 if ((to.tsym.flags() & INTERFACE) == 0) {
3312 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3313 reverse = true;
3314 to = from;
3315 from = target;
3316 }
3317 Assert.check((from.tsym.flags() & FINAL) != 0);
3318 Type t1 = asSuper(from, to.tsym);
3319 if (t1 == null) return false;
3320 Type t2 = to;
3321 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3322 return false;
3323 if (!source.allowCovariantReturns())
3324 // reject if there is a common method signature with
3325 // incompatible return types.
3326 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3327 if (!isReifiable(target) &&
3328 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3329 warn.warn(LintCategory.UNCHECKED);
3330 return true;
3331 }
3333 private boolean giveWarning(Type from, Type to) {
3334 Type subFrom = asSub(from, to.tsym);
3335 return to.isParameterized() &&
3336 (!(isUnbounded(to) ||
3337 isSubtype(from, to) ||
3338 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3339 }
3341 private List<Type> superClosure(Type t, Type s) {
3342 List<Type> cl = List.nil();
3343 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3344 if (isSubtype(s, erasure(l.head))) {
3345 cl = insert(cl, l.head);
3346 } else {
3347 cl = union(cl, superClosure(l.head, s));
3348 }
3349 }
3350 return cl;
3351 }
3353 private boolean containsTypeEquivalent(Type t, Type s) {
3354 return
3355 isSameType(t, s) || // shortcut
3356 containsType(t, s) && containsType(s, t);
3357 }
3359 // <editor-fold defaultstate="collapsed" desc="adapt">
3360 /**
3361 * Adapt a type by computing a substitution which maps a source
3362 * type to a target type.
3363 *
3364 * @param source the source type
3365 * @param target the target type
3366 * @param from the type variables of the computed substitution
3367 * @param to the types of the computed substitution.
3368 */
3369 public void adapt(Type source,
3370 Type target,
3371 ListBuffer<Type> from,
3372 ListBuffer<Type> to) throws AdaptFailure {
3373 new Adapter(from, to).adapt(source, target);
3374 }
3376 class Adapter extends SimpleVisitor<Void, Type> {
3378 ListBuffer<Type> from;
3379 ListBuffer<Type> to;
3380 Map<Symbol,Type> mapping;
3382 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3383 this.from = from;
3384 this.to = to;
3385 mapping = new HashMap<Symbol,Type>();
3386 }
3388 public void adapt(Type source, Type target) throws AdaptFailure {
3389 visit(source, target);
3390 List<Type> fromList = from.toList();
3391 List<Type> toList = to.toList();
3392 while (!fromList.isEmpty()) {
3393 Type val = mapping.get(fromList.head.tsym);
3394 if (toList.head != val)
3395 toList.head = val;
3396 fromList = fromList.tail;
3397 toList = toList.tail;
3398 }
3399 }
3401 @Override
3402 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3403 if (target.tag == CLASS)
3404 adaptRecursive(source.allparams(), target.allparams());
3405 return null;
3406 }
3408 @Override
3409 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3410 if (target.tag == ARRAY)
3411 adaptRecursive(elemtype(source), elemtype(target));
3412 return null;
3413 }
3415 @Override
3416 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3417 if (source.isExtendsBound())
3418 adaptRecursive(upperBound(source), upperBound(target));
3419 else if (source.isSuperBound())
3420 adaptRecursive(lowerBound(source), lowerBound(target));
3421 return null;
3422 }
3424 @Override
3425 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3426 // Check to see if there is
3427 // already a mapping for $source$, in which case
3428 // the old mapping will be merged with the new
3429 Type val = mapping.get(source.tsym);
3430 if (val != null) {
3431 if (val.isSuperBound() && target.isSuperBound()) {
3432 val = isSubtype(lowerBound(val), lowerBound(target))
3433 ? target : val;
3434 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3435 val = isSubtype(upperBound(val), upperBound(target))
3436 ? val : target;
3437 } else if (!isSameType(val, target)) {
3438 throw new AdaptFailure();
3439 }
3440 } else {
3441 val = target;
3442 from.append(source);
3443 to.append(target);
3444 }
3445 mapping.put(source.tsym, val);
3446 return null;
3447 }
3449 @Override
3450 public Void visitType(Type source, Type target) {
3451 return null;
3452 }
3454 private Set<TypePair> cache = new HashSet<TypePair>();
3456 private void adaptRecursive(Type source, Type target) {
3457 TypePair pair = new TypePair(source, target);
3458 if (cache.add(pair)) {
3459 try {
3460 visit(source, target);
3461 } finally {
3462 cache.remove(pair);
3463 }
3464 }
3465 }
3467 private void adaptRecursive(List<Type> source, List<Type> target) {
3468 if (source.length() == target.length()) {
3469 while (source.nonEmpty()) {
3470 adaptRecursive(source.head, target.head);
3471 source = source.tail;
3472 target = target.tail;
3473 }
3474 }
3475 }
3476 }
3478 public static class AdaptFailure extends RuntimeException {
3479 static final long serialVersionUID = -7490231548272701566L;
3480 }
3482 private void adaptSelf(Type t,
3483 ListBuffer<Type> from,
3484 ListBuffer<Type> to) {
3485 try {
3486 //if (t.tsym.type != t)
3487 adapt(t.tsym.type, t, from, to);
3488 } catch (AdaptFailure ex) {
3489 // Adapt should never fail calculating a mapping from
3490 // t.tsym.type to t as there can be no merge problem.
3491 throw new AssertionError(ex);
3492 }
3493 }
3494 // </editor-fold>
3496 /**
3497 * Rewrite all type variables (universal quantifiers) in the given
3498 * type to wildcards (existential quantifiers). This is used to
3499 * determine if a cast is allowed. For example, if high is true
3500 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3501 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3502 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3503 * List<Integer>} with a warning.
3504 * @param t a type
3505 * @param high if true return an upper bound; otherwise a lower
3506 * bound
3507 * @param rewriteTypeVars only rewrite captured wildcards if false;
3508 * otherwise rewrite all type variables
3509 * @return the type rewritten with wildcards (existential
3510 * quantifiers) only
3511 */
3512 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3513 return new Rewriter(high, rewriteTypeVars).visit(t);
3514 }
3516 class Rewriter extends UnaryVisitor<Type> {
3518 boolean high;
3519 boolean rewriteTypeVars;
3521 Rewriter(boolean high, boolean rewriteTypeVars) {
3522 this.high = high;
3523 this.rewriteTypeVars = rewriteTypeVars;
3524 }
3526 @Override
3527 public Type visitClassType(ClassType t, Void s) {
3528 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3529 boolean changed = false;
3530 for (Type arg : t.allparams()) {
3531 Type bound = visit(arg);
3532 if (arg != bound) {
3533 changed = true;
3534 }
3535 rewritten.append(bound);
3536 }
3537 if (changed)
3538 return subst(t.tsym.type,
3539 t.tsym.type.allparams(),
3540 rewritten.toList());
3541 else
3542 return t;
3543 }
3545 public Type visitType(Type t, Void s) {
3546 return high ? upperBound(t) : lowerBound(t);
3547 }
3549 @Override
3550 public Type visitCapturedType(CapturedType t, Void s) {
3551 Type bound = visitWildcardType(t.wildcard, null);
3552 return (bound.contains(t)) ?
3553 erasure(bound) :
3554 bound;
3555 }
3557 @Override
3558 public Type visitTypeVar(TypeVar t, Void s) {
3559 if (rewriteTypeVars) {
3560 Type bound = high ?
3561 (t.bound.contains(t) ?
3562 erasure(t.bound) :
3563 visit(t.bound)) :
3564 syms.botType;
3565 return rewriteAsWildcardType(bound, t);
3566 }
3567 else
3568 return t;
3569 }
3571 @Override
3572 public Type visitWildcardType(WildcardType t, Void s) {
3573 Type bound = high ? t.getExtendsBound() :
3574 t.getSuperBound();
3575 if (bound == null)
3576 bound = high ? syms.objectType : syms.botType;
3577 return rewriteAsWildcardType(visit(bound), t.bound);
3578 }
3580 private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
3581 return high ?
3582 makeExtendsWildcard(B(bound), formal) :
3583 makeSuperWildcard(B(bound), formal);
3584 }
3586 Type B(Type t) {
3587 while (t.tag == WILDCARD) {
3588 WildcardType w = (WildcardType)t;
3589 t = high ?
3590 w.getExtendsBound() :
3591 w.getSuperBound();
3592 if (t == null) {
3593 t = high ? syms.objectType : syms.botType;
3594 }
3595 }
3596 return t;
3597 }
3598 }
3601 /**
3602 * Create a wildcard with the given upper (extends) bound; create
3603 * an unbounded wildcard if bound is Object.
3604 *
3605 * @param bound the upper bound
3606 * @param formal the formal type parameter that will be
3607 * substituted by the wildcard
3608 */
3609 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3610 if (bound == syms.objectType) {
3611 return new WildcardType(syms.objectType,
3612 BoundKind.UNBOUND,
3613 syms.boundClass,
3614 formal);
3615 } else {
3616 return new WildcardType(bound,
3617 BoundKind.EXTENDS,
3618 syms.boundClass,
3619 formal);
3620 }
3621 }
3623 /**
3624 * Create a wildcard with the given lower (super) bound; create an
3625 * unbounded wildcard if bound is bottom (type of {@code null}).
3626 *
3627 * @param bound the lower bound
3628 * @param formal the formal type parameter that will be
3629 * substituted by the wildcard
3630 */
3631 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3632 if (bound.tag == BOT) {
3633 return new WildcardType(syms.objectType,
3634 BoundKind.UNBOUND,
3635 syms.boundClass,
3636 formal);
3637 } else {
3638 return new WildcardType(bound,
3639 BoundKind.SUPER,
3640 syms.boundClass,
3641 formal);
3642 }
3643 }
3645 /**
3646 * A wrapper for a type that allows use in sets.
3647 */
3648 class SingletonType {
3649 final Type t;
3650 SingletonType(Type t) {
3651 this.t = t;
3652 }
3653 public int hashCode() {
3654 return Types.hashCode(t);
3655 }
3656 public boolean equals(Object obj) {
3657 return (obj instanceof SingletonType) &&
3658 isSameType(t, ((SingletonType)obj).t);
3659 }
3660 public String toString() {
3661 return t.toString();
3662 }
3663 }
3664 // </editor-fold>
3666 // <editor-fold defaultstate="collapsed" desc="Visitors">
3667 /**
3668 * A default visitor for types. All visitor methods except
3669 * visitType are implemented by delegating to visitType. Concrete
3670 * subclasses must provide an implementation of visitType and can
3671 * override other methods as needed.
3672 *
3673 * @param <R> the return type of the operation implemented by this
3674 * visitor; use Void if no return type is needed.
3675 * @param <S> the type of the second argument (the first being the
3676 * type itself) of the operation implemented by this visitor; use
3677 * Void if a second argument is not needed.
3678 */
3679 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3680 final public R visit(Type t, S s) { return t.accept(this, s); }
3681 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3682 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3683 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3684 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3685 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3686 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3687 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3688 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3689 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3690 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3691 }
3693 /**
3694 * A default visitor for symbols. All visitor methods except
3695 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3696 * subclasses must provide an implementation of visitSymbol and can
3697 * override other methods as needed.
3698 *
3699 * @param <R> the return type of the operation implemented by this
3700 * visitor; use Void if no return type is needed.
3701 * @param <S> the type of the second argument (the first being the
3702 * symbol itself) of the operation implemented by this visitor; use
3703 * Void if a second argument is not needed.
3704 */
3705 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3706 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3707 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3708 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3709 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3710 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3711 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3712 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3713 }
3715 /**
3716 * A <em>simple</em> visitor for types. This visitor is simple as
3717 * captured wildcards, for-all types (generic methods), and
3718 * undetermined type variables (part of inference) are hidden.
3719 * Captured wildcards are hidden by treating them as type
3720 * variables and the rest are hidden by visiting their qtypes.
3721 *
3722 * @param <R> the return type of the operation implemented by this
3723 * visitor; use Void if no return type is needed.
3724 * @param <S> the type of the second argument (the first being the
3725 * type itself) of the operation implemented by this visitor; use
3726 * Void if a second argument is not needed.
3727 */
3728 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3729 @Override
3730 public R visitCapturedType(CapturedType t, S s) {
3731 return visitTypeVar(t, s);
3732 }
3733 @Override
3734 public R visitForAll(ForAll t, S s) {
3735 return visit(t.qtype, s);
3736 }
3737 @Override
3738 public R visitUndetVar(UndetVar t, S s) {
3739 return visit(t.qtype, s);
3740 }
3741 }
3743 /**
3744 * A plain relation on types. That is a 2-ary function on the
3745 * form Type × Type → Boolean.
3746 * <!-- In plain text: Type x Type -> Boolean -->
3747 */
3748 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3750 /**
3751 * A convenience visitor for implementing operations that only
3752 * require one argument (the type itself), that is, unary
3753 * operations.
3754 *
3755 * @param <R> the return type of the operation implemented by this
3756 * visitor; use Void if no return type is needed.
3757 */
3758 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3759 final public R visit(Type t) { return t.accept(this, null); }
3760 }
3762 /**
3763 * A visitor for implementing a mapping from types to types. The
3764 * default behavior of this class is to implement the identity
3765 * mapping (mapping a type to itself). This can be overridden in
3766 * subclasses.
3767 *
3768 * @param <S> the type of the second argument (the first being the
3769 * type itself) of this mapping; use Void if a second argument is
3770 * not needed.
3771 */
3772 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3773 final public Type visit(Type t) { return t.accept(this, null); }
3774 public Type visitType(Type t, S s) { return t; }
3775 }
3776 // </editor-fold>
3779 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3781 public RetentionPolicy getRetention(Attribute.Compound a) {
3782 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3783 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3784 if (c != null) {
3785 Attribute value = c.member(names.value);
3786 if (value != null && value instanceof Attribute.Enum) {
3787 Name levelName = ((Attribute.Enum)value).value.name;
3788 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3789 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3790 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3791 else ;// /* fail soft */ throw new AssertionError(levelName);
3792 }
3793 }
3794 return vis;
3795 }
3796 // </editor-fold>
3797 }