Thu, 09 Dec 2010 15:50:10 +0000
7005095: Cast: compile reject sensible cast from final class to interface
Summary: a previous fix to cast conversion has made the compiler too strict w.r.t. final cast
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 (upcast ? giveWarning(a, b) :
1037 giveWarning(b, a))
1038 warnStack.head.warnUnchecked();
1039 return true;
1040 }
1041 }
1042 if (isReifiable(s))
1043 return isSubtypeUnchecked(a, b);
1044 else
1045 return isSubtypeUnchecked(a, b, warnStack.head);
1046 }
1048 // Sidecast
1049 if (s.tag == CLASS) {
1050 if ((s.tsym.flags() & INTERFACE) != 0) {
1051 return ((t.tsym.flags() & FINAL) == 0)
1052 ? sideCast(t, s, warnStack.head)
1053 : sideCastFinal(t, s, warnStack.head);
1054 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1055 return ((s.tsym.flags() & FINAL) == 0)
1056 ? sideCast(t, s, warnStack.head)
1057 : sideCastFinal(t, s, warnStack.head);
1058 } else {
1059 // unrelated class types
1060 return false;
1061 }
1062 }
1063 }
1064 return false;
1065 }
1067 @Override
1068 public Boolean visitArrayType(ArrayType t, Type s) {
1069 switch (s.tag) {
1070 case ERROR:
1071 case BOT:
1072 return true;
1073 case TYPEVAR:
1074 if (isCastable(s, t, Warner.noWarnings)) {
1075 warnStack.head.warnUnchecked();
1076 return true;
1077 } else {
1078 return false;
1079 }
1080 case CLASS:
1081 return isSubtype(t, s);
1082 case ARRAY:
1083 if (elemtype(t).tag <= lastBaseTag) {
1084 return elemtype(t).tag == elemtype(s).tag;
1085 } else {
1086 return visit(elemtype(t), elemtype(s));
1087 }
1088 default:
1089 return false;
1090 }
1091 }
1093 @Override
1094 public Boolean visitTypeVar(TypeVar t, Type s) {
1095 switch (s.tag) {
1096 case ERROR:
1097 case BOT:
1098 return true;
1099 case TYPEVAR:
1100 if (isSubtype(t, s)) {
1101 return true;
1102 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1103 warnStack.head.warnUnchecked();
1104 return true;
1105 } else {
1106 return false;
1107 }
1108 default:
1109 return isCastable(t.bound, s, warnStack.head);
1110 }
1111 }
1113 @Override
1114 public Boolean visitErrorType(ErrorType t, Type s) {
1115 return true;
1116 }
1117 };
1118 // </editor-fold>
1120 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1121 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1122 while (ts.tail != null && ss.tail != null) {
1123 if (disjointType(ts.head, ss.head)) return true;
1124 ts = ts.tail;
1125 ss = ss.tail;
1126 }
1127 return false;
1128 }
1130 /**
1131 * Two types or wildcards are considered disjoint if it can be
1132 * proven that no type can be contained in both. It is
1133 * conservative in that it is allowed to say that two types are
1134 * not disjoint, even though they actually are.
1135 *
1136 * The type C<X> is castable to C<Y> exactly if X and Y are not
1137 * disjoint.
1138 */
1139 public boolean disjointType(Type t, Type s) {
1140 return disjointType.visit(t, s);
1141 }
1142 // where
1143 private TypeRelation disjointType = new TypeRelation() {
1145 private Set<TypePair> cache = new HashSet<TypePair>();
1147 public Boolean visitType(Type t, Type s) {
1148 if (s.tag == WILDCARD)
1149 return visit(s, t);
1150 else
1151 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1152 }
1154 private boolean isCastableRecursive(Type t, Type s) {
1155 TypePair pair = new TypePair(t, s);
1156 if (cache.add(pair)) {
1157 try {
1158 return Types.this.isCastable(t, s);
1159 } finally {
1160 cache.remove(pair);
1161 }
1162 } else {
1163 return true;
1164 }
1165 }
1167 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1168 TypePair pair = new TypePair(t, s);
1169 if (cache.add(pair)) {
1170 try {
1171 return Types.this.notSoftSubtype(t, s);
1172 } finally {
1173 cache.remove(pair);
1174 }
1175 } else {
1176 return false;
1177 }
1178 }
1180 @Override
1181 public Boolean visitWildcardType(WildcardType t, Type s) {
1182 if (t.isUnbound())
1183 return false;
1185 if (s.tag != WILDCARD) {
1186 if (t.isExtendsBound())
1187 return notSoftSubtypeRecursive(s, t.type);
1188 else // isSuperBound()
1189 return notSoftSubtypeRecursive(t.type, s);
1190 }
1192 if (s.isUnbound())
1193 return false;
1195 if (t.isExtendsBound()) {
1196 if (s.isExtendsBound())
1197 return !isCastableRecursive(t.type, upperBound(s));
1198 else if (s.isSuperBound())
1199 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1200 } else if (t.isSuperBound()) {
1201 if (s.isExtendsBound())
1202 return notSoftSubtypeRecursive(t.type, upperBound(s));
1203 }
1204 return false;
1205 }
1206 };
1207 // </editor-fold>
1209 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1210 /**
1211 * Returns the lower bounds of the formals of a method.
1212 */
1213 public List<Type> lowerBoundArgtypes(Type t) {
1214 return map(t.getParameterTypes(), lowerBoundMapping);
1215 }
1216 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1217 public Type apply(Type t) {
1218 return lowerBound(t);
1219 }
1220 };
1221 // </editor-fold>
1223 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1224 /**
1225 * This relation answers the question: is impossible that
1226 * something of type `t' can be a subtype of `s'? This is
1227 * different from the question "is `t' not a subtype of `s'?"
1228 * when type variables are involved: Integer is not a subtype of T
1229 * where <T extends Number> but it is not true that Integer cannot
1230 * possibly be a subtype of T.
1231 */
1232 public boolean notSoftSubtype(Type t, Type s) {
1233 if (t == s) return false;
1234 if (t.tag == TYPEVAR) {
1235 TypeVar tv = (TypeVar) t;
1236 return !isCastable(tv.bound,
1237 relaxBound(s),
1238 Warner.noWarnings);
1239 }
1240 if (s.tag != WILDCARD)
1241 s = upperBound(s);
1243 return !isSubtype(t, relaxBound(s));
1244 }
1246 private Type relaxBound(Type t) {
1247 if (t.tag == TYPEVAR) {
1248 while (t.tag == TYPEVAR)
1249 t = t.getUpperBound();
1250 t = rewriteQuantifiers(t, true, true);
1251 }
1252 return t;
1253 }
1254 // </editor-fold>
1256 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1257 public boolean isReifiable(Type t) {
1258 return isReifiable.visit(t);
1259 }
1260 // where
1261 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1263 public Boolean visitType(Type t, Void ignored) {
1264 return true;
1265 }
1267 @Override
1268 public Boolean visitClassType(ClassType t, Void ignored) {
1269 if (t.isCompound())
1270 return false;
1271 else {
1272 if (!t.isParameterized())
1273 return true;
1275 for (Type param : t.allparams()) {
1276 if (!param.isUnbound())
1277 return false;
1278 }
1279 return true;
1280 }
1281 }
1283 @Override
1284 public Boolean visitArrayType(ArrayType t, Void ignored) {
1285 return visit(t.elemtype);
1286 }
1288 @Override
1289 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1290 return false;
1291 }
1292 };
1293 // </editor-fold>
1295 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1296 public boolean isArray(Type t) {
1297 while (t.tag == WILDCARD)
1298 t = upperBound(t);
1299 return t.tag == ARRAY;
1300 }
1302 /**
1303 * The element type of an array.
1304 */
1305 public Type elemtype(Type t) {
1306 switch (t.tag) {
1307 case WILDCARD:
1308 return elemtype(upperBound(t));
1309 case ARRAY:
1310 return ((ArrayType)t).elemtype;
1311 case FORALL:
1312 return elemtype(((ForAll)t).qtype);
1313 case ERROR:
1314 return t;
1315 default:
1316 return null;
1317 }
1318 }
1320 /**
1321 * Mapping to take element type of an arraytype
1322 */
1323 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1324 public Type apply(Type t) { return elemtype(t); }
1325 };
1327 /**
1328 * The number of dimensions of an array type.
1329 */
1330 public int dimensions(Type t) {
1331 int result = 0;
1332 while (t.tag == ARRAY) {
1333 result++;
1334 t = elemtype(t);
1335 }
1336 return result;
1337 }
1338 // </editor-fold>
1340 // <editor-fold defaultstate="collapsed" desc="asSuper">
1341 /**
1342 * Return the (most specific) base type of t that starts with the
1343 * given symbol. If none exists, return null.
1344 *
1345 * @param t a type
1346 * @param sym a symbol
1347 */
1348 public Type asSuper(Type t, Symbol sym) {
1349 return asSuper.visit(t, sym);
1350 }
1351 // where
1352 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1354 public Type visitType(Type t, Symbol sym) {
1355 return null;
1356 }
1358 @Override
1359 public Type visitClassType(ClassType t, Symbol sym) {
1360 if (t.tsym == sym)
1361 return t;
1363 Type st = supertype(t);
1364 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1365 Type x = asSuper(st, sym);
1366 if (x != null)
1367 return x;
1368 }
1369 if ((sym.flags() & INTERFACE) != 0) {
1370 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1371 Type x = asSuper(l.head, sym);
1372 if (x != null)
1373 return x;
1374 }
1375 }
1376 return null;
1377 }
1379 @Override
1380 public Type visitArrayType(ArrayType t, Symbol sym) {
1381 return isSubtype(t, sym.type) ? sym.type : null;
1382 }
1384 @Override
1385 public Type visitTypeVar(TypeVar t, Symbol sym) {
1386 if (t.tsym == sym)
1387 return t;
1388 else
1389 return asSuper(t.bound, sym);
1390 }
1392 @Override
1393 public Type visitErrorType(ErrorType t, Symbol sym) {
1394 return t;
1395 }
1396 };
1398 /**
1399 * Return the base type of t or any of its outer types that starts
1400 * with the given symbol. If none exists, return null.
1401 *
1402 * @param t a type
1403 * @param sym a symbol
1404 */
1405 public Type asOuterSuper(Type t, Symbol sym) {
1406 switch (t.tag) {
1407 case CLASS:
1408 do {
1409 Type s = asSuper(t, sym);
1410 if (s != null) return s;
1411 t = t.getEnclosingType();
1412 } while (t.tag == CLASS);
1413 return null;
1414 case ARRAY:
1415 return isSubtype(t, sym.type) ? sym.type : null;
1416 case TYPEVAR:
1417 return asSuper(t, sym);
1418 case ERROR:
1419 return t;
1420 default:
1421 return null;
1422 }
1423 }
1425 /**
1426 * Return the base type of t or any of its enclosing types that
1427 * starts with the given symbol. If none exists, return null.
1428 *
1429 * @param t a type
1430 * @param sym a symbol
1431 */
1432 public Type asEnclosingSuper(Type t, Symbol sym) {
1433 switch (t.tag) {
1434 case CLASS:
1435 do {
1436 Type s = asSuper(t, sym);
1437 if (s != null) return s;
1438 Type outer = t.getEnclosingType();
1439 t = (outer.tag == CLASS) ? outer :
1440 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1441 Type.noType;
1442 } while (t.tag == CLASS);
1443 return null;
1444 case ARRAY:
1445 return isSubtype(t, sym.type) ? sym.type : null;
1446 case TYPEVAR:
1447 return asSuper(t, sym);
1448 case ERROR:
1449 return t;
1450 default:
1451 return null;
1452 }
1453 }
1454 // </editor-fold>
1456 // <editor-fold defaultstate="collapsed" desc="memberType">
1457 /**
1458 * The type of given symbol, seen as a member of t.
1459 *
1460 * @param t a type
1461 * @param sym a symbol
1462 */
1463 public Type memberType(Type t, Symbol sym) {
1464 return (sym.flags() & STATIC) != 0
1465 ? sym.type
1466 : memberType.visit(t, sym);
1467 }
1468 // where
1469 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1471 public Type visitType(Type t, Symbol sym) {
1472 return sym.type;
1473 }
1475 @Override
1476 public Type visitWildcardType(WildcardType t, Symbol sym) {
1477 return memberType(upperBound(t), sym);
1478 }
1480 @Override
1481 public Type visitClassType(ClassType t, Symbol sym) {
1482 Symbol owner = sym.owner;
1483 long flags = sym.flags();
1484 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1485 Type base = asOuterSuper(t, owner);
1486 //if t is an intersection type T = CT & I1 & I2 ... & In
1487 //its supertypes CT, I1, ... In might contain wildcards
1488 //so we need to go through capture conversion
1489 base = t.isCompound() ? capture(base) : base;
1490 if (base != null) {
1491 List<Type> ownerParams = owner.type.allparams();
1492 List<Type> baseParams = base.allparams();
1493 if (ownerParams.nonEmpty()) {
1494 if (baseParams.isEmpty()) {
1495 // then base is a raw type
1496 return erasure(sym.type);
1497 } else {
1498 return subst(sym.type, ownerParams, baseParams);
1499 }
1500 }
1501 }
1502 }
1503 return sym.type;
1504 }
1506 @Override
1507 public Type visitTypeVar(TypeVar t, Symbol sym) {
1508 return memberType(t.bound, sym);
1509 }
1511 @Override
1512 public Type visitErrorType(ErrorType t, Symbol sym) {
1513 return t;
1514 }
1515 };
1516 // </editor-fold>
1518 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1519 public boolean isAssignable(Type t, Type s) {
1520 return isAssignable(t, s, Warner.noWarnings);
1521 }
1523 /**
1524 * Is t assignable to s?<br>
1525 * Equivalent to subtype except for constant values and raw
1526 * types.<br>
1527 * (not defined for Method and ForAll types)
1528 */
1529 public boolean isAssignable(Type t, Type s, Warner warn) {
1530 if (t.tag == ERROR)
1531 return true;
1532 if (t.tag <= INT && t.constValue() != null) {
1533 int value = ((Number)t.constValue()).intValue();
1534 switch (s.tag) {
1535 case BYTE:
1536 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1537 return true;
1538 break;
1539 case CHAR:
1540 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1541 return true;
1542 break;
1543 case SHORT:
1544 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1545 return true;
1546 break;
1547 case INT:
1548 return true;
1549 case CLASS:
1550 switch (unboxedType(s).tag) {
1551 case BYTE:
1552 case CHAR:
1553 case SHORT:
1554 return isAssignable(t, unboxedType(s), warn);
1555 }
1556 break;
1557 }
1558 }
1559 return isConvertible(t, s, warn);
1560 }
1561 // </editor-fold>
1563 // <editor-fold defaultstate="collapsed" desc="erasure">
1564 /**
1565 * The erasure of t {@code |t|} -- the type that results when all
1566 * type parameters in t are deleted.
1567 */
1568 public Type erasure(Type t) {
1569 return erasure(t, false);
1570 }
1571 //where
1572 private Type erasure(Type t, boolean recurse) {
1573 if (t.tag <= lastBaseTag)
1574 return t; /* fast special case */
1575 else
1576 return erasure.visit(t, recurse);
1577 }
1578 // where
1579 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1580 public Type visitType(Type t, Boolean recurse) {
1581 if (t.tag <= lastBaseTag)
1582 return t; /*fast special case*/
1583 else
1584 return t.map(recurse ? erasureRecFun : erasureFun);
1585 }
1587 @Override
1588 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1589 return erasure(upperBound(t), recurse);
1590 }
1592 @Override
1593 public Type visitClassType(ClassType t, Boolean recurse) {
1594 Type erased = t.tsym.erasure(Types.this);
1595 if (recurse) {
1596 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1597 }
1598 return erased;
1599 }
1601 @Override
1602 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1603 return erasure(t.bound, recurse);
1604 }
1606 @Override
1607 public Type visitErrorType(ErrorType t, Boolean recurse) {
1608 return t;
1609 }
1610 };
1612 private Mapping erasureFun = new Mapping ("erasure") {
1613 public Type apply(Type t) { return erasure(t); }
1614 };
1616 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1617 public Type apply(Type t) { return erasureRecursive(t); }
1618 };
1620 public List<Type> erasure(List<Type> ts) {
1621 return Type.map(ts, erasureFun);
1622 }
1624 public Type erasureRecursive(Type t) {
1625 return erasure(t, true);
1626 }
1628 public List<Type> erasureRecursive(List<Type> ts) {
1629 return Type.map(ts, erasureRecFun);
1630 }
1631 // </editor-fold>
1633 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1634 /**
1635 * Make a compound type from non-empty list of types
1636 *
1637 * @param bounds the types from which the compound type is formed
1638 * @param supertype is objectType if all bounds are interfaces,
1639 * null otherwise.
1640 */
1641 public Type makeCompoundType(List<Type> bounds,
1642 Type supertype) {
1643 ClassSymbol bc =
1644 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1645 Type.moreInfo
1646 ? names.fromString(bounds.toString())
1647 : names.empty,
1648 syms.noSymbol);
1649 if (bounds.head.tag == TYPEVAR)
1650 // error condition, recover
1651 bc.erasure_field = syms.objectType;
1652 else
1653 bc.erasure_field = erasure(bounds.head);
1654 bc.members_field = new Scope(bc);
1655 ClassType bt = (ClassType)bc.type;
1656 bt.allparams_field = List.nil();
1657 if (supertype != null) {
1658 bt.supertype_field = supertype;
1659 bt.interfaces_field = bounds;
1660 } else {
1661 bt.supertype_field = bounds.head;
1662 bt.interfaces_field = bounds.tail;
1663 }
1664 assert bt.supertype_field.tsym.completer != null
1665 || !bt.supertype_field.isInterface()
1666 : bt.supertype_field;
1667 return bt;
1668 }
1670 /**
1671 * Same as {@link #makeCompoundType(List,Type)}, except that the
1672 * second parameter is computed directly. Note that this might
1673 * cause a symbol completion. Hence, this version of
1674 * makeCompoundType may not be called during a classfile read.
1675 */
1676 public Type makeCompoundType(List<Type> bounds) {
1677 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1678 supertype(bounds.head) : null;
1679 return makeCompoundType(bounds, supertype);
1680 }
1682 /**
1683 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1684 * arguments are converted to a list and passed to the other
1685 * method. Note that this might cause a symbol completion.
1686 * Hence, this version of makeCompoundType may not be called
1687 * during a classfile read.
1688 */
1689 public Type makeCompoundType(Type bound1, Type bound2) {
1690 return makeCompoundType(List.of(bound1, bound2));
1691 }
1692 // </editor-fold>
1694 // <editor-fold defaultstate="collapsed" desc="supertype">
1695 public Type supertype(Type t) {
1696 return supertype.visit(t);
1697 }
1698 // where
1699 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1701 public Type visitType(Type t, Void ignored) {
1702 // A note on wildcards: there is no good way to
1703 // determine a supertype for a super bounded wildcard.
1704 return null;
1705 }
1707 @Override
1708 public Type visitClassType(ClassType t, Void ignored) {
1709 if (t.supertype_field == null) {
1710 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1711 // An interface has no superclass; its supertype is Object.
1712 if (t.isInterface())
1713 supertype = ((ClassType)t.tsym.type).supertype_field;
1714 if (t.supertype_field == null) {
1715 List<Type> actuals = classBound(t).allparams();
1716 List<Type> formals = t.tsym.type.allparams();
1717 if (t.hasErasedSupertypes()) {
1718 t.supertype_field = erasureRecursive(supertype);
1719 } else if (formals.nonEmpty()) {
1720 t.supertype_field = subst(supertype, formals, actuals);
1721 }
1722 else {
1723 t.supertype_field = supertype;
1724 }
1725 }
1726 }
1727 return t.supertype_field;
1728 }
1730 /**
1731 * The supertype is always a class type. If the type
1732 * variable's bounds start with a class type, this is also
1733 * the supertype. Otherwise, the supertype is
1734 * java.lang.Object.
1735 */
1736 @Override
1737 public Type visitTypeVar(TypeVar t, Void ignored) {
1738 if (t.bound.tag == TYPEVAR ||
1739 (!t.bound.isCompound() && !t.bound.isInterface())) {
1740 return t.bound;
1741 } else {
1742 return supertype(t.bound);
1743 }
1744 }
1746 @Override
1747 public Type visitArrayType(ArrayType t, Void ignored) {
1748 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1749 return arraySuperType();
1750 else
1751 return new ArrayType(supertype(t.elemtype), t.tsym);
1752 }
1754 @Override
1755 public Type visitErrorType(ErrorType t, Void ignored) {
1756 return t;
1757 }
1758 };
1759 // </editor-fold>
1761 // <editor-fold defaultstate="collapsed" desc="interfaces">
1762 /**
1763 * Return the interfaces implemented by this class.
1764 */
1765 public List<Type> interfaces(Type t) {
1766 return interfaces.visit(t);
1767 }
1768 // where
1769 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1771 public List<Type> visitType(Type t, Void ignored) {
1772 return List.nil();
1773 }
1775 @Override
1776 public List<Type> visitClassType(ClassType t, Void ignored) {
1777 if (t.interfaces_field == null) {
1778 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1779 if (t.interfaces_field == null) {
1780 // If t.interfaces_field is null, then t must
1781 // be a parameterized type (not to be confused
1782 // with a generic type declaration).
1783 // Terminology:
1784 // Parameterized type: List<String>
1785 // Generic type declaration: class List<E> { ... }
1786 // So t corresponds to List<String> and
1787 // t.tsym.type corresponds to List<E>.
1788 // The reason t must be parameterized type is
1789 // that completion will happen as a side
1790 // effect of calling
1791 // ClassSymbol.getInterfaces. Since
1792 // t.interfaces_field is null after
1793 // completion, we can assume that t is not the
1794 // type of a class/interface declaration.
1795 assert t != t.tsym.type : t.toString();
1796 List<Type> actuals = t.allparams();
1797 List<Type> formals = t.tsym.type.allparams();
1798 if (t.hasErasedSupertypes()) {
1799 t.interfaces_field = erasureRecursive(interfaces);
1800 } else if (formals.nonEmpty()) {
1801 t.interfaces_field =
1802 upperBounds(subst(interfaces, formals, actuals));
1803 }
1804 else {
1805 t.interfaces_field = interfaces;
1806 }
1807 }
1808 }
1809 return t.interfaces_field;
1810 }
1812 @Override
1813 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1814 if (t.bound.isCompound())
1815 return interfaces(t.bound);
1817 if (t.bound.isInterface())
1818 return List.of(t.bound);
1820 return List.nil();
1821 }
1822 };
1823 // </editor-fold>
1825 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1826 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1828 public boolean isDerivedRaw(Type t) {
1829 Boolean result = isDerivedRawCache.get(t);
1830 if (result == null) {
1831 result = isDerivedRawInternal(t);
1832 isDerivedRawCache.put(t, result);
1833 }
1834 return result;
1835 }
1837 public boolean isDerivedRawInternal(Type t) {
1838 if (t.isErroneous())
1839 return false;
1840 return
1841 t.isRaw() ||
1842 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1843 isDerivedRaw(interfaces(t));
1844 }
1846 public boolean isDerivedRaw(List<Type> ts) {
1847 List<Type> l = ts;
1848 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1849 return l.nonEmpty();
1850 }
1851 // </editor-fold>
1853 // <editor-fold defaultstate="collapsed" desc="setBounds">
1854 /**
1855 * Set the bounds field of the given type variable to reflect a
1856 * (possibly multiple) list of bounds.
1857 * @param t a type variable
1858 * @param bounds the bounds, must be nonempty
1859 * @param supertype is objectType if all bounds are interfaces,
1860 * null otherwise.
1861 */
1862 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1863 if (bounds.tail.isEmpty())
1864 t.bound = bounds.head;
1865 else
1866 t.bound = makeCompoundType(bounds, supertype);
1867 t.rank_field = -1;
1868 }
1870 /**
1871 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1872 * third parameter is computed directly, as follows: if all
1873 * all bounds are interface types, the computed supertype is Object,
1874 * otherwise the supertype is simply left null (in this case, the supertype
1875 * is assumed to be the head of the bound list passed as second argument).
1876 * Note that this check might cause a symbol completion. Hence, this version of
1877 * setBounds may not be called during a classfile read.
1878 */
1879 public void setBounds(TypeVar t, List<Type> bounds) {
1880 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1881 syms.objectType : null;
1882 setBounds(t, bounds, supertype);
1883 t.rank_field = -1;
1884 }
1885 // </editor-fold>
1887 // <editor-fold defaultstate="collapsed" desc="getBounds">
1888 /**
1889 * Return list of bounds of the given type variable.
1890 */
1891 public List<Type> getBounds(TypeVar t) {
1892 if (t.bound.isErroneous() || !t.bound.isCompound())
1893 return List.of(t.bound);
1894 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1895 return interfaces(t).prepend(supertype(t));
1896 else
1897 // No superclass was given in bounds.
1898 // In this case, supertype is Object, erasure is first interface.
1899 return interfaces(t);
1900 }
1901 // </editor-fold>
1903 // <editor-fold defaultstate="collapsed" desc="classBound">
1904 /**
1905 * If the given type is a (possibly selected) type variable,
1906 * return the bounding class of this type, otherwise return the
1907 * type itself.
1908 */
1909 public Type classBound(Type t) {
1910 return classBound.visit(t);
1911 }
1912 // where
1913 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1915 public Type visitType(Type t, Void ignored) {
1916 return t;
1917 }
1919 @Override
1920 public Type visitClassType(ClassType t, Void ignored) {
1921 Type outer1 = classBound(t.getEnclosingType());
1922 if (outer1 != t.getEnclosingType())
1923 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1924 else
1925 return t;
1926 }
1928 @Override
1929 public Type visitTypeVar(TypeVar t, Void ignored) {
1930 return classBound(supertype(t));
1931 }
1933 @Override
1934 public Type visitErrorType(ErrorType t, Void ignored) {
1935 return t;
1936 }
1937 };
1938 // </editor-fold>
1940 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1941 /**
1942 * Returns true iff the first signature is a <em>sub
1943 * signature</em> of the other. This is <b>not</b> an equivalence
1944 * relation.
1945 *
1946 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1947 * @see #overrideEquivalent(Type t, Type s)
1948 * @param t first signature (possibly raw).
1949 * @param s second signature (could be subjected to erasure).
1950 * @return true if t is a sub signature of s.
1951 */
1952 public boolean isSubSignature(Type t, Type s) {
1953 return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
1954 }
1956 /**
1957 * Returns true iff these signatures are related by <em>override
1958 * equivalence</em>. This is the natural extension of
1959 * isSubSignature to an equivalence relation.
1960 *
1961 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1962 * @see #isSubSignature(Type t, Type s)
1963 * @param t a signature (possible raw, could be subjected to
1964 * erasure).
1965 * @param s a signature (possible raw, could be subjected to
1966 * erasure).
1967 * @return true if either argument is a sub signature of the other.
1968 */
1969 public boolean overrideEquivalent(Type t, Type s) {
1970 return hasSameArgs(t, s) ||
1971 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
1972 }
1974 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
1975 class ImplementationCache {
1977 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
1978 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
1980 class Entry {
1981 final MethodSymbol cachedImpl;
1982 final Filter<Symbol> implFilter;
1983 final boolean checkResult;
1984 final Scope.ScopeCounter scopeCounter;
1986 public Entry(MethodSymbol cachedImpl,
1987 Filter<Symbol> scopeFilter,
1988 boolean checkResult,
1989 Scope.ScopeCounter scopeCounter) {
1990 this.cachedImpl = cachedImpl;
1991 this.implFilter = scopeFilter;
1992 this.checkResult = checkResult;
1993 this.scopeCounter = scopeCounter;
1994 }
1996 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, Scope.ScopeCounter scopeCounter) {
1997 return this.implFilter == scopeFilter &&
1998 this.checkResult == checkResult &&
1999 this.scopeCounter.val() >= scopeCounter.val();
2000 }
2001 }
2003 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter, Scope.ScopeCounter scopeCounter) {
2004 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2005 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2006 if (cache == null) {
2007 cache = new HashMap<TypeSymbol, Entry>();
2008 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2009 }
2010 Entry e = cache.get(origin);
2011 if (e == null ||
2012 !e.matches(implFilter, checkResult, scopeCounter)) {
2013 MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter);
2014 cache.put(origin, new Entry(impl, implFilter, checkResult, scopeCounter));
2015 return impl;
2016 }
2017 else {
2018 return e.cachedImpl;
2019 }
2020 }
2022 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
2023 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
2024 while (t.tag == TYPEVAR)
2025 t = t.getUpperBound();
2026 TypeSymbol c = t.tsym;
2027 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2028 e.scope != null;
2029 e = e.next()) {
2030 if (e.sym != null &&
2031 e.sym.overrides(ms, origin, types, checkResult))
2032 return (MethodSymbol)e.sym;
2033 }
2034 }
2035 return null;
2036 }
2037 }
2039 private ImplementationCache implCache = new ImplementationCache();
2041 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
2042 return implCache.get(ms, origin, checkResult, implFilter, scopeCounter);
2043 }
2044 // </editor-fold>
2046 /**
2047 * Does t have the same arguments as s? It is assumed that both
2048 * types are (possibly polymorphic) method types. Monomorphic
2049 * method types "have the same arguments", if their argument lists
2050 * are equal. Polymorphic method types "have the same arguments",
2051 * if they have the same arguments after renaming all type
2052 * variables of one to corresponding type variables in the other,
2053 * where correspondence is by position in the type parameter list.
2054 */
2055 public boolean hasSameArgs(Type t, Type s) {
2056 return hasSameArgs.visit(t, s);
2057 }
2058 // where
2059 private TypeRelation hasSameArgs = new TypeRelation() {
2061 public Boolean visitType(Type t, Type s) {
2062 throw new AssertionError();
2063 }
2065 @Override
2066 public Boolean visitMethodType(MethodType t, Type s) {
2067 return s.tag == METHOD
2068 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2069 }
2071 @Override
2072 public Boolean visitForAll(ForAll t, Type s) {
2073 if (s.tag != FORALL)
2074 return false;
2076 ForAll forAll = (ForAll)s;
2077 return hasSameBounds(t, forAll)
2078 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2079 }
2081 @Override
2082 public Boolean visitErrorType(ErrorType t, Type s) {
2083 return false;
2084 }
2085 };
2086 // </editor-fold>
2088 // <editor-fold defaultstate="collapsed" desc="subst">
2089 public List<Type> subst(List<Type> ts,
2090 List<Type> from,
2091 List<Type> to) {
2092 return new Subst(from, to).subst(ts);
2093 }
2095 /**
2096 * Substitute all occurrences of a type in `from' with the
2097 * corresponding type in `to' in 't'. Match lists `from' and `to'
2098 * from the right: If lists have different length, discard leading
2099 * elements of the longer list.
2100 */
2101 public Type subst(Type t, List<Type> from, List<Type> to) {
2102 return new Subst(from, to).subst(t);
2103 }
2105 private class Subst extends UnaryVisitor<Type> {
2106 List<Type> from;
2107 List<Type> to;
2109 public Subst(List<Type> from, List<Type> to) {
2110 int fromLength = from.length();
2111 int toLength = to.length();
2112 while (fromLength > toLength) {
2113 fromLength--;
2114 from = from.tail;
2115 }
2116 while (fromLength < toLength) {
2117 toLength--;
2118 to = to.tail;
2119 }
2120 this.from = from;
2121 this.to = to;
2122 }
2124 Type subst(Type t) {
2125 if (from.tail == null)
2126 return t;
2127 else
2128 return visit(t);
2129 }
2131 List<Type> subst(List<Type> ts) {
2132 if (from.tail == null)
2133 return ts;
2134 boolean wild = false;
2135 if (ts.nonEmpty() && from.nonEmpty()) {
2136 Type head1 = subst(ts.head);
2137 List<Type> tail1 = subst(ts.tail);
2138 if (head1 != ts.head || tail1 != ts.tail)
2139 return tail1.prepend(head1);
2140 }
2141 return ts;
2142 }
2144 public Type visitType(Type t, Void ignored) {
2145 return t;
2146 }
2148 @Override
2149 public Type visitMethodType(MethodType t, Void ignored) {
2150 List<Type> argtypes = subst(t.argtypes);
2151 Type restype = subst(t.restype);
2152 List<Type> thrown = subst(t.thrown);
2153 if (argtypes == t.argtypes &&
2154 restype == t.restype &&
2155 thrown == t.thrown)
2156 return t;
2157 else
2158 return new MethodType(argtypes, restype, thrown, t.tsym);
2159 }
2161 @Override
2162 public Type visitTypeVar(TypeVar t, Void ignored) {
2163 for (List<Type> from = this.from, to = this.to;
2164 from.nonEmpty();
2165 from = from.tail, to = to.tail) {
2166 if (t == from.head) {
2167 return to.head.withTypeVar(t);
2168 }
2169 }
2170 return t;
2171 }
2173 @Override
2174 public Type visitClassType(ClassType t, Void ignored) {
2175 if (!t.isCompound()) {
2176 List<Type> typarams = t.getTypeArguments();
2177 List<Type> typarams1 = subst(typarams);
2178 Type outer = t.getEnclosingType();
2179 Type outer1 = subst(outer);
2180 if (typarams1 == typarams && outer1 == outer)
2181 return t;
2182 else
2183 return new ClassType(outer1, typarams1, t.tsym);
2184 } else {
2185 Type st = subst(supertype(t));
2186 List<Type> is = upperBounds(subst(interfaces(t)));
2187 if (st == supertype(t) && is == interfaces(t))
2188 return t;
2189 else
2190 return makeCompoundType(is.prepend(st));
2191 }
2192 }
2194 @Override
2195 public Type visitWildcardType(WildcardType t, Void ignored) {
2196 Type bound = t.type;
2197 if (t.kind != BoundKind.UNBOUND)
2198 bound = subst(bound);
2199 if (bound == t.type) {
2200 return t;
2201 } else {
2202 if (t.isExtendsBound() && bound.isExtendsBound())
2203 bound = upperBound(bound);
2204 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2205 }
2206 }
2208 @Override
2209 public Type visitArrayType(ArrayType t, Void ignored) {
2210 Type elemtype = subst(t.elemtype);
2211 if (elemtype == t.elemtype)
2212 return t;
2213 else
2214 return new ArrayType(upperBound(elemtype), t.tsym);
2215 }
2217 @Override
2218 public Type visitForAll(ForAll t, Void ignored) {
2219 List<Type> tvars1 = substBounds(t.tvars, from, to);
2220 Type qtype1 = subst(t.qtype);
2221 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2222 return t;
2223 } else if (tvars1 == t.tvars) {
2224 return new ForAll(tvars1, qtype1);
2225 } else {
2226 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2227 }
2228 }
2230 @Override
2231 public Type visitErrorType(ErrorType t, Void ignored) {
2232 return t;
2233 }
2234 }
2236 public List<Type> substBounds(List<Type> tvars,
2237 List<Type> from,
2238 List<Type> to) {
2239 if (tvars.isEmpty())
2240 return tvars;
2241 ListBuffer<Type> newBoundsBuf = lb();
2242 boolean changed = false;
2243 // calculate new bounds
2244 for (Type t : tvars) {
2245 TypeVar tv = (TypeVar) t;
2246 Type bound = subst(tv.bound, from, to);
2247 if (bound != tv.bound)
2248 changed = true;
2249 newBoundsBuf.append(bound);
2250 }
2251 if (!changed)
2252 return tvars;
2253 ListBuffer<Type> newTvars = lb();
2254 // create new type variables without bounds
2255 for (Type t : tvars) {
2256 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2257 }
2258 // the new bounds should use the new type variables in place
2259 // of the old
2260 List<Type> newBounds = newBoundsBuf.toList();
2261 from = tvars;
2262 to = newTvars.toList();
2263 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2264 newBounds.head = subst(newBounds.head, from, to);
2265 }
2266 newBounds = newBoundsBuf.toList();
2267 // set the bounds of new type variables to the new bounds
2268 for (Type t : newTvars.toList()) {
2269 TypeVar tv = (TypeVar) t;
2270 tv.bound = newBounds.head;
2271 newBounds = newBounds.tail;
2272 }
2273 return newTvars.toList();
2274 }
2276 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2277 Type bound1 = subst(t.bound, from, to);
2278 if (bound1 == t.bound)
2279 return t;
2280 else {
2281 // create new type variable without bounds
2282 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2283 // the new bound should use the new type variable in place
2284 // of the old
2285 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2286 return tv;
2287 }
2288 }
2289 // </editor-fold>
2291 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2292 /**
2293 * Does t have the same bounds for quantified variables as s?
2294 */
2295 boolean hasSameBounds(ForAll t, ForAll s) {
2296 List<Type> l1 = t.tvars;
2297 List<Type> l2 = s.tvars;
2298 while (l1.nonEmpty() && l2.nonEmpty() &&
2299 isSameType(l1.head.getUpperBound(),
2300 subst(l2.head.getUpperBound(),
2301 s.tvars,
2302 t.tvars))) {
2303 l1 = l1.tail;
2304 l2 = l2.tail;
2305 }
2306 return l1.isEmpty() && l2.isEmpty();
2307 }
2308 // </editor-fold>
2310 // <editor-fold defaultstate="collapsed" desc="newInstances">
2311 /** Create new vector of type variables from list of variables
2312 * changing all recursive bounds from old to new list.
2313 */
2314 public List<Type> newInstances(List<Type> tvars) {
2315 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2316 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2317 TypeVar tv = (TypeVar) l.head;
2318 tv.bound = subst(tv.bound, tvars, tvars1);
2319 }
2320 return tvars1;
2321 }
2322 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2323 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2324 };
2325 // </editor-fold>
2327 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2328 public Type createErrorType(Type originalType) {
2329 return new ErrorType(originalType, syms.errSymbol);
2330 }
2332 public Type createErrorType(ClassSymbol c, Type originalType) {
2333 return new ErrorType(c, originalType);
2334 }
2336 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2337 return new ErrorType(name, container, originalType);
2338 }
2339 // </editor-fold>
2341 // <editor-fold defaultstate="collapsed" desc="rank">
2342 /**
2343 * The rank of a class is the length of the longest path between
2344 * the class and java.lang.Object in the class inheritance
2345 * graph. Undefined for all but reference types.
2346 */
2347 public int rank(Type t) {
2348 switch(t.tag) {
2349 case CLASS: {
2350 ClassType cls = (ClassType)t;
2351 if (cls.rank_field < 0) {
2352 Name fullname = cls.tsym.getQualifiedName();
2353 if (fullname == names.java_lang_Object)
2354 cls.rank_field = 0;
2355 else {
2356 int r = rank(supertype(cls));
2357 for (List<Type> l = interfaces(cls);
2358 l.nonEmpty();
2359 l = l.tail) {
2360 if (rank(l.head) > r)
2361 r = rank(l.head);
2362 }
2363 cls.rank_field = r + 1;
2364 }
2365 }
2366 return cls.rank_field;
2367 }
2368 case TYPEVAR: {
2369 TypeVar tvar = (TypeVar)t;
2370 if (tvar.rank_field < 0) {
2371 int r = rank(supertype(tvar));
2372 for (List<Type> l = interfaces(tvar);
2373 l.nonEmpty();
2374 l = l.tail) {
2375 if (rank(l.head) > r) r = rank(l.head);
2376 }
2377 tvar.rank_field = r + 1;
2378 }
2379 return tvar.rank_field;
2380 }
2381 case ERROR:
2382 return 0;
2383 default:
2384 throw new AssertionError();
2385 }
2386 }
2387 // </editor-fold>
2389 /**
2390 * Helper method for generating a string representation of a given type
2391 * accordingly to a given locale
2392 */
2393 public String toString(Type t, Locale locale) {
2394 return Printer.createStandardPrinter(messages).visit(t, locale);
2395 }
2397 /**
2398 * Helper method for generating a string representation of a given type
2399 * accordingly to a given locale
2400 */
2401 public String toString(Symbol t, Locale locale) {
2402 return Printer.createStandardPrinter(messages).visit(t, locale);
2403 }
2405 // <editor-fold defaultstate="collapsed" desc="toString">
2406 /**
2407 * This toString is slightly more descriptive than the one on Type.
2408 *
2409 * @deprecated Types.toString(Type t, Locale l) provides better support
2410 * for localization
2411 */
2412 @Deprecated
2413 public String toString(Type t) {
2414 if (t.tag == FORALL) {
2415 ForAll forAll = (ForAll)t;
2416 return typaramsString(forAll.tvars) + forAll.qtype;
2417 }
2418 return "" + t;
2419 }
2420 // where
2421 private String typaramsString(List<Type> tvars) {
2422 StringBuffer s = new StringBuffer();
2423 s.append('<');
2424 boolean first = true;
2425 for (Type t : tvars) {
2426 if (!first) s.append(", ");
2427 first = false;
2428 appendTyparamString(((TypeVar)t), s);
2429 }
2430 s.append('>');
2431 return s.toString();
2432 }
2433 private void appendTyparamString(TypeVar t, StringBuffer buf) {
2434 buf.append(t);
2435 if (t.bound == null ||
2436 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2437 return;
2438 buf.append(" extends "); // Java syntax; no need for i18n
2439 Type bound = t.bound;
2440 if (!bound.isCompound()) {
2441 buf.append(bound);
2442 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2443 buf.append(supertype(t));
2444 for (Type intf : interfaces(t)) {
2445 buf.append('&');
2446 buf.append(intf);
2447 }
2448 } else {
2449 // No superclass was given in bounds.
2450 // In this case, supertype is Object, erasure is first interface.
2451 boolean first = true;
2452 for (Type intf : interfaces(t)) {
2453 if (!first) buf.append('&');
2454 first = false;
2455 buf.append(intf);
2456 }
2457 }
2458 }
2459 // </editor-fold>
2461 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2462 /**
2463 * A cache for closures.
2464 *
2465 * <p>A closure is a list of all the supertypes and interfaces of
2466 * a class or interface type, ordered by ClassSymbol.precedes
2467 * (that is, subclasses come first, arbitrary but fixed
2468 * otherwise).
2469 */
2470 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2472 /**
2473 * Returns the closure of a class or interface type.
2474 */
2475 public List<Type> closure(Type t) {
2476 List<Type> cl = closureCache.get(t);
2477 if (cl == null) {
2478 Type st = supertype(t);
2479 if (!t.isCompound()) {
2480 if (st.tag == CLASS) {
2481 cl = insert(closure(st), t);
2482 } else if (st.tag == TYPEVAR) {
2483 cl = closure(st).prepend(t);
2484 } else {
2485 cl = List.of(t);
2486 }
2487 } else {
2488 cl = closure(supertype(t));
2489 }
2490 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2491 cl = union(cl, closure(l.head));
2492 closureCache.put(t, cl);
2493 }
2494 return cl;
2495 }
2497 /**
2498 * Insert a type in a closure
2499 */
2500 public List<Type> insert(List<Type> cl, Type t) {
2501 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2502 return cl.prepend(t);
2503 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2504 return insert(cl.tail, t).prepend(cl.head);
2505 } else {
2506 return cl;
2507 }
2508 }
2510 /**
2511 * Form the union of two closures
2512 */
2513 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2514 if (cl1.isEmpty()) {
2515 return cl2;
2516 } else if (cl2.isEmpty()) {
2517 return cl1;
2518 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2519 return union(cl1.tail, cl2).prepend(cl1.head);
2520 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2521 return union(cl1, cl2.tail).prepend(cl2.head);
2522 } else {
2523 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2524 }
2525 }
2527 /**
2528 * Intersect two closures
2529 */
2530 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2531 if (cl1 == cl2)
2532 return cl1;
2533 if (cl1.isEmpty() || cl2.isEmpty())
2534 return List.nil();
2535 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2536 return intersect(cl1.tail, cl2);
2537 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2538 return intersect(cl1, cl2.tail);
2539 if (isSameType(cl1.head, cl2.head))
2540 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2541 if (cl1.head.tsym == cl2.head.tsym &&
2542 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2543 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2544 Type merge = merge(cl1.head,cl2.head);
2545 return intersect(cl1.tail, cl2.tail).prepend(merge);
2546 }
2547 if (cl1.head.isRaw() || cl2.head.isRaw())
2548 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2549 }
2550 return intersect(cl1.tail, cl2.tail);
2551 }
2552 // where
2553 class TypePair {
2554 final Type t1;
2555 final Type t2;
2556 TypePair(Type t1, Type t2) {
2557 this.t1 = t1;
2558 this.t2 = t2;
2559 }
2560 @Override
2561 public int hashCode() {
2562 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2563 }
2564 @Override
2565 public boolean equals(Object obj) {
2566 if (!(obj instanceof TypePair))
2567 return false;
2568 TypePair typePair = (TypePair)obj;
2569 return isSameType(t1, typePair.t1)
2570 && isSameType(t2, typePair.t2);
2571 }
2572 }
2573 Set<TypePair> mergeCache = new HashSet<TypePair>();
2574 private Type merge(Type c1, Type c2) {
2575 ClassType class1 = (ClassType) c1;
2576 List<Type> act1 = class1.getTypeArguments();
2577 ClassType class2 = (ClassType) c2;
2578 List<Type> act2 = class2.getTypeArguments();
2579 ListBuffer<Type> merged = new ListBuffer<Type>();
2580 List<Type> typarams = class1.tsym.type.getTypeArguments();
2582 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2583 if (containsType(act1.head, act2.head)) {
2584 merged.append(act1.head);
2585 } else if (containsType(act2.head, act1.head)) {
2586 merged.append(act2.head);
2587 } else {
2588 TypePair pair = new TypePair(c1, c2);
2589 Type m;
2590 if (mergeCache.add(pair)) {
2591 m = new WildcardType(lub(upperBound(act1.head),
2592 upperBound(act2.head)),
2593 BoundKind.EXTENDS,
2594 syms.boundClass);
2595 mergeCache.remove(pair);
2596 } else {
2597 m = new WildcardType(syms.objectType,
2598 BoundKind.UNBOUND,
2599 syms.boundClass);
2600 }
2601 merged.append(m.withTypeVar(typarams.head));
2602 }
2603 act1 = act1.tail;
2604 act2 = act2.tail;
2605 typarams = typarams.tail;
2606 }
2607 assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2608 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2609 }
2611 /**
2612 * Return the minimum type of a closure, a compound type if no
2613 * unique minimum exists.
2614 */
2615 private Type compoundMin(List<Type> cl) {
2616 if (cl.isEmpty()) return syms.objectType;
2617 List<Type> compound = closureMin(cl);
2618 if (compound.isEmpty())
2619 return null;
2620 else if (compound.tail.isEmpty())
2621 return compound.head;
2622 else
2623 return makeCompoundType(compound);
2624 }
2626 /**
2627 * Return the minimum types of a closure, suitable for computing
2628 * compoundMin or glb.
2629 */
2630 private List<Type> closureMin(List<Type> cl) {
2631 ListBuffer<Type> classes = lb();
2632 ListBuffer<Type> interfaces = lb();
2633 while (!cl.isEmpty()) {
2634 Type current = cl.head;
2635 if (current.isInterface())
2636 interfaces.append(current);
2637 else
2638 classes.append(current);
2639 ListBuffer<Type> candidates = lb();
2640 for (Type t : cl.tail) {
2641 if (!isSubtypeNoCapture(current, t))
2642 candidates.append(t);
2643 }
2644 cl = candidates.toList();
2645 }
2646 return classes.appendList(interfaces).toList();
2647 }
2649 /**
2650 * Return the least upper bound of pair of types. if the lub does
2651 * not exist return null.
2652 */
2653 public Type lub(Type t1, Type t2) {
2654 return lub(List.of(t1, t2));
2655 }
2657 /**
2658 * Return the least upper bound (lub) of set of types. If the lub
2659 * does not exist return the type of null (bottom).
2660 */
2661 public Type lub(List<Type> ts) {
2662 final int ARRAY_BOUND = 1;
2663 final int CLASS_BOUND = 2;
2664 int boundkind = 0;
2665 for (Type t : ts) {
2666 switch (t.tag) {
2667 case CLASS:
2668 boundkind |= CLASS_BOUND;
2669 break;
2670 case ARRAY:
2671 boundkind |= ARRAY_BOUND;
2672 break;
2673 case TYPEVAR:
2674 do {
2675 t = t.getUpperBound();
2676 } while (t.tag == TYPEVAR);
2677 if (t.tag == ARRAY) {
2678 boundkind |= ARRAY_BOUND;
2679 } else {
2680 boundkind |= CLASS_BOUND;
2681 }
2682 break;
2683 default:
2684 if (t.isPrimitive())
2685 return syms.errType;
2686 }
2687 }
2688 switch (boundkind) {
2689 case 0:
2690 return syms.botType;
2692 case ARRAY_BOUND:
2693 // calculate lub(A[], B[])
2694 List<Type> elements = Type.map(ts, elemTypeFun);
2695 for (Type t : elements) {
2696 if (t.isPrimitive()) {
2697 // if a primitive type is found, then return
2698 // arraySuperType unless all the types are the
2699 // same
2700 Type first = ts.head;
2701 for (Type s : ts.tail) {
2702 if (!isSameType(first, s)) {
2703 // lub(int[], B[]) is Cloneable & Serializable
2704 return arraySuperType();
2705 }
2706 }
2707 // all the array types are the same, return one
2708 // lub(int[], int[]) is int[]
2709 return first;
2710 }
2711 }
2712 // lub(A[], B[]) is lub(A, B)[]
2713 return new ArrayType(lub(elements), syms.arrayClass);
2715 case CLASS_BOUND:
2716 // calculate lub(A, B)
2717 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2718 ts = ts.tail;
2719 assert !ts.isEmpty();
2720 List<Type> cl = closure(ts.head);
2721 for (Type t : ts.tail) {
2722 if (t.tag == CLASS || t.tag == TYPEVAR)
2723 cl = intersect(cl, closure(t));
2724 }
2725 return compoundMin(cl);
2727 default:
2728 // calculate lub(A, B[])
2729 List<Type> classes = List.of(arraySuperType());
2730 for (Type t : ts) {
2731 if (t.tag != ARRAY) // Filter out any arrays
2732 classes = classes.prepend(t);
2733 }
2734 // lub(A, B[]) is lub(A, arraySuperType)
2735 return lub(classes);
2736 }
2737 }
2738 // where
2739 private Type arraySuperType = null;
2740 private Type arraySuperType() {
2741 // initialized lazily to avoid problems during compiler startup
2742 if (arraySuperType == null) {
2743 synchronized (this) {
2744 if (arraySuperType == null) {
2745 // JLS 10.8: all arrays implement Cloneable and Serializable.
2746 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2747 syms.cloneableType),
2748 syms.objectType);
2749 }
2750 }
2751 }
2752 return arraySuperType;
2753 }
2754 // </editor-fold>
2756 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2757 public Type glb(List<Type> ts) {
2758 Type t1 = ts.head;
2759 for (Type t2 : ts.tail) {
2760 if (t1.isErroneous())
2761 return t1;
2762 t1 = glb(t1, t2);
2763 }
2764 return t1;
2765 }
2766 //where
2767 public Type glb(Type t, Type s) {
2768 if (s == null)
2769 return t;
2770 else if (t.isPrimitive() || s.isPrimitive())
2771 return syms.errType;
2772 else if (isSubtypeNoCapture(t, s))
2773 return t;
2774 else if (isSubtypeNoCapture(s, t))
2775 return s;
2777 List<Type> closure = union(closure(t), closure(s));
2778 List<Type> bounds = closureMin(closure);
2780 if (bounds.isEmpty()) { // length == 0
2781 return syms.objectType;
2782 } else if (bounds.tail.isEmpty()) { // length == 1
2783 return bounds.head;
2784 } else { // length > 1
2785 int classCount = 0;
2786 for (Type bound : bounds)
2787 if (!bound.isInterface())
2788 classCount++;
2789 if (classCount > 1)
2790 return createErrorType(t);
2791 }
2792 return makeCompoundType(bounds);
2793 }
2794 // </editor-fold>
2796 // <editor-fold defaultstate="collapsed" desc="hashCode">
2797 /**
2798 * Compute a hash code on a type.
2799 */
2800 public static int hashCode(Type t) {
2801 return hashCode.visit(t);
2802 }
2803 // where
2804 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
2806 public Integer visitType(Type t, Void ignored) {
2807 return t.tag;
2808 }
2810 @Override
2811 public Integer visitClassType(ClassType t, Void ignored) {
2812 int result = visit(t.getEnclosingType());
2813 result *= 127;
2814 result += t.tsym.flatName().hashCode();
2815 for (Type s : t.getTypeArguments()) {
2816 result *= 127;
2817 result += visit(s);
2818 }
2819 return result;
2820 }
2822 @Override
2823 public Integer visitWildcardType(WildcardType t, Void ignored) {
2824 int result = t.kind.hashCode();
2825 if (t.type != null) {
2826 result *= 127;
2827 result += visit(t.type);
2828 }
2829 return result;
2830 }
2832 @Override
2833 public Integer visitArrayType(ArrayType t, Void ignored) {
2834 return visit(t.elemtype) + 12;
2835 }
2837 @Override
2838 public Integer visitTypeVar(TypeVar t, Void ignored) {
2839 return System.identityHashCode(t.tsym);
2840 }
2842 @Override
2843 public Integer visitUndetVar(UndetVar t, Void ignored) {
2844 return System.identityHashCode(t);
2845 }
2847 @Override
2848 public Integer visitErrorType(ErrorType t, Void ignored) {
2849 return 0;
2850 }
2851 };
2852 // </editor-fold>
2854 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
2855 /**
2856 * Does t have a result that is a subtype of the result type of s,
2857 * suitable for covariant returns? It is assumed that both types
2858 * are (possibly polymorphic) method types. Monomorphic method
2859 * types are handled in the obvious way. Polymorphic method types
2860 * require renaming all type variables of one to corresponding
2861 * type variables in the other, where correspondence is by
2862 * position in the type parameter list. */
2863 public boolean resultSubtype(Type t, Type s, Warner warner) {
2864 List<Type> tvars = t.getTypeArguments();
2865 List<Type> svars = s.getTypeArguments();
2866 Type tres = t.getReturnType();
2867 Type sres = subst(s.getReturnType(), svars, tvars);
2868 return covariantReturnType(tres, sres, warner);
2869 }
2871 /**
2872 * Return-Type-Substitutable.
2873 * @see <a href="http://java.sun.com/docs/books/jls/">The Java
2874 * Language Specification, Third Ed. (8.4.5)</a>
2875 */
2876 public boolean returnTypeSubstitutable(Type r1, Type r2) {
2877 if (hasSameArgs(r1, r2))
2878 return resultSubtype(r1, r2, Warner.noWarnings);
2879 else
2880 return covariantReturnType(r1.getReturnType(),
2881 erasure(r2.getReturnType()),
2882 Warner.noWarnings);
2883 }
2885 public boolean returnTypeSubstitutable(Type r1,
2886 Type r2, Type r2res,
2887 Warner warner) {
2888 if (isSameType(r1.getReturnType(), r2res))
2889 return true;
2890 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
2891 return false;
2893 if (hasSameArgs(r1, r2))
2894 return covariantReturnType(r1.getReturnType(), r2res, warner);
2895 if (!source.allowCovariantReturns())
2896 return false;
2897 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
2898 return true;
2899 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
2900 return false;
2901 warner.warnUnchecked();
2902 return true;
2903 }
2905 /**
2906 * Is t an appropriate return type in an overrider for a
2907 * method that returns s?
2908 */
2909 public boolean covariantReturnType(Type t, Type s, Warner warner) {
2910 return
2911 isSameType(t, s) ||
2912 source.allowCovariantReturns() &&
2913 !t.isPrimitive() &&
2914 !s.isPrimitive() &&
2915 isAssignable(t, s, warner);
2916 }
2917 // </editor-fold>
2919 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
2920 /**
2921 * Return the class that boxes the given primitive.
2922 */
2923 public ClassSymbol boxedClass(Type t) {
2924 return reader.enterClass(syms.boxedName[t.tag]);
2925 }
2927 /**
2928 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
2929 */
2930 public Type boxedTypeOrType(Type t) {
2931 return t.isPrimitive() ?
2932 boxedClass(t).type :
2933 t;
2934 }
2936 /**
2937 * Return the primitive type corresponding to a boxed type.
2938 */
2939 public Type unboxedType(Type t) {
2940 if (allowBoxing) {
2941 for (int i=0; i<syms.boxedName.length; i++) {
2942 Name box = syms.boxedName[i];
2943 if (box != null &&
2944 asSuper(t, reader.enterClass(box)) != null)
2945 return syms.typeOfTag[i];
2946 }
2947 }
2948 return Type.noType;
2949 }
2950 // </editor-fold>
2952 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
2953 /*
2954 * JLS 3rd Ed. 5.1.10 Capture Conversion:
2955 *
2956 * Let G name a generic type declaration with n formal type
2957 * parameters A1 ... An with corresponding bounds U1 ... Un. There
2958 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
2959 * where, for 1 <= i <= n:
2960 *
2961 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
2962 * Si is a fresh type variable whose upper bound is
2963 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
2964 * type.
2965 *
2966 * + If Ti is a wildcard type argument of the form ? extends Bi,
2967 * then Si is a fresh type variable whose upper bound is
2968 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
2969 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
2970 * a compile-time error if for any two classes (not interfaces)
2971 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
2972 *
2973 * + If Ti is a wildcard type argument of the form ? super Bi,
2974 * then Si is a fresh type variable whose upper bound is
2975 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
2976 *
2977 * + Otherwise, Si = Ti.
2978 *
2979 * Capture conversion on any type other than a parameterized type
2980 * (4.5) acts as an identity conversion (5.1.1). Capture
2981 * conversions never require a special action at run time and
2982 * therefore never throw an exception at run time.
2983 *
2984 * Capture conversion is not applied recursively.
2985 */
2986 /**
2987 * Capture conversion as specified by JLS 3rd Ed.
2988 */
2990 public List<Type> capture(List<Type> ts) {
2991 List<Type> buf = List.nil();
2992 for (Type t : ts) {
2993 buf = buf.prepend(capture(t));
2994 }
2995 return buf.reverse();
2996 }
2997 public Type capture(Type t) {
2998 if (t.tag != CLASS)
2999 return t;
3000 if (t.getEnclosingType() != Type.noType) {
3001 Type capturedEncl = capture(t.getEnclosingType());
3002 if (capturedEncl != t.getEnclosingType()) {
3003 Type type1 = memberType(capturedEncl, t.tsym);
3004 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3005 }
3006 }
3007 ClassType cls = (ClassType)t;
3008 if (cls.isRaw() || !cls.isParameterized())
3009 return cls;
3011 ClassType G = (ClassType)cls.asElement().asType();
3012 List<Type> A = G.getTypeArguments();
3013 List<Type> T = cls.getTypeArguments();
3014 List<Type> S = freshTypeVariables(T);
3016 List<Type> currentA = A;
3017 List<Type> currentT = T;
3018 List<Type> currentS = S;
3019 boolean captured = false;
3020 while (!currentA.isEmpty() &&
3021 !currentT.isEmpty() &&
3022 !currentS.isEmpty()) {
3023 if (currentS.head != currentT.head) {
3024 captured = true;
3025 WildcardType Ti = (WildcardType)currentT.head;
3026 Type Ui = currentA.head.getUpperBound();
3027 CapturedType Si = (CapturedType)currentS.head;
3028 if (Ui == null)
3029 Ui = syms.objectType;
3030 switch (Ti.kind) {
3031 case UNBOUND:
3032 Si.bound = subst(Ui, A, S);
3033 Si.lower = syms.botType;
3034 break;
3035 case EXTENDS:
3036 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3037 Si.lower = syms.botType;
3038 break;
3039 case SUPER:
3040 Si.bound = subst(Ui, A, S);
3041 Si.lower = Ti.getSuperBound();
3042 break;
3043 }
3044 if (Si.bound == Si.lower)
3045 currentS.head = Si.bound;
3046 }
3047 currentA = currentA.tail;
3048 currentT = currentT.tail;
3049 currentS = currentS.tail;
3050 }
3051 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3052 return erasure(t); // some "rare" type involved
3054 if (captured)
3055 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3056 else
3057 return t;
3058 }
3059 // where
3060 public List<Type> freshTypeVariables(List<Type> types) {
3061 ListBuffer<Type> result = lb();
3062 for (Type t : types) {
3063 if (t.tag == WILDCARD) {
3064 Type bound = ((WildcardType)t).getExtendsBound();
3065 if (bound == null)
3066 bound = syms.objectType;
3067 result.append(new CapturedType(capturedName,
3068 syms.noSymbol,
3069 bound,
3070 syms.botType,
3071 (WildcardType)t));
3072 } else {
3073 result.append(t);
3074 }
3075 }
3076 return result.toList();
3077 }
3078 // </editor-fold>
3080 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3081 private List<Type> upperBounds(List<Type> ss) {
3082 if (ss.isEmpty()) return ss;
3083 Type head = upperBound(ss.head);
3084 List<Type> tail = upperBounds(ss.tail);
3085 if (head != ss.head || tail != ss.tail)
3086 return tail.prepend(head);
3087 else
3088 return ss;
3089 }
3091 private boolean sideCast(Type from, Type to, Warner warn) {
3092 // We are casting from type $from$ to type $to$, which are
3093 // non-final unrelated types. This method
3094 // tries to reject a cast by transferring type parameters
3095 // from $to$ to $from$ by common superinterfaces.
3096 boolean reverse = false;
3097 Type target = to;
3098 if ((to.tsym.flags() & INTERFACE) == 0) {
3099 assert (from.tsym.flags() & INTERFACE) != 0;
3100 reverse = true;
3101 to = from;
3102 from = target;
3103 }
3104 List<Type> commonSupers = superClosure(to, erasure(from));
3105 boolean giveWarning = commonSupers.isEmpty();
3106 // The arguments to the supers could be unified here to
3107 // get a more accurate analysis
3108 while (commonSupers.nonEmpty()) {
3109 Type t1 = asSuper(from, commonSupers.head.tsym);
3110 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3111 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3112 return false;
3113 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3114 commonSupers = commonSupers.tail;
3115 }
3116 if (giveWarning && !isReifiable(reverse ? from : to))
3117 warn.warnUnchecked();
3118 if (!source.allowCovariantReturns())
3119 // reject if there is a common method signature with
3120 // incompatible return types.
3121 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3122 return true;
3123 }
3125 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3126 // We are casting from type $from$ to type $to$, which are
3127 // unrelated types one of which is final and the other of
3128 // which is an interface. This method
3129 // tries to reject a cast by transferring type parameters
3130 // from the final class to the interface.
3131 boolean reverse = false;
3132 Type target = to;
3133 if ((to.tsym.flags() & INTERFACE) == 0) {
3134 assert (from.tsym.flags() & INTERFACE) != 0;
3135 reverse = true;
3136 to = from;
3137 from = target;
3138 }
3139 assert (from.tsym.flags() & FINAL) != 0;
3140 Type t1 = asSuper(from, to.tsym);
3141 if (t1 == null) return false;
3142 Type t2 = to;
3143 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3144 return false;
3145 if (!source.allowCovariantReturns())
3146 // reject if there is a common method signature with
3147 // incompatible return types.
3148 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3149 if (!isReifiable(target) &&
3150 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3151 warn.warnUnchecked();
3152 return true;
3153 }
3155 private boolean giveWarning(Type from, Type to) {
3156 Type subFrom = asSub(from, to.tsym);
3157 return to.isParameterized() &&
3158 (!(isUnbounded(to) ||
3159 isSubtype(from, to) ||
3160 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3161 }
3163 private List<Type> superClosure(Type t, Type s) {
3164 List<Type> cl = List.nil();
3165 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3166 if (isSubtype(s, erasure(l.head))) {
3167 cl = insert(cl, l.head);
3168 } else {
3169 cl = union(cl, superClosure(l.head, s));
3170 }
3171 }
3172 return cl;
3173 }
3175 private boolean containsTypeEquivalent(Type t, Type s) {
3176 return
3177 isSameType(t, s) || // shortcut
3178 containsType(t, s) && containsType(s, t);
3179 }
3181 // <editor-fold defaultstate="collapsed" desc="adapt">
3182 /**
3183 * Adapt a type by computing a substitution which maps a source
3184 * type to a target type.
3185 *
3186 * @param source the source type
3187 * @param target the target type
3188 * @param from the type variables of the computed substitution
3189 * @param to the types of the computed substitution.
3190 */
3191 public void adapt(Type source,
3192 Type target,
3193 ListBuffer<Type> from,
3194 ListBuffer<Type> to) throws AdaptFailure {
3195 new Adapter(from, to).adapt(source, target);
3196 }
3198 class Adapter extends SimpleVisitor<Void, Type> {
3200 ListBuffer<Type> from;
3201 ListBuffer<Type> to;
3202 Map<Symbol,Type> mapping;
3204 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3205 this.from = from;
3206 this.to = to;
3207 mapping = new HashMap<Symbol,Type>();
3208 }
3210 public void adapt(Type source, Type target) throws AdaptFailure {
3211 visit(source, target);
3212 List<Type> fromList = from.toList();
3213 List<Type> toList = to.toList();
3214 while (!fromList.isEmpty()) {
3215 Type val = mapping.get(fromList.head.tsym);
3216 if (toList.head != val)
3217 toList.head = val;
3218 fromList = fromList.tail;
3219 toList = toList.tail;
3220 }
3221 }
3223 @Override
3224 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3225 if (target.tag == CLASS)
3226 adaptRecursive(source.allparams(), target.allparams());
3227 return null;
3228 }
3230 @Override
3231 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3232 if (target.tag == ARRAY)
3233 adaptRecursive(elemtype(source), elemtype(target));
3234 return null;
3235 }
3237 @Override
3238 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3239 if (source.isExtendsBound())
3240 adaptRecursive(upperBound(source), upperBound(target));
3241 else if (source.isSuperBound())
3242 adaptRecursive(lowerBound(source), lowerBound(target));
3243 return null;
3244 }
3246 @Override
3247 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3248 // Check to see if there is
3249 // already a mapping for $source$, in which case
3250 // the old mapping will be merged with the new
3251 Type val = mapping.get(source.tsym);
3252 if (val != null) {
3253 if (val.isSuperBound() && target.isSuperBound()) {
3254 val = isSubtype(lowerBound(val), lowerBound(target))
3255 ? target : val;
3256 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3257 val = isSubtype(upperBound(val), upperBound(target))
3258 ? val : target;
3259 } else if (!isSameType(val, target)) {
3260 throw new AdaptFailure();
3261 }
3262 } else {
3263 val = target;
3264 from.append(source);
3265 to.append(target);
3266 }
3267 mapping.put(source.tsym, val);
3268 return null;
3269 }
3271 @Override
3272 public Void visitType(Type source, Type target) {
3273 return null;
3274 }
3276 private Set<TypePair> cache = new HashSet<TypePair>();
3278 private void adaptRecursive(Type source, Type target) {
3279 TypePair pair = new TypePair(source, target);
3280 if (cache.add(pair)) {
3281 try {
3282 visit(source, target);
3283 } finally {
3284 cache.remove(pair);
3285 }
3286 }
3287 }
3289 private void adaptRecursive(List<Type> source, List<Type> target) {
3290 if (source.length() == target.length()) {
3291 while (source.nonEmpty()) {
3292 adaptRecursive(source.head, target.head);
3293 source = source.tail;
3294 target = target.tail;
3295 }
3296 }
3297 }
3298 }
3300 public static class AdaptFailure extends RuntimeException {
3301 static final long serialVersionUID = -7490231548272701566L;
3302 }
3304 private void adaptSelf(Type t,
3305 ListBuffer<Type> from,
3306 ListBuffer<Type> to) {
3307 try {
3308 //if (t.tsym.type != t)
3309 adapt(t.tsym.type, t, from, to);
3310 } catch (AdaptFailure ex) {
3311 // Adapt should never fail calculating a mapping from
3312 // t.tsym.type to t as there can be no merge problem.
3313 throw new AssertionError(ex);
3314 }
3315 }
3316 // </editor-fold>
3318 /**
3319 * Rewrite all type variables (universal quantifiers) in the given
3320 * type to wildcards (existential quantifiers). This is used to
3321 * determine if a cast is allowed. For example, if high is true
3322 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3323 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3324 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3325 * List<Integer>} with a warning.
3326 * @param t a type
3327 * @param high if true return an upper bound; otherwise a lower
3328 * bound
3329 * @param rewriteTypeVars only rewrite captured wildcards if false;
3330 * otherwise rewrite all type variables
3331 * @return the type rewritten with wildcards (existential
3332 * quantifiers) only
3333 */
3334 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3335 return new Rewriter(high, rewriteTypeVars).visit(t);
3336 }
3338 class Rewriter extends UnaryVisitor<Type> {
3340 boolean high;
3341 boolean rewriteTypeVars;
3343 Rewriter(boolean high, boolean rewriteTypeVars) {
3344 this.high = high;
3345 this.rewriteTypeVars = rewriteTypeVars;
3346 }
3348 @Override
3349 public Type visitClassType(ClassType t, Void s) {
3350 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3351 boolean changed = false;
3352 for (Type arg : t.allparams()) {
3353 Type bound = visit(arg);
3354 if (arg != bound) {
3355 changed = true;
3356 }
3357 rewritten.append(bound);
3358 }
3359 if (changed)
3360 return subst(t.tsym.type,
3361 t.tsym.type.allparams(),
3362 rewritten.toList());
3363 else
3364 return t;
3365 }
3367 public Type visitType(Type t, Void s) {
3368 return high ? upperBound(t) : lowerBound(t);
3369 }
3371 @Override
3372 public Type visitCapturedType(CapturedType t, Void s) {
3373 Type bound = visitWildcardType(t.wildcard, null);
3374 return (bound.contains(t)) ?
3375 erasure(bound) :
3376 bound;
3377 }
3379 @Override
3380 public Type visitTypeVar(TypeVar t, Void s) {
3381 if (rewriteTypeVars) {
3382 Type bound = high ?
3383 (t.bound.contains(t) ?
3384 erasure(t.bound) :
3385 visit(t.bound)) :
3386 syms.botType;
3387 return rewriteAsWildcardType(bound, t);
3388 }
3389 else
3390 return t;
3391 }
3393 @Override
3394 public Type visitWildcardType(WildcardType t, Void s) {
3395 Type bound = high ? t.getExtendsBound() :
3396 t.getSuperBound();
3397 if (bound == null)
3398 bound = high ? syms.objectType : syms.botType;
3399 return rewriteAsWildcardType(visit(bound), t.bound);
3400 }
3402 private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
3403 return high ?
3404 makeExtendsWildcard(B(bound), formal) :
3405 makeSuperWildcard(B(bound), formal);
3406 }
3408 Type B(Type t) {
3409 while (t.tag == WILDCARD) {
3410 WildcardType w = (WildcardType)t;
3411 t = high ?
3412 w.getExtendsBound() :
3413 w.getSuperBound();
3414 if (t == null) {
3415 t = high ? syms.objectType : syms.botType;
3416 }
3417 }
3418 return t;
3419 }
3420 }
3423 /**
3424 * Create a wildcard with the given upper (extends) bound; create
3425 * an unbounded wildcard if bound is Object.
3426 *
3427 * @param bound the upper bound
3428 * @param formal the formal type parameter that will be
3429 * substituted by the wildcard
3430 */
3431 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3432 if (bound == syms.objectType) {
3433 return new WildcardType(syms.objectType,
3434 BoundKind.UNBOUND,
3435 syms.boundClass,
3436 formal);
3437 } else {
3438 return new WildcardType(bound,
3439 BoundKind.EXTENDS,
3440 syms.boundClass,
3441 formal);
3442 }
3443 }
3445 /**
3446 * Create a wildcard with the given lower (super) bound; create an
3447 * unbounded wildcard if bound is bottom (type of {@code null}).
3448 *
3449 * @param bound the lower bound
3450 * @param formal the formal type parameter that will be
3451 * substituted by the wildcard
3452 */
3453 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3454 if (bound.tag == BOT) {
3455 return new WildcardType(syms.objectType,
3456 BoundKind.UNBOUND,
3457 syms.boundClass,
3458 formal);
3459 } else {
3460 return new WildcardType(bound,
3461 BoundKind.SUPER,
3462 syms.boundClass,
3463 formal);
3464 }
3465 }
3467 /**
3468 * A wrapper for a type that allows use in sets.
3469 */
3470 class SingletonType {
3471 final Type t;
3472 SingletonType(Type t) {
3473 this.t = t;
3474 }
3475 public int hashCode() {
3476 return Types.hashCode(t);
3477 }
3478 public boolean equals(Object obj) {
3479 return (obj instanceof SingletonType) &&
3480 isSameType(t, ((SingletonType)obj).t);
3481 }
3482 public String toString() {
3483 return t.toString();
3484 }
3485 }
3486 // </editor-fold>
3488 // <editor-fold defaultstate="collapsed" desc="Visitors">
3489 /**
3490 * A default visitor for types. All visitor methods except
3491 * visitType are implemented by delegating to visitType. Concrete
3492 * subclasses must provide an implementation of visitType and can
3493 * override other methods as needed.
3494 *
3495 * @param <R> the return type of the operation implemented by this
3496 * visitor; use Void if no return type is needed.
3497 * @param <S> the type of the second argument (the first being the
3498 * type itself) of the operation implemented by this visitor; use
3499 * Void if a second argument is not needed.
3500 */
3501 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3502 final public R visit(Type t, S s) { return t.accept(this, s); }
3503 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3504 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3505 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3506 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3507 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3508 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3509 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3510 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3511 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3512 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3513 }
3515 /**
3516 * A default visitor for symbols. All visitor methods except
3517 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3518 * subclasses must provide an implementation of visitSymbol and can
3519 * override other methods as needed.
3520 *
3521 * @param <R> the return type of the operation implemented by this
3522 * visitor; use Void if no return type is needed.
3523 * @param <S> the type of the second argument (the first being the
3524 * symbol itself) of the operation implemented by this visitor; use
3525 * Void if a second argument is not needed.
3526 */
3527 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3528 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3529 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3530 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3531 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3532 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3533 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3534 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3535 }
3537 /**
3538 * A <em>simple</em> visitor for types. This visitor is simple as
3539 * captured wildcards, for-all types (generic methods), and
3540 * undetermined type variables (part of inference) are hidden.
3541 * Captured wildcards are hidden by treating them as type
3542 * variables and the rest are hidden by visiting their qtypes.
3543 *
3544 * @param <R> the return type of the operation implemented by this
3545 * visitor; use Void if no return type is needed.
3546 * @param <S> the type of the second argument (the first being the
3547 * type itself) of the operation implemented by this visitor; use
3548 * Void if a second argument is not needed.
3549 */
3550 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3551 @Override
3552 public R visitCapturedType(CapturedType t, S s) {
3553 return visitTypeVar(t, s);
3554 }
3555 @Override
3556 public R visitForAll(ForAll t, S s) {
3557 return visit(t.qtype, s);
3558 }
3559 @Override
3560 public R visitUndetVar(UndetVar t, S s) {
3561 return visit(t.qtype, s);
3562 }
3563 }
3565 /**
3566 * A plain relation on types. That is a 2-ary function on the
3567 * form Type × Type → Boolean.
3568 * <!-- In plain text: Type x Type -> Boolean -->
3569 */
3570 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3572 /**
3573 * A convenience visitor for implementing operations that only
3574 * require one argument (the type itself), that is, unary
3575 * operations.
3576 *
3577 * @param <R> the return type of the operation implemented by this
3578 * visitor; use Void if no return type is needed.
3579 */
3580 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3581 final public R visit(Type t) { return t.accept(this, null); }
3582 }
3584 /**
3585 * A visitor for implementing a mapping from types to types. The
3586 * default behavior of this class is to implement the identity
3587 * mapping (mapping a type to itself). This can be overridden in
3588 * subclasses.
3589 *
3590 * @param <S> the type of the second argument (the first being the
3591 * type itself) of this mapping; use Void if a second argument is
3592 * not needed.
3593 */
3594 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3595 final public Type visit(Type t) { return t.accept(this, null); }
3596 public Type visitType(Type t, S s) { return t; }
3597 }
3598 // </editor-fold>
3601 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3603 public RetentionPolicy getRetention(Attribute.Compound a) {
3604 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3605 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3606 if (c != null) {
3607 Attribute value = c.member(names.value);
3608 if (value != null && value instanceof Attribute.Enum) {
3609 Name levelName = ((Attribute.Enum)value).value.name;
3610 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3611 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3612 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3613 else ;// /* fail soft */ throw new AssertionError(levelName);
3614 }
3615 }
3616 return vis;
3617 }
3618 // </editor-fold>
3619 }