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