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