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