Mon, 10 Jan 2011 15:08:31 -0800
6396503: javac should not require assertions enabled
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.code;
28 import java.lang.ref.SoftReference;
29 import java.util.*;
31 import com.sun.tools.javac.util.*;
32 import com.sun.tools.javac.util.List;
34 import com.sun.tools.javac.jvm.ClassReader;
35 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
36 import com.sun.tools.javac.code.Lint.LintCategory;
37 import com.sun.tools.javac.comp.Check;
39 import static com.sun.tools.javac.code.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 List<Type> tvars1 = substBounds(t.tvars, from, to);
2263 Type qtype1 = subst(t.qtype);
2264 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2265 return t;
2266 } else if (tvars1 == t.tvars) {
2267 return new ForAll(tvars1, qtype1);
2268 } else {
2269 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2270 }
2271 }
2273 @Override
2274 public Type visitErrorType(ErrorType t, Void ignored) {
2275 return t;
2276 }
2277 }
2279 public List<Type> substBounds(List<Type> tvars,
2280 List<Type> from,
2281 List<Type> to) {
2282 if (tvars.isEmpty())
2283 return tvars;
2284 ListBuffer<Type> newBoundsBuf = lb();
2285 boolean changed = false;
2286 // calculate new bounds
2287 for (Type t : tvars) {
2288 TypeVar tv = (TypeVar) t;
2289 Type bound = subst(tv.bound, from, to);
2290 if (bound != tv.bound)
2291 changed = true;
2292 newBoundsBuf.append(bound);
2293 }
2294 if (!changed)
2295 return tvars;
2296 ListBuffer<Type> newTvars = lb();
2297 // create new type variables without bounds
2298 for (Type t : tvars) {
2299 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2300 }
2301 // the new bounds should use the new type variables in place
2302 // of the old
2303 List<Type> newBounds = newBoundsBuf.toList();
2304 from = tvars;
2305 to = newTvars.toList();
2306 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2307 newBounds.head = subst(newBounds.head, from, to);
2308 }
2309 newBounds = newBoundsBuf.toList();
2310 // set the bounds of new type variables to the new bounds
2311 for (Type t : newTvars.toList()) {
2312 TypeVar tv = (TypeVar) t;
2313 tv.bound = newBounds.head;
2314 newBounds = newBounds.tail;
2315 }
2316 return newTvars.toList();
2317 }
2319 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2320 Type bound1 = subst(t.bound, from, to);
2321 if (bound1 == t.bound)
2322 return t;
2323 else {
2324 // create new type variable without bounds
2325 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2326 // the new bound should use the new type variable in place
2327 // of the old
2328 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2329 return tv;
2330 }
2331 }
2332 // </editor-fold>
2334 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2335 /**
2336 * Does t have the same bounds for quantified variables as s?
2337 */
2338 boolean hasSameBounds(ForAll t, ForAll s) {
2339 List<Type> l1 = t.tvars;
2340 List<Type> l2 = s.tvars;
2341 while (l1.nonEmpty() && l2.nonEmpty() &&
2342 isSameType(l1.head.getUpperBound(),
2343 subst(l2.head.getUpperBound(),
2344 s.tvars,
2345 t.tvars))) {
2346 l1 = l1.tail;
2347 l2 = l2.tail;
2348 }
2349 return l1.isEmpty() && l2.isEmpty();
2350 }
2351 // </editor-fold>
2353 // <editor-fold defaultstate="collapsed" desc="newInstances">
2354 /** Create new vector of type variables from list of variables
2355 * changing all recursive bounds from old to new list.
2356 */
2357 public List<Type> newInstances(List<Type> tvars) {
2358 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2359 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2360 TypeVar tv = (TypeVar) l.head;
2361 tv.bound = subst(tv.bound, tvars, tvars1);
2362 }
2363 return tvars1;
2364 }
2365 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2366 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2367 };
2368 // </editor-fold>
2370 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2371 public Type createErrorType(Type originalType) {
2372 return new ErrorType(originalType, syms.errSymbol);
2373 }
2375 public Type createErrorType(ClassSymbol c, Type originalType) {
2376 return new ErrorType(c, originalType);
2377 }
2379 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2380 return new ErrorType(name, container, originalType);
2381 }
2382 // </editor-fold>
2384 // <editor-fold defaultstate="collapsed" desc="rank">
2385 /**
2386 * The rank of a class is the length of the longest path between
2387 * the class and java.lang.Object in the class inheritance
2388 * graph. Undefined for all but reference types.
2389 */
2390 public int rank(Type t) {
2391 switch(t.tag) {
2392 case CLASS: {
2393 ClassType cls = (ClassType)t;
2394 if (cls.rank_field < 0) {
2395 Name fullname = cls.tsym.getQualifiedName();
2396 if (fullname == names.java_lang_Object)
2397 cls.rank_field = 0;
2398 else {
2399 int r = rank(supertype(cls));
2400 for (List<Type> l = interfaces(cls);
2401 l.nonEmpty();
2402 l = l.tail) {
2403 if (rank(l.head) > r)
2404 r = rank(l.head);
2405 }
2406 cls.rank_field = r + 1;
2407 }
2408 }
2409 return cls.rank_field;
2410 }
2411 case TYPEVAR: {
2412 TypeVar tvar = (TypeVar)t;
2413 if (tvar.rank_field < 0) {
2414 int r = rank(supertype(tvar));
2415 for (List<Type> l = interfaces(tvar);
2416 l.nonEmpty();
2417 l = l.tail) {
2418 if (rank(l.head) > r) r = rank(l.head);
2419 }
2420 tvar.rank_field = r + 1;
2421 }
2422 return tvar.rank_field;
2423 }
2424 case ERROR:
2425 return 0;
2426 default:
2427 throw new AssertionError();
2428 }
2429 }
2430 // </editor-fold>
2432 /**
2433 * Helper method for generating a string representation of a given type
2434 * accordingly to a given locale
2435 */
2436 public String toString(Type t, Locale locale) {
2437 return Printer.createStandardPrinter(messages).visit(t, locale);
2438 }
2440 /**
2441 * Helper method for generating a string representation of a given type
2442 * accordingly to a given locale
2443 */
2444 public String toString(Symbol t, Locale locale) {
2445 return Printer.createStandardPrinter(messages).visit(t, locale);
2446 }
2448 // <editor-fold defaultstate="collapsed" desc="toString">
2449 /**
2450 * This toString is slightly more descriptive than the one on Type.
2451 *
2452 * @deprecated Types.toString(Type t, Locale l) provides better support
2453 * for localization
2454 */
2455 @Deprecated
2456 public String toString(Type t) {
2457 if (t.tag == FORALL) {
2458 ForAll forAll = (ForAll)t;
2459 return typaramsString(forAll.tvars) + forAll.qtype;
2460 }
2461 return "" + t;
2462 }
2463 // where
2464 private String typaramsString(List<Type> tvars) {
2465 StringBuffer s = new StringBuffer();
2466 s.append('<');
2467 boolean first = true;
2468 for (Type t : tvars) {
2469 if (!first) s.append(", ");
2470 first = false;
2471 appendTyparamString(((TypeVar)t), s);
2472 }
2473 s.append('>');
2474 return s.toString();
2475 }
2476 private void appendTyparamString(TypeVar t, StringBuffer buf) {
2477 buf.append(t);
2478 if (t.bound == null ||
2479 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2480 return;
2481 buf.append(" extends "); // Java syntax; no need for i18n
2482 Type bound = t.bound;
2483 if (!bound.isCompound()) {
2484 buf.append(bound);
2485 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2486 buf.append(supertype(t));
2487 for (Type intf : interfaces(t)) {
2488 buf.append('&');
2489 buf.append(intf);
2490 }
2491 } else {
2492 // No superclass was given in bounds.
2493 // In this case, supertype is Object, erasure is first interface.
2494 boolean first = true;
2495 for (Type intf : interfaces(t)) {
2496 if (!first) buf.append('&');
2497 first = false;
2498 buf.append(intf);
2499 }
2500 }
2501 }
2502 // </editor-fold>
2504 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2505 /**
2506 * A cache for closures.
2507 *
2508 * <p>A closure is a list of all the supertypes and interfaces of
2509 * a class or interface type, ordered by ClassSymbol.precedes
2510 * (that is, subclasses come first, arbitrary but fixed
2511 * otherwise).
2512 */
2513 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2515 /**
2516 * Returns the closure of a class or interface type.
2517 */
2518 public List<Type> closure(Type t) {
2519 List<Type> cl = closureCache.get(t);
2520 if (cl == null) {
2521 Type st = supertype(t);
2522 if (!t.isCompound()) {
2523 if (st.tag == CLASS) {
2524 cl = insert(closure(st), t);
2525 } else if (st.tag == TYPEVAR) {
2526 cl = closure(st).prepend(t);
2527 } else {
2528 cl = List.of(t);
2529 }
2530 } else {
2531 cl = closure(supertype(t));
2532 }
2533 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2534 cl = union(cl, closure(l.head));
2535 closureCache.put(t, cl);
2536 }
2537 return cl;
2538 }
2540 /**
2541 * Insert a type in a closure
2542 */
2543 public List<Type> insert(List<Type> cl, Type t) {
2544 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2545 return cl.prepend(t);
2546 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2547 return insert(cl.tail, t).prepend(cl.head);
2548 } else {
2549 return cl;
2550 }
2551 }
2553 /**
2554 * Form the union of two closures
2555 */
2556 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2557 if (cl1.isEmpty()) {
2558 return cl2;
2559 } else if (cl2.isEmpty()) {
2560 return cl1;
2561 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2562 return union(cl1.tail, cl2).prepend(cl1.head);
2563 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2564 return union(cl1, cl2.tail).prepend(cl2.head);
2565 } else {
2566 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2567 }
2568 }
2570 /**
2571 * Intersect two closures
2572 */
2573 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2574 if (cl1 == cl2)
2575 return cl1;
2576 if (cl1.isEmpty() || cl2.isEmpty())
2577 return List.nil();
2578 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2579 return intersect(cl1.tail, cl2);
2580 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2581 return intersect(cl1, cl2.tail);
2582 if (isSameType(cl1.head, cl2.head))
2583 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2584 if (cl1.head.tsym == cl2.head.tsym &&
2585 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2586 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2587 Type merge = merge(cl1.head,cl2.head);
2588 return intersect(cl1.tail, cl2.tail).prepend(merge);
2589 }
2590 if (cl1.head.isRaw() || cl2.head.isRaw())
2591 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2592 }
2593 return intersect(cl1.tail, cl2.tail);
2594 }
2595 // where
2596 class TypePair {
2597 final Type t1;
2598 final Type t2;
2599 TypePair(Type t1, Type t2) {
2600 this.t1 = t1;
2601 this.t2 = t2;
2602 }
2603 @Override
2604 public int hashCode() {
2605 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2606 }
2607 @Override
2608 public boolean equals(Object obj) {
2609 if (!(obj instanceof TypePair))
2610 return false;
2611 TypePair typePair = (TypePair)obj;
2612 return isSameType(t1, typePair.t1)
2613 && isSameType(t2, typePair.t2);
2614 }
2615 }
2616 Set<TypePair> mergeCache = new HashSet<TypePair>();
2617 private Type merge(Type c1, Type c2) {
2618 ClassType class1 = (ClassType) c1;
2619 List<Type> act1 = class1.getTypeArguments();
2620 ClassType class2 = (ClassType) c2;
2621 List<Type> act2 = class2.getTypeArguments();
2622 ListBuffer<Type> merged = new ListBuffer<Type>();
2623 List<Type> typarams = class1.tsym.type.getTypeArguments();
2625 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2626 if (containsType(act1.head, act2.head)) {
2627 merged.append(act1.head);
2628 } else if (containsType(act2.head, act1.head)) {
2629 merged.append(act2.head);
2630 } else {
2631 TypePair pair = new TypePair(c1, c2);
2632 Type m;
2633 if (mergeCache.add(pair)) {
2634 m = new WildcardType(lub(upperBound(act1.head),
2635 upperBound(act2.head)),
2636 BoundKind.EXTENDS,
2637 syms.boundClass);
2638 mergeCache.remove(pair);
2639 } else {
2640 m = new WildcardType(syms.objectType,
2641 BoundKind.UNBOUND,
2642 syms.boundClass);
2643 }
2644 merged.append(m.withTypeVar(typarams.head));
2645 }
2646 act1 = act1.tail;
2647 act2 = act2.tail;
2648 typarams = typarams.tail;
2649 }
2650 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2651 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2652 }
2654 /**
2655 * Return the minimum type of a closure, a compound type if no
2656 * unique minimum exists.
2657 */
2658 private Type compoundMin(List<Type> cl) {
2659 if (cl.isEmpty()) return syms.objectType;
2660 List<Type> compound = closureMin(cl);
2661 if (compound.isEmpty())
2662 return null;
2663 else if (compound.tail.isEmpty())
2664 return compound.head;
2665 else
2666 return makeCompoundType(compound);
2667 }
2669 /**
2670 * Return the minimum types of a closure, suitable for computing
2671 * compoundMin or glb.
2672 */
2673 private List<Type> closureMin(List<Type> cl) {
2674 ListBuffer<Type> classes = lb();
2675 ListBuffer<Type> interfaces = lb();
2676 while (!cl.isEmpty()) {
2677 Type current = cl.head;
2678 if (current.isInterface())
2679 interfaces.append(current);
2680 else
2681 classes.append(current);
2682 ListBuffer<Type> candidates = lb();
2683 for (Type t : cl.tail) {
2684 if (!isSubtypeNoCapture(current, t))
2685 candidates.append(t);
2686 }
2687 cl = candidates.toList();
2688 }
2689 return classes.appendList(interfaces).toList();
2690 }
2692 /**
2693 * Return the least upper bound of pair of types. if the lub does
2694 * not exist return null.
2695 */
2696 public Type lub(Type t1, Type t2) {
2697 return lub(List.of(t1, t2));
2698 }
2700 /**
2701 * Return the least upper bound (lub) of set of types. If the lub
2702 * does not exist return the type of null (bottom).
2703 */
2704 public Type lub(List<Type> ts) {
2705 final int ARRAY_BOUND = 1;
2706 final int CLASS_BOUND = 2;
2707 int boundkind = 0;
2708 for (Type t : ts) {
2709 switch (t.tag) {
2710 case CLASS:
2711 boundkind |= CLASS_BOUND;
2712 break;
2713 case ARRAY:
2714 boundkind |= ARRAY_BOUND;
2715 break;
2716 case TYPEVAR:
2717 do {
2718 t = t.getUpperBound();
2719 } while (t.tag == TYPEVAR);
2720 if (t.tag == ARRAY) {
2721 boundkind |= ARRAY_BOUND;
2722 } else {
2723 boundkind |= CLASS_BOUND;
2724 }
2725 break;
2726 default:
2727 if (t.isPrimitive())
2728 return syms.errType;
2729 }
2730 }
2731 switch (boundkind) {
2732 case 0:
2733 return syms.botType;
2735 case ARRAY_BOUND:
2736 // calculate lub(A[], B[])
2737 List<Type> elements = Type.map(ts, elemTypeFun);
2738 for (Type t : elements) {
2739 if (t.isPrimitive()) {
2740 // if a primitive type is found, then return
2741 // arraySuperType unless all the types are the
2742 // same
2743 Type first = ts.head;
2744 for (Type s : ts.tail) {
2745 if (!isSameType(first, s)) {
2746 // lub(int[], B[]) is Cloneable & Serializable
2747 return arraySuperType();
2748 }
2749 }
2750 // all the array types are the same, return one
2751 // lub(int[], int[]) is int[]
2752 return first;
2753 }
2754 }
2755 // lub(A[], B[]) is lub(A, B)[]
2756 return new ArrayType(lub(elements), syms.arrayClass);
2758 case CLASS_BOUND:
2759 // calculate lub(A, B)
2760 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2761 ts = ts.tail;
2762 Assert.check(!ts.isEmpty());
2763 List<Type> cl = closure(ts.head);
2764 for (Type t : ts.tail) {
2765 if (t.tag == CLASS || t.tag == TYPEVAR)
2766 cl = intersect(cl, closure(t));
2767 }
2768 return compoundMin(cl);
2770 default:
2771 // calculate lub(A, B[])
2772 List<Type> classes = List.of(arraySuperType());
2773 for (Type t : ts) {
2774 if (t.tag != ARRAY) // Filter out any arrays
2775 classes = classes.prepend(t);
2776 }
2777 // lub(A, B[]) is lub(A, arraySuperType)
2778 return lub(classes);
2779 }
2780 }
2781 // where
2782 private Type arraySuperType = null;
2783 private Type arraySuperType() {
2784 // initialized lazily to avoid problems during compiler startup
2785 if (arraySuperType == null) {
2786 synchronized (this) {
2787 if (arraySuperType == null) {
2788 // JLS 10.8: all arrays implement Cloneable and Serializable.
2789 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2790 syms.cloneableType),
2791 syms.objectType);
2792 }
2793 }
2794 }
2795 return arraySuperType;
2796 }
2797 // </editor-fold>
2799 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2800 public Type glb(List<Type> ts) {
2801 Type t1 = ts.head;
2802 for (Type t2 : ts.tail) {
2803 if (t1.isErroneous())
2804 return t1;
2805 t1 = glb(t1, t2);
2806 }
2807 return t1;
2808 }
2809 //where
2810 public Type glb(Type t, Type s) {
2811 if (s == null)
2812 return t;
2813 else if (t.isPrimitive() || s.isPrimitive())
2814 return syms.errType;
2815 else if (isSubtypeNoCapture(t, s))
2816 return t;
2817 else if (isSubtypeNoCapture(s, t))
2818 return s;
2820 List<Type> closure = union(closure(t), closure(s));
2821 List<Type> bounds = closureMin(closure);
2823 if (bounds.isEmpty()) { // length == 0
2824 return syms.objectType;
2825 } else if (bounds.tail.isEmpty()) { // length == 1
2826 return bounds.head;
2827 } else { // length > 1
2828 int classCount = 0;
2829 for (Type bound : bounds)
2830 if (!bound.isInterface())
2831 classCount++;
2832 if (classCount > 1)
2833 return createErrorType(t);
2834 }
2835 return makeCompoundType(bounds);
2836 }
2837 // </editor-fold>
2839 // <editor-fold defaultstate="collapsed" desc="hashCode">
2840 /**
2841 * Compute a hash code on a type.
2842 */
2843 public static int hashCode(Type t) {
2844 return hashCode.visit(t);
2845 }
2846 // where
2847 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
2849 public Integer visitType(Type t, Void ignored) {
2850 return t.tag;
2851 }
2853 @Override
2854 public Integer visitClassType(ClassType t, Void ignored) {
2855 int result = visit(t.getEnclosingType());
2856 result *= 127;
2857 result += t.tsym.flatName().hashCode();
2858 for (Type s : t.getTypeArguments()) {
2859 result *= 127;
2860 result += visit(s);
2861 }
2862 return result;
2863 }
2865 @Override
2866 public Integer visitWildcardType(WildcardType t, Void ignored) {
2867 int result = t.kind.hashCode();
2868 if (t.type != null) {
2869 result *= 127;
2870 result += visit(t.type);
2871 }
2872 return result;
2873 }
2875 @Override
2876 public Integer visitArrayType(ArrayType t, Void ignored) {
2877 return visit(t.elemtype) + 12;
2878 }
2880 @Override
2881 public Integer visitTypeVar(TypeVar t, Void ignored) {
2882 return System.identityHashCode(t.tsym);
2883 }
2885 @Override
2886 public Integer visitUndetVar(UndetVar t, Void ignored) {
2887 return System.identityHashCode(t);
2888 }
2890 @Override
2891 public Integer visitErrorType(ErrorType t, Void ignored) {
2892 return 0;
2893 }
2894 };
2895 // </editor-fold>
2897 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
2898 /**
2899 * Does t have a result that is a subtype of the result type of s,
2900 * suitable for covariant returns? It is assumed that both types
2901 * are (possibly polymorphic) method types. Monomorphic method
2902 * types are handled in the obvious way. Polymorphic method types
2903 * require renaming all type variables of one to corresponding
2904 * type variables in the other, where correspondence is by
2905 * position in the type parameter list. */
2906 public boolean resultSubtype(Type t, Type s, Warner warner) {
2907 List<Type> tvars = t.getTypeArguments();
2908 List<Type> svars = s.getTypeArguments();
2909 Type tres = t.getReturnType();
2910 Type sres = subst(s.getReturnType(), svars, tvars);
2911 return covariantReturnType(tres, sres, warner);
2912 }
2914 /**
2915 * Return-Type-Substitutable.
2916 * @see <a href="http://java.sun.com/docs/books/jls/">The Java
2917 * Language Specification, Third Ed. (8.4.5)</a>
2918 */
2919 public boolean returnTypeSubstitutable(Type r1, Type r2) {
2920 if (hasSameArgs(r1, r2))
2921 return resultSubtype(r1, r2, Warner.noWarnings);
2922 else
2923 return covariantReturnType(r1.getReturnType(),
2924 erasure(r2.getReturnType()),
2925 Warner.noWarnings);
2926 }
2928 public boolean returnTypeSubstitutable(Type r1,
2929 Type r2, Type r2res,
2930 Warner warner) {
2931 if (isSameType(r1.getReturnType(), r2res))
2932 return true;
2933 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
2934 return false;
2936 if (hasSameArgs(r1, r2))
2937 return covariantReturnType(r1.getReturnType(), r2res, warner);
2938 if (!source.allowCovariantReturns())
2939 return false;
2940 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
2941 return true;
2942 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
2943 return false;
2944 warner.warn(LintCategory.UNCHECKED);
2945 return true;
2946 }
2948 /**
2949 * Is t an appropriate return type in an overrider for a
2950 * method that returns s?
2951 */
2952 public boolean covariantReturnType(Type t, Type s, Warner warner) {
2953 return
2954 isSameType(t, s) ||
2955 source.allowCovariantReturns() &&
2956 !t.isPrimitive() &&
2957 !s.isPrimitive() &&
2958 isAssignable(t, s, warner);
2959 }
2960 // </editor-fold>
2962 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
2963 /**
2964 * Return the class that boxes the given primitive.
2965 */
2966 public ClassSymbol boxedClass(Type t) {
2967 return reader.enterClass(syms.boxedName[t.tag]);
2968 }
2970 /**
2971 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
2972 */
2973 public Type boxedTypeOrType(Type t) {
2974 return t.isPrimitive() ?
2975 boxedClass(t).type :
2976 t;
2977 }
2979 /**
2980 * Return the primitive type corresponding to a boxed type.
2981 */
2982 public Type unboxedType(Type t) {
2983 if (allowBoxing) {
2984 for (int i=0; i<syms.boxedName.length; i++) {
2985 Name box = syms.boxedName[i];
2986 if (box != null &&
2987 asSuper(t, reader.enterClass(box)) != null)
2988 return syms.typeOfTag[i];
2989 }
2990 }
2991 return Type.noType;
2992 }
2993 // </editor-fold>
2995 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
2996 /*
2997 * JLS 3rd Ed. 5.1.10 Capture Conversion:
2998 *
2999 * Let G name a generic type declaration with n formal type
3000 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3001 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3002 * where, for 1 <= i <= n:
3003 *
3004 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3005 * Si is a fresh type variable whose upper bound is
3006 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3007 * type.
3008 *
3009 * + If Ti is a wildcard type argument of the form ? extends Bi,
3010 * then Si is a fresh type variable whose upper bound is
3011 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3012 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3013 * a compile-time error if for any two classes (not interfaces)
3014 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3015 *
3016 * + If Ti is a wildcard type argument of the form ? super Bi,
3017 * then Si is a fresh type variable whose upper bound is
3018 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3019 *
3020 * + Otherwise, Si = Ti.
3021 *
3022 * Capture conversion on any type other than a parameterized type
3023 * (4.5) acts as an identity conversion (5.1.1). Capture
3024 * conversions never require a special action at run time and
3025 * therefore never throw an exception at run time.
3026 *
3027 * Capture conversion is not applied recursively.
3028 */
3029 /**
3030 * Capture conversion as specified by JLS 3rd Ed.
3031 */
3033 public List<Type> capture(List<Type> ts) {
3034 List<Type> buf = List.nil();
3035 for (Type t : ts) {
3036 buf = buf.prepend(capture(t));
3037 }
3038 return buf.reverse();
3039 }
3040 public Type capture(Type t) {
3041 if (t.tag != CLASS)
3042 return t;
3043 if (t.getEnclosingType() != Type.noType) {
3044 Type capturedEncl = capture(t.getEnclosingType());
3045 if (capturedEncl != t.getEnclosingType()) {
3046 Type type1 = memberType(capturedEncl, t.tsym);
3047 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3048 }
3049 }
3050 ClassType cls = (ClassType)t;
3051 if (cls.isRaw() || !cls.isParameterized())
3052 return cls;
3054 ClassType G = (ClassType)cls.asElement().asType();
3055 List<Type> A = G.getTypeArguments();
3056 List<Type> T = cls.getTypeArguments();
3057 List<Type> S = freshTypeVariables(T);
3059 List<Type> currentA = A;
3060 List<Type> currentT = T;
3061 List<Type> currentS = S;
3062 boolean captured = false;
3063 while (!currentA.isEmpty() &&
3064 !currentT.isEmpty() &&
3065 !currentS.isEmpty()) {
3066 if (currentS.head != currentT.head) {
3067 captured = true;
3068 WildcardType Ti = (WildcardType)currentT.head;
3069 Type Ui = currentA.head.getUpperBound();
3070 CapturedType Si = (CapturedType)currentS.head;
3071 if (Ui == null)
3072 Ui = syms.objectType;
3073 switch (Ti.kind) {
3074 case UNBOUND:
3075 Si.bound = subst(Ui, A, S);
3076 Si.lower = syms.botType;
3077 break;
3078 case EXTENDS:
3079 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3080 Si.lower = syms.botType;
3081 break;
3082 case SUPER:
3083 Si.bound = subst(Ui, A, S);
3084 Si.lower = Ti.getSuperBound();
3085 break;
3086 }
3087 if (Si.bound == Si.lower)
3088 currentS.head = Si.bound;
3089 }
3090 currentA = currentA.tail;
3091 currentT = currentT.tail;
3092 currentS = currentS.tail;
3093 }
3094 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3095 return erasure(t); // some "rare" type involved
3097 if (captured)
3098 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3099 else
3100 return t;
3101 }
3102 // where
3103 public List<Type> freshTypeVariables(List<Type> types) {
3104 ListBuffer<Type> result = lb();
3105 for (Type t : types) {
3106 if (t.tag == WILDCARD) {
3107 Type bound = ((WildcardType)t).getExtendsBound();
3108 if (bound == null)
3109 bound = syms.objectType;
3110 result.append(new CapturedType(capturedName,
3111 syms.noSymbol,
3112 bound,
3113 syms.botType,
3114 (WildcardType)t));
3115 } else {
3116 result.append(t);
3117 }
3118 }
3119 return result.toList();
3120 }
3121 // </editor-fold>
3123 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3124 private List<Type> upperBounds(List<Type> ss) {
3125 if (ss.isEmpty()) return ss;
3126 Type head = upperBound(ss.head);
3127 List<Type> tail = upperBounds(ss.tail);
3128 if (head != ss.head || tail != ss.tail)
3129 return tail.prepend(head);
3130 else
3131 return ss;
3132 }
3134 private boolean sideCast(Type from, Type to, Warner warn) {
3135 // We are casting from type $from$ to type $to$, which are
3136 // non-final unrelated types. This method
3137 // tries to reject a cast by transferring type parameters
3138 // from $to$ to $from$ by common superinterfaces.
3139 boolean reverse = false;
3140 Type target = to;
3141 if ((to.tsym.flags() & INTERFACE) == 0) {
3142 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3143 reverse = true;
3144 to = from;
3145 from = target;
3146 }
3147 List<Type> commonSupers = superClosure(to, erasure(from));
3148 boolean giveWarning = commonSupers.isEmpty();
3149 // The arguments to the supers could be unified here to
3150 // get a more accurate analysis
3151 while (commonSupers.nonEmpty()) {
3152 Type t1 = asSuper(from, commonSupers.head.tsym);
3153 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3154 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3155 return false;
3156 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3157 commonSupers = commonSupers.tail;
3158 }
3159 if (giveWarning && !isReifiable(reverse ? from : to))
3160 warn.warn(LintCategory.UNCHECKED);
3161 if (!source.allowCovariantReturns())
3162 // reject if there is a common method signature with
3163 // incompatible return types.
3164 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3165 return true;
3166 }
3168 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3169 // We are casting from type $from$ to type $to$, which are
3170 // unrelated types one of which is final and the other of
3171 // which is an interface. This method
3172 // tries to reject a cast by transferring type parameters
3173 // from the final class to the interface.
3174 boolean reverse = false;
3175 Type target = to;
3176 if ((to.tsym.flags() & INTERFACE) == 0) {
3177 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3178 reverse = true;
3179 to = from;
3180 from = target;
3181 }
3182 Assert.check((from.tsym.flags() & FINAL) != 0);
3183 Type t1 = asSuper(from, to.tsym);
3184 if (t1 == null) return false;
3185 Type t2 = to;
3186 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3187 return false;
3188 if (!source.allowCovariantReturns())
3189 // reject if there is a common method signature with
3190 // incompatible return types.
3191 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3192 if (!isReifiable(target) &&
3193 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3194 warn.warn(LintCategory.UNCHECKED);
3195 return true;
3196 }
3198 private boolean giveWarning(Type from, Type to) {
3199 Type subFrom = asSub(from, to.tsym);
3200 return to.isParameterized() &&
3201 (!(isUnbounded(to) ||
3202 isSubtype(from, to) ||
3203 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3204 }
3206 private List<Type> superClosure(Type t, Type s) {
3207 List<Type> cl = List.nil();
3208 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3209 if (isSubtype(s, erasure(l.head))) {
3210 cl = insert(cl, l.head);
3211 } else {
3212 cl = union(cl, superClosure(l.head, s));
3213 }
3214 }
3215 return cl;
3216 }
3218 private boolean containsTypeEquivalent(Type t, Type s) {
3219 return
3220 isSameType(t, s) || // shortcut
3221 containsType(t, s) && containsType(s, t);
3222 }
3224 // <editor-fold defaultstate="collapsed" desc="adapt">
3225 /**
3226 * Adapt a type by computing a substitution which maps a source
3227 * type to a target type.
3228 *
3229 * @param source the source type
3230 * @param target the target type
3231 * @param from the type variables of the computed substitution
3232 * @param to the types of the computed substitution.
3233 */
3234 public void adapt(Type source,
3235 Type target,
3236 ListBuffer<Type> from,
3237 ListBuffer<Type> to) throws AdaptFailure {
3238 new Adapter(from, to).adapt(source, target);
3239 }
3241 class Adapter extends SimpleVisitor<Void, Type> {
3243 ListBuffer<Type> from;
3244 ListBuffer<Type> to;
3245 Map<Symbol,Type> mapping;
3247 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3248 this.from = from;
3249 this.to = to;
3250 mapping = new HashMap<Symbol,Type>();
3251 }
3253 public void adapt(Type source, Type target) throws AdaptFailure {
3254 visit(source, target);
3255 List<Type> fromList = from.toList();
3256 List<Type> toList = to.toList();
3257 while (!fromList.isEmpty()) {
3258 Type val = mapping.get(fromList.head.tsym);
3259 if (toList.head != val)
3260 toList.head = val;
3261 fromList = fromList.tail;
3262 toList = toList.tail;
3263 }
3264 }
3266 @Override
3267 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3268 if (target.tag == CLASS)
3269 adaptRecursive(source.allparams(), target.allparams());
3270 return null;
3271 }
3273 @Override
3274 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3275 if (target.tag == ARRAY)
3276 adaptRecursive(elemtype(source), elemtype(target));
3277 return null;
3278 }
3280 @Override
3281 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3282 if (source.isExtendsBound())
3283 adaptRecursive(upperBound(source), upperBound(target));
3284 else if (source.isSuperBound())
3285 adaptRecursive(lowerBound(source), lowerBound(target));
3286 return null;
3287 }
3289 @Override
3290 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3291 // Check to see if there is
3292 // already a mapping for $source$, in which case
3293 // the old mapping will be merged with the new
3294 Type val = mapping.get(source.tsym);
3295 if (val != null) {
3296 if (val.isSuperBound() && target.isSuperBound()) {
3297 val = isSubtype(lowerBound(val), lowerBound(target))
3298 ? target : val;
3299 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3300 val = isSubtype(upperBound(val), upperBound(target))
3301 ? val : target;
3302 } else if (!isSameType(val, target)) {
3303 throw new AdaptFailure();
3304 }
3305 } else {
3306 val = target;
3307 from.append(source);
3308 to.append(target);
3309 }
3310 mapping.put(source.tsym, val);
3311 return null;
3312 }
3314 @Override
3315 public Void visitType(Type source, Type target) {
3316 return null;
3317 }
3319 private Set<TypePair> cache = new HashSet<TypePair>();
3321 private void adaptRecursive(Type source, Type target) {
3322 TypePair pair = new TypePair(source, target);
3323 if (cache.add(pair)) {
3324 try {
3325 visit(source, target);
3326 } finally {
3327 cache.remove(pair);
3328 }
3329 }
3330 }
3332 private void adaptRecursive(List<Type> source, List<Type> target) {
3333 if (source.length() == target.length()) {
3334 while (source.nonEmpty()) {
3335 adaptRecursive(source.head, target.head);
3336 source = source.tail;
3337 target = target.tail;
3338 }
3339 }
3340 }
3341 }
3343 public static class AdaptFailure extends RuntimeException {
3344 static final long serialVersionUID = -7490231548272701566L;
3345 }
3347 private void adaptSelf(Type t,
3348 ListBuffer<Type> from,
3349 ListBuffer<Type> to) {
3350 try {
3351 //if (t.tsym.type != t)
3352 adapt(t.tsym.type, t, from, to);
3353 } catch (AdaptFailure ex) {
3354 // Adapt should never fail calculating a mapping from
3355 // t.tsym.type to t as there can be no merge problem.
3356 throw new AssertionError(ex);
3357 }
3358 }
3359 // </editor-fold>
3361 /**
3362 * Rewrite all type variables (universal quantifiers) in the given
3363 * type to wildcards (existential quantifiers). This is used to
3364 * determine if a cast is allowed. For example, if high is true
3365 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3366 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3367 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3368 * List<Integer>} with a warning.
3369 * @param t a type
3370 * @param high if true return an upper bound; otherwise a lower
3371 * bound
3372 * @param rewriteTypeVars only rewrite captured wildcards if false;
3373 * otherwise rewrite all type variables
3374 * @return the type rewritten with wildcards (existential
3375 * quantifiers) only
3376 */
3377 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3378 return new Rewriter(high, rewriteTypeVars).visit(t);
3379 }
3381 class Rewriter extends UnaryVisitor<Type> {
3383 boolean high;
3384 boolean rewriteTypeVars;
3386 Rewriter(boolean high, boolean rewriteTypeVars) {
3387 this.high = high;
3388 this.rewriteTypeVars = rewriteTypeVars;
3389 }
3391 @Override
3392 public Type visitClassType(ClassType t, Void s) {
3393 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3394 boolean changed = false;
3395 for (Type arg : t.allparams()) {
3396 Type bound = visit(arg);
3397 if (arg != bound) {
3398 changed = true;
3399 }
3400 rewritten.append(bound);
3401 }
3402 if (changed)
3403 return subst(t.tsym.type,
3404 t.tsym.type.allparams(),
3405 rewritten.toList());
3406 else
3407 return t;
3408 }
3410 public Type visitType(Type t, Void s) {
3411 return high ? upperBound(t) : lowerBound(t);
3412 }
3414 @Override
3415 public Type visitCapturedType(CapturedType t, Void s) {
3416 Type bound = visitWildcardType(t.wildcard, null);
3417 return (bound.contains(t)) ?
3418 erasure(bound) :
3419 bound;
3420 }
3422 @Override
3423 public Type visitTypeVar(TypeVar t, Void s) {
3424 if (rewriteTypeVars) {
3425 Type bound = high ?
3426 (t.bound.contains(t) ?
3427 erasure(t.bound) :
3428 visit(t.bound)) :
3429 syms.botType;
3430 return rewriteAsWildcardType(bound, t);
3431 }
3432 else
3433 return t;
3434 }
3436 @Override
3437 public Type visitWildcardType(WildcardType t, Void s) {
3438 Type bound = high ? t.getExtendsBound() :
3439 t.getSuperBound();
3440 if (bound == null)
3441 bound = high ? syms.objectType : syms.botType;
3442 return rewriteAsWildcardType(visit(bound), t.bound);
3443 }
3445 private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
3446 return high ?
3447 makeExtendsWildcard(B(bound), formal) :
3448 makeSuperWildcard(B(bound), formal);
3449 }
3451 Type B(Type t) {
3452 while (t.tag == WILDCARD) {
3453 WildcardType w = (WildcardType)t;
3454 t = high ?
3455 w.getExtendsBound() :
3456 w.getSuperBound();
3457 if (t == null) {
3458 t = high ? syms.objectType : syms.botType;
3459 }
3460 }
3461 return t;
3462 }
3463 }
3466 /**
3467 * Create a wildcard with the given upper (extends) bound; create
3468 * an unbounded wildcard if bound is Object.
3469 *
3470 * @param bound the upper bound
3471 * @param formal the formal type parameter that will be
3472 * substituted by the wildcard
3473 */
3474 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3475 if (bound == syms.objectType) {
3476 return new WildcardType(syms.objectType,
3477 BoundKind.UNBOUND,
3478 syms.boundClass,
3479 formal);
3480 } else {
3481 return new WildcardType(bound,
3482 BoundKind.EXTENDS,
3483 syms.boundClass,
3484 formal);
3485 }
3486 }
3488 /**
3489 * Create a wildcard with the given lower (super) bound; create an
3490 * unbounded wildcard if bound is bottom (type of {@code null}).
3491 *
3492 * @param bound the lower bound
3493 * @param formal the formal type parameter that will be
3494 * substituted by the wildcard
3495 */
3496 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3497 if (bound.tag == BOT) {
3498 return new WildcardType(syms.objectType,
3499 BoundKind.UNBOUND,
3500 syms.boundClass,
3501 formal);
3502 } else {
3503 return new WildcardType(bound,
3504 BoundKind.SUPER,
3505 syms.boundClass,
3506 formal);
3507 }
3508 }
3510 /**
3511 * A wrapper for a type that allows use in sets.
3512 */
3513 class SingletonType {
3514 final Type t;
3515 SingletonType(Type t) {
3516 this.t = t;
3517 }
3518 public int hashCode() {
3519 return Types.hashCode(t);
3520 }
3521 public boolean equals(Object obj) {
3522 return (obj instanceof SingletonType) &&
3523 isSameType(t, ((SingletonType)obj).t);
3524 }
3525 public String toString() {
3526 return t.toString();
3527 }
3528 }
3529 // </editor-fold>
3531 // <editor-fold defaultstate="collapsed" desc="Visitors">
3532 /**
3533 * A default visitor for types. All visitor methods except
3534 * visitType are implemented by delegating to visitType. Concrete
3535 * subclasses must provide an implementation of visitType and can
3536 * override other methods as needed.
3537 *
3538 * @param <R> the return type of the operation implemented by this
3539 * visitor; use Void if no return type is needed.
3540 * @param <S> the type of the second argument (the first being the
3541 * type itself) of the operation implemented by this visitor; use
3542 * Void if a second argument is not needed.
3543 */
3544 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3545 final public R visit(Type t, S s) { return t.accept(this, s); }
3546 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3547 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3548 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3549 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3550 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3551 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3552 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3553 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3554 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3555 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3556 }
3558 /**
3559 * A default visitor for symbols. All visitor methods except
3560 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3561 * subclasses must provide an implementation of visitSymbol and can
3562 * override other methods as needed.
3563 *
3564 * @param <R> the return type of the operation implemented by this
3565 * visitor; use Void if no return type is needed.
3566 * @param <S> the type of the second argument (the first being the
3567 * symbol itself) of the operation implemented by this visitor; use
3568 * Void if a second argument is not needed.
3569 */
3570 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3571 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3572 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3573 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3574 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3575 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3576 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3577 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3578 }
3580 /**
3581 * A <em>simple</em> visitor for types. This visitor is simple as
3582 * captured wildcards, for-all types (generic methods), and
3583 * undetermined type variables (part of inference) are hidden.
3584 * Captured wildcards are hidden by treating them as type
3585 * variables and the rest are hidden by visiting their qtypes.
3586 *
3587 * @param <R> the return type of the operation implemented by this
3588 * visitor; use Void if no return type is needed.
3589 * @param <S> the type of the second argument (the first being the
3590 * type itself) of the operation implemented by this visitor; use
3591 * Void if a second argument is not needed.
3592 */
3593 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3594 @Override
3595 public R visitCapturedType(CapturedType t, S s) {
3596 return visitTypeVar(t, s);
3597 }
3598 @Override
3599 public R visitForAll(ForAll t, S s) {
3600 return visit(t.qtype, s);
3601 }
3602 @Override
3603 public R visitUndetVar(UndetVar t, S s) {
3604 return visit(t.qtype, s);
3605 }
3606 }
3608 /**
3609 * A plain relation on types. That is a 2-ary function on the
3610 * form Type × Type → Boolean.
3611 * <!-- In plain text: Type x Type -> Boolean -->
3612 */
3613 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3615 /**
3616 * A convenience visitor for implementing operations that only
3617 * require one argument (the type itself), that is, unary
3618 * operations.
3619 *
3620 * @param <R> the return type of the operation implemented by this
3621 * visitor; use Void if no return type is needed.
3622 */
3623 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3624 final public R visit(Type t) { return t.accept(this, null); }
3625 }
3627 /**
3628 * A visitor for implementing a mapping from types to types. The
3629 * default behavior of this class is to implement the identity
3630 * mapping (mapping a type to itself). This can be overridden in
3631 * subclasses.
3632 *
3633 * @param <S> the type of the second argument (the first being the
3634 * type itself) of this mapping; use Void if a second argument is
3635 * not needed.
3636 */
3637 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3638 final public Type visit(Type t) { return t.accept(this, null); }
3639 public Type visitType(Type t, S s) { return t; }
3640 }
3641 // </editor-fold>
3644 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3646 public RetentionPolicy getRetention(Attribute.Compound a) {
3647 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3648 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3649 if (c != null) {
3650 Attribute value = c.member(names.value);
3651 if (value != null && value instanceof Attribute.Enum) {
3652 Name levelName = ((Attribute.Enum)value).value.name;
3653 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3654 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3655 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3656 else ;// /* fail soft */ throw new AssertionError(levelName);
3657 }
3658 }
3659 return vis;
3660 }
3661 // </editor-fold>
3662 }