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