Mon, 20 Aug 2012 21:24:10 +0530
7181320: javac NullPointerException for switch labels with cast to String expressions
Reviewed-by: mcimadamore
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 eraseNotNeeded(t)? t : erasure(t, false);
1593 }
1594 //where
1595 private boolean eraseNotNeeded(Type t) {
1596 // We don't want to erase primitive types and String type as that
1597 // operation is idempotent. Also, erasing these could result in loss
1598 // of information such as constant values attached to such types.
1599 return (t.tag <= lastBaseTag) || (syms.stringType.tsym == t.tsym);
1600 }
1602 private Type erasure(Type t, boolean recurse) {
1603 if (t.tag <= lastBaseTag)
1604 return t; /* fast special case */
1605 else
1606 return erasure.visit(t, recurse);
1607 }
1608 // where
1609 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1610 public Type visitType(Type t, Boolean recurse) {
1611 if (t.tag <= lastBaseTag)
1612 return t; /*fast special case*/
1613 else
1614 return t.map(recurse ? erasureRecFun : erasureFun);
1615 }
1617 @Override
1618 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1619 return erasure(upperBound(t), recurse);
1620 }
1622 @Override
1623 public Type visitClassType(ClassType t, Boolean recurse) {
1624 Type erased = t.tsym.erasure(Types.this);
1625 if (recurse) {
1626 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1627 }
1628 return erased;
1629 }
1631 @Override
1632 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1633 return erasure(t.bound, recurse);
1634 }
1636 @Override
1637 public Type visitErrorType(ErrorType t, Boolean recurse) {
1638 return t;
1639 }
1640 };
1642 private Mapping erasureFun = new Mapping ("erasure") {
1643 public Type apply(Type t) { return erasure(t); }
1644 };
1646 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1647 public Type apply(Type t) { return erasureRecursive(t); }
1648 };
1650 public List<Type> erasure(List<Type> ts) {
1651 return Type.map(ts, erasureFun);
1652 }
1654 public Type erasureRecursive(Type t) {
1655 return erasure(t, true);
1656 }
1658 public List<Type> erasureRecursive(List<Type> ts) {
1659 return Type.map(ts, erasureRecFun);
1660 }
1661 // </editor-fold>
1663 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1664 /**
1665 * Make a compound type from non-empty list of types
1666 *
1667 * @param bounds the types from which the compound type is formed
1668 * @param supertype is objectType if all bounds are interfaces,
1669 * null otherwise.
1670 */
1671 public Type makeCompoundType(List<Type> bounds,
1672 Type supertype) {
1673 ClassSymbol bc =
1674 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1675 Type.moreInfo
1676 ? names.fromString(bounds.toString())
1677 : names.empty,
1678 syms.noSymbol);
1679 if (bounds.head.tag == TYPEVAR)
1680 // error condition, recover
1681 bc.erasure_field = syms.objectType;
1682 else
1683 bc.erasure_field = erasure(bounds.head);
1684 bc.members_field = new Scope(bc);
1685 ClassType bt = (ClassType)bc.type;
1686 bt.allparams_field = List.nil();
1687 if (supertype != null) {
1688 bt.supertype_field = supertype;
1689 bt.interfaces_field = bounds;
1690 } else {
1691 bt.supertype_field = bounds.head;
1692 bt.interfaces_field = bounds.tail;
1693 }
1694 Assert.check(bt.supertype_field.tsym.completer != null
1695 || !bt.supertype_field.isInterface(),
1696 bt.supertype_field);
1697 return bt;
1698 }
1700 /**
1701 * Same as {@link #makeCompoundType(List,Type)}, except that the
1702 * second parameter is computed directly. Note that this might
1703 * cause a symbol completion. Hence, this version of
1704 * makeCompoundType may not be called during a classfile read.
1705 */
1706 public Type makeCompoundType(List<Type> bounds) {
1707 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1708 supertype(bounds.head) : null;
1709 return makeCompoundType(bounds, supertype);
1710 }
1712 /**
1713 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1714 * arguments are converted to a list and passed to the other
1715 * method. Note that this might cause a symbol completion.
1716 * Hence, this version of makeCompoundType may not be called
1717 * during a classfile read.
1718 */
1719 public Type makeCompoundType(Type bound1, Type bound2) {
1720 return makeCompoundType(List.of(bound1, bound2));
1721 }
1722 // </editor-fold>
1724 // <editor-fold defaultstate="collapsed" desc="supertype">
1725 public Type supertype(Type t) {
1726 return supertype.visit(t);
1727 }
1728 // where
1729 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1731 public Type visitType(Type t, Void ignored) {
1732 // A note on wildcards: there is no good way to
1733 // determine a supertype for a super bounded wildcard.
1734 return null;
1735 }
1737 @Override
1738 public Type visitClassType(ClassType t, Void ignored) {
1739 if (t.supertype_field == null) {
1740 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1741 // An interface has no superclass; its supertype is Object.
1742 if (t.isInterface())
1743 supertype = ((ClassType)t.tsym.type).supertype_field;
1744 if (t.supertype_field == null) {
1745 List<Type> actuals = classBound(t).allparams();
1746 List<Type> formals = t.tsym.type.allparams();
1747 if (t.hasErasedSupertypes()) {
1748 t.supertype_field = erasureRecursive(supertype);
1749 } else if (formals.nonEmpty()) {
1750 t.supertype_field = subst(supertype, formals, actuals);
1751 }
1752 else {
1753 t.supertype_field = supertype;
1754 }
1755 }
1756 }
1757 return t.supertype_field;
1758 }
1760 /**
1761 * The supertype is always a class type. If the type
1762 * variable's bounds start with a class type, this is also
1763 * the supertype. Otherwise, the supertype is
1764 * java.lang.Object.
1765 */
1766 @Override
1767 public Type visitTypeVar(TypeVar t, Void ignored) {
1768 if (t.bound.tag == TYPEVAR ||
1769 (!t.bound.isCompound() && !t.bound.isInterface())) {
1770 return t.bound;
1771 } else {
1772 return supertype(t.bound);
1773 }
1774 }
1776 @Override
1777 public Type visitArrayType(ArrayType t, Void ignored) {
1778 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1779 return arraySuperType();
1780 else
1781 return new ArrayType(supertype(t.elemtype), t.tsym);
1782 }
1784 @Override
1785 public Type visitErrorType(ErrorType t, Void ignored) {
1786 return t;
1787 }
1788 };
1789 // </editor-fold>
1791 // <editor-fold defaultstate="collapsed" desc="interfaces">
1792 /**
1793 * Return the interfaces implemented by this class.
1794 */
1795 public List<Type> interfaces(Type t) {
1796 return interfaces.visit(t);
1797 }
1798 // where
1799 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1801 public List<Type> visitType(Type t, Void ignored) {
1802 return List.nil();
1803 }
1805 @Override
1806 public List<Type> visitClassType(ClassType t, Void ignored) {
1807 if (t.interfaces_field == null) {
1808 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1809 if (t.interfaces_field == null) {
1810 // If t.interfaces_field is null, then t must
1811 // be a parameterized type (not to be confused
1812 // with a generic type declaration).
1813 // Terminology:
1814 // Parameterized type: List<String>
1815 // Generic type declaration: class List<E> { ... }
1816 // So t corresponds to List<String> and
1817 // t.tsym.type corresponds to List<E>.
1818 // The reason t must be parameterized type is
1819 // that completion will happen as a side
1820 // effect of calling
1821 // ClassSymbol.getInterfaces. Since
1822 // t.interfaces_field is null after
1823 // completion, we can assume that t is not the
1824 // type of a class/interface declaration.
1825 Assert.check(t != t.tsym.type, t);
1826 List<Type> actuals = t.allparams();
1827 List<Type> formals = t.tsym.type.allparams();
1828 if (t.hasErasedSupertypes()) {
1829 t.interfaces_field = erasureRecursive(interfaces);
1830 } else if (formals.nonEmpty()) {
1831 t.interfaces_field =
1832 upperBounds(subst(interfaces, formals, actuals));
1833 }
1834 else {
1835 t.interfaces_field = interfaces;
1836 }
1837 }
1838 }
1839 return t.interfaces_field;
1840 }
1842 @Override
1843 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1844 if (t.bound.isCompound())
1845 return interfaces(t.bound);
1847 if (t.bound.isInterface())
1848 return List.of(t.bound);
1850 return List.nil();
1851 }
1852 };
1853 // </editor-fold>
1855 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1856 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1858 public boolean isDerivedRaw(Type t) {
1859 Boolean result = isDerivedRawCache.get(t);
1860 if (result == null) {
1861 result = isDerivedRawInternal(t);
1862 isDerivedRawCache.put(t, result);
1863 }
1864 return result;
1865 }
1867 public boolean isDerivedRawInternal(Type t) {
1868 if (t.isErroneous())
1869 return false;
1870 return
1871 t.isRaw() ||
1872 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1873 isDerivedRaw(interfaces(t));
1874 }
1876 public boolean isDerivedRaw(List<Type> ts) {
1877 List<Type> l = ts;
1878 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1879 return l.nonEmpty();
1880 }
1881 // </editor-fold>
1883 // <editor-fold defaultstate="collapsed" desc="setBounds">
1884 /**
1885 * Set the bounds field of the given type variable to reflect a
1886 * (possibly multiple) list of bounds.
1887 * @param t a type variable
1888 * @param bounds the bounds, must be nonempty
1889 * @param supertype is objectType if all bounds are interfaces,
1890 * null otherwise.
1891 */
1892 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1893 if (bounds.tail.isEmpty())
1894 t.bound = bounds.head;
1895 else
1896 t.bound = makeCompoundType(bounds, supertype);
1897 t.rank_field = -1;
1898 }
1900 /**
1901 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1902 * third parameter is computed directly, as follows: if all
1903 * all bounds are interface types, the computed supertype is Object,
1904 * otherwise the supertype is simply left null (in this case, the supertype
1905 * is assumed to be the head of the bound list passed as second argument).
1906 * Note that this check might cause a symbol completion. Hence, this version of
1907 * setBounds may not be called during a classfile read.
1908 */
1909 public void setBounds(TypeVar t, List<Type> bounds) {
1910 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1911 syms.objectType : null;
1912 setBounds(t, bounds, supertype);
1913 t.rank_field = -1;
1914 }
1915 // </editor-fold>
1917 // <editor-fold defaultstate="collapsed" desc="getBounds">
1918 /**
1919 * Return list of bounds of the given type variable.
1920 */
1921 public List<Type> getBounds(TypeVar t) {
1922 if (t.bound.isErroneous() || !t.bound.isCompound())
1923 return List.of(t.bound);
1924 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1925 return interfaces(t).prepend(supertype(t));
1926 else
1927 // No superclass was given in bounds.
1928 // In this case, supertype is Object, erasure is first interface.
1929 return interfaces(t);
1930 }
1931 // </editor-fold>
1933 // <editor-fold defaultstate="collapsed" desc="classBound">
1934 /**
1935 * If the given type is a (possibly selected) type variable,
1936 * return the bounding class of this type, otherwise return the
1937 * type itself.
1938 */
1939 public Type classBound(Type t) {
1940 return classBound.visit(t);
1941 }
1942 // where
1943 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1945 public Type visitType(Type t, Void ignored) {
1946 return t;
1947 }
1949 @Override
1950 public Type visitClassType(ClassType t, Void ignored) {
1951 Type outer1 = classBound(t.getEnclosingType());
1952 if (outer1 != t.getEnclosingType())
1953 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1954 else
1955 return t;
1956 }
1958 @Override
1959 public Type visitTypeVar(TypeVar t, Void ignored) {
1960 return classBound(supertype(t));
1961 }
1963 @Override
1964 public Type visitErrorType(ErrorType t, Void ignored) {
1965 return t;
1966 }
1967 };
1968 // </editor-fold>
1970 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1971 /**
1972 * Returns true iff the first signature is a <em>sub
1973 * signature</em> of the other. This is <b>not</b> an equivalence
1974 * relation.
1975 *
1976 * @jls section 8.4.2.
1977 * @see #overrideEquivalent(Type t, Type s)
1978 * @param t first signature (possibly raw).
1979 * @param s second signature (could be subjected to erasure).
1980 * @return true if t is a sub signature of s.
1981 */
1982 public boolean isSubSignature(Type t, Type s) {
1983 return isSubSignature(t, s, true);
1984 }
1986 public boolean isSubSignature(Type t, Type s, boolean strict) {
1987 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
1988 }
1990 /**
1991 * Returns true iff these signatures are related by <em>override
1992 * equivalence</em>. This is the natural extension of
1993 * isSubSignature to an equivalence relation.
1994 *
1995 * @jls section 8.4.2.
1996 * @see #isSubSignature(Type t, Type s)
1997 * @param t a signature (possible raw, could be subjected to
1998 * erasure).
1999 * @param s a signature (possible raw, could be subjected to
2000 * erasure).
2001 * @return true if either argument is a sub signature of the other.
2002 */
2003 public boolean overrideEquivalent(Type t, Type s) {
2004 return hasSameArgs(t, s) ||
2005 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2006 }
2008 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2009 class ImplementationCache {
2011 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2012 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2014 class Entry {
2015 final MethodSymbol cachedImpl;
2016 final Filter<Symbol> implFilter;
2017 final boolean checkResult;
2018 final int prevMark;
2020 public Entry(MethodSymbol cachedImpl,
2021 Filter<Symbol> scopeFilter,
2022 boolean checkResult,
2023 int prevMark) {
2024 this.cachedImpl = cachedImpl;
2025 this.implFilter = scopeFilter;
2026 this.checkResult = checkResult;
2027 this.prevMark = prevMark;
2028 }
2030 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2031 return this.implFilter == scopeFilter &&
2032 this.checkResult == checkResult &&
2033 this.prevMark == mark;
2034 }
2035 }
2037 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2038 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2039 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2040 if (cache == null) {
2041 cache = new HashMap<TypeSymbol, Entry>();
2042 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2043 }
2044 Entry e = cache.get(origin);
2045 CompoundScope members = membersClosure(origin.type, true);
2046 if (e == null ||
2047 !e.matches(implFilter, checkResult, members.getMark())) {
2048 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2049 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2050 return impl;
2051 }
2052 else {
2053 return e.cachedImpl;
2054 }
2055 }
2057 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2058 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2059 while (t.tag == TYPEVAR)
2060 t = t.getUpperBound();
2061 TypeSymbol c = t.tsym;
2062 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2063 e.scope != null;
2064 e = e.next(implFilter)) {
2065 if (e.sym != null &&
2066 e.sym.overrides(ms, origin, Types.this, checkResult))
2067 return (MethodSymbol)e.sym;
2068 }
2069 }
2070 return null;
2071 }
2072 }
2074 private ImplementationCache implCache = new ImplementationCache();
2076 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2077 return implCache.get(ms, origin, checkResult, implFilter);
2078 }
2079 // </editor-fold>
2081 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2082 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2084 private WeakHashMap<TypeSymbol, Entry> _map =
2085 new WeakHashMap<TypeSymbol, Entry>();
2087 class Entry {
2088 final boolean skipInterfaces;
2089 final CompoundScope compoundScope;
2091 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2092 this.skipInterfaces = skipInterfaces;
2093 this.compoundScope = compoundScope;
2094 }
2096 boolean matches(boolean skipInterfaces) {
2097 return this.skipInterfaces == skipInterfaces;
2098 }
2099 }
2101 List<TypeSymbol> seenTypes = List.nil();
2103 /** members closure visitor methods **/
2105 public CompoundScope visitType(Type t, Boolean skipInterface) {
2106 return null;
2107 }
2109 @Override
2110 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2111 if (seenTypes.contains(t.tsym)) {
2112 //this is possible when an interface is implemented in multiple
2113 //superclasses, or when a classs hierarchy is circular - in such
2114 //cases we don't need to recurse (empty scope is returned)
2115 return new CompoundScope(t.tsym);
2116 }
2117 try {
2118 seenTypes = seenTypes.prepend(t.tsym);
2119 ClassSymbol csym = (ClassSymbol)t.tsym;
2120 Entry e = _map.get(csym);
2121 if (e == null || !e.matches(skipInterface)) {
2122 CompoundScope membersClosure = new CompoundScope(csym);
2123 if (!skipInterface) {
2124 for (Type i : interfaces(t)) {
2125 membersClosure.addSubScope(visit(i, skipInterface));
2126 }
2127 }
2128 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2129 membersClosure.addSubScope(csym.members());
2130 e = new Entry(skipInterface, membersClosure);
2131 _map.put(csym, e);
2132 }
2133 return e.compoundScope;
2134 }
2135 finally {
2136 seenTypes = seenTypes.tail;
2137 }
2138 }
2140 @Override
2141 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2142 return visit(t.getUpperBound(), skipInterface);
2143 }
2144 }
2146 private MembersClosureCache membersCache = new MembersClosureCache();
2148 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2149 return membersCache.visit(site, skipInterface);
2150 }
2151 // </editor-fold>
2153 /**
2154 * Does t have the same arguments as s? It is assumed that both
2155 * types are (possibly polymorphic) method types. Monomorphic
2156 * method types "have the same arguments", if their argument lists
2157 * are equal. Polymorphic method types "have the same arguments",
2158 * if they have the same arguments after renaming all type
2159 * variables of one to corresponding type variables in the other,
2160 * where correspondence is by position in the type parameter list.
2161 */
2162 public boolean hasSameArgs(Type t, Type s) {
2163 return hasSameArgs(t, s, true);
2164 }
2166 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2167 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2168 }
2170 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2171 return hasSameArgs.visit(t, s);
2172 }
2173 // where
2174 private class HasSameArgs extends TypeRelation {
2176 boolean strict;
2178 public HasSameArgs(boolean strict) {
2179 this.strict = strict;
2180 }
2182 public Boolean visitType(Type t, Type s) {
2183 throw new AssertionError();
2184 }
2186 @Override
2187 public Boolean visitMethodType(MethodType t, Type s) {
2188 return s.tag == METHOD
2189 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2190 }
2192 @Override
2193 public Boolean visitForAll(ForAll t, Type s) {
2194 if (s.tag != FORALL)
2195 return strict ? false : visitMethodType(t.asMethodType(), s);
2197 ForAll forAll = (ForAll)s;
2198 return hasSameBounds(t, forAll)
2199 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2200 }
2202 @Override
2203 public Boolean visitErrorType(ErrorType t, Type s) {
2204 return false;
2205 }
2206 };
2208 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2209 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2211 // </editor-fold>
2213 // <editor-fold defaultstate="collapsed" desc="subst">
2214 public List<Type> subst(List<Type> ts,
2215 List<Type> from,
2216 List<Type> to) {
2217 return new Subst(from, to).subst(ts);
2218 }
2220 /**
2221 * Substitute all occurrences of a type in `from' with the
2222 * corresponding type in `to' in 't'. Match lists `from' and `to'
2223 * from the right: If lists have different length, discard leading
2224 * elements of the longer list.
2225 */
2226 public Type subst(Type t, List<Type> from, List<Type> to) {
2227 return new Subst(from, to).subst(t);
2228 }
2230 private class Subst extends UnaryVisitor<Type> {
2231 List<Type> from;
2232 List<Type> to;
2234 public Subst(List<Type> from, List<Type> to) {
2235 int fromLength = from.length();
2236 int toLength = to.length();
2237 while (fromLength > toLength) {
2238 fromLength--;
2239 from = from.tail;
2240 }
2241 while (fromLength < toLength) {
2242 toLength--;
2243 to = to.tail;
2244 }
2245 this.from = from;
2246 this.to = to;
2247 }
2249 Type subst(Type t) {
2250 if (from.tail == null)
2251 return t;
2252 else
2253 return visit(t);
2254 }
2256 List<Type> subst(List<Type> ts) {
2257 if (from.tail == null)
2258 return ts;
2259 boolean wild = false;
2260 if (ts.nonEmpty() && from.nonEmpty()) {
2261 Type head1 = subst(ts.head);
2262 List<Type> tail1 = subst(ts.tail);
2263 if (head1 != ts.head || tail1 != ts.tail)
2264 return tail1.prepend(head1);
2265 }
2266 return ts;
2267 }
2269 public Type visitType(Type t, Void ignored) {
2270 return t;
2271 }
2273 @Override
2274 public Type visitMethodType(MethodType t, Void ignored) {
2275 List<Type> argtypes = subst(t.argtypes);
2276 Type restype = subst(t.restype);
2277 List<Type> thrown = subst(t.thrown);
2278 if (argtypes == t.argtypes &&
2279 restype == t.restype &&
2280 thrown == t.thrown)
2281 return t;
2282 else
2283 return new MethodType(argtypes, restype, thrown, t.tsym);
2284 }
2286 @Override
2287 public Type visitTypeVar(TypeVar t, Void ignored) {
2288 for (List<Type> from = this.from, to = this.to;
2289 from.nonEmpty();
2290 from = from.tail, to = to.tail) {
2291 if (t == from.head) {
2292 return to.head.withTypeVar(t);
2293 }
2294 }
2295 return t;
2296 }
2298 @Override
2299 public Type visitClassType(ClassType t, Void ignored) {
2300 if (!t.isCompound()) {
2301 List<Type> typarams = t.getTypeArguments();
2302 List<Type> typarams1 = subst(typarams);
2303 Type outer = t.getEnclosingType();
2304 Type outer1 = subst(outer);
2305 if (typarams1 == typarams && outer1 == outer)
2306 return t;
2307 else
2308 return new ClassType(outer1, typarams1, t.tsym);
2309 } else {
2310 Type st = subst(supertype(t));
2311 List<Type> is = upperBounds(subst(interfaces(t)));
2312 if (st == supertype(t) && is == interfaces(t))
2313 return t;
2314 else
2315 return makeCompoundType(is.prepend(st));
2316 }
2317 }
2319 @Override
2320 public Type visitWildcardType(WildcardType t, Void ignored) {
2321 Type bound = t.type;
2322 if (t.kind != BoundKind.UNBOUND)
2323 bound = subst(bound);
2324 if (bound == t.type) {
2325 return t;
2326 } else {
2327 if (t.isExtendsBound() && bound.isExtendsBound())
2328 bound = upperBound(bound);
2329 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2330 }
2331 }
2333 @Override
2334 public Type visitArrayType(ArrayType t, Void ignored) {
2335 Type elemtype = subst(t.elemtype);
2336 if (elemtype == t.elemtype)
2337 return t;
2338 else
2339 return new ArrayType(upperBound(elemtype), t.tsym);
2340 }
2342 @Override
2343 public Type visitForAll(ForAll t, Void ignored) {
2344 if (Type.containsAny(to, t.tvars)) {
2345 //perform alpha-renaming of free-variables in 't'
2346 //if 'to' types contain variables that are free in 't'
2347 List<Type> freevars = newInstances(t.tvars);
2348 t = new ForAll(freevars,
2349 Types.this.subst(t.qtype, t.tvars, freevars));
2350 }
2351 List<Type> tvars1 = substBounds(t.tvars, from, to);
2352 Type qtype1 = subst(t.qtype);
2353 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2354 return t;
2355 } else if (tvars1 == t.tvars) {
2356 return new ForAll(tvars1, qtype1);
2357 } else {
2358 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2359 }
2360 }
2362 @Override
2363 public Type visitErrorType(ErrorType t, Void ignored) {
2364 return t;
2365 }
2366 }
2368 public List<Type> substBounds(List<Type> tvars,
2369 List<Type> from,
2370 List<Type> to) {
2371 if (tvars.isEmpty())
2372 return tvars;
2373 ListBuffer<Type> newBoundsBuf = lb();
2374 boolean changed = false;
2375 // calculate new bounds
2376 for (Type t : tvars) {
2377 TypeVar tv = (TypeVar) t;
2378 Type bound = subst(tv.bound, from, to);
2379 if (bound != tv.bound)
2380 changed = true;
2381 newBoundsBuf.append(bound);
2382 }
2383 if (!changed)
2384 return tvars;
2385 ListBuffer<Type> newTvars = lb();
2386 // create new type variables without bounds
2387 for (Type t : tvars) {
2388 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2389 }
2390 // the new bounds should use the new type variables in place
2391 // of the old
2392 List<Type> newBounds = newBoundsBuf.toList();
2393 from = tvars;
2394 to = newTvars.toList();
2395 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2396 newBounds.head = subst(newBounds.head, from, to);
2397 }
2398 newBounds = newBoundsBuf.toList();
2399 // set the bounds of new type variables to the new bounds
2400 for (Type t : newTvars.toList()) {
2401 TypeVar tv = (TypeVar) t;
2402 tv.bound = newBounds.head;
2403 newBounds = newBounds.tail;
2404 }
2405 return newTvars.toList();
2406 }
2408 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2409 Type bound1 = subst(t.bound, from, to);
2410 if (bound1 == t.bound)
2411 return t;
2412 else {
2413 // create new type variable without bounds
2414 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2415 // the new bound should use the new type variable in place
2416 // of the old
2417 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2418 return tv;
2419 }
2420 }
2421 // </editor-fold>
2423 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2424 /**
2425 * Does t have the same bounds for quantified variables as s?
2426 */
2427 boolean hasSameBounds(ForAll t, ForAll s) {
2428 List<Type> l1 = t.tvars;
2429 List<Type> l2 = s.tvars;
2430 while (l1.nonEmpty() && l2.nonEmpty() &&
2431 isSameType(l1.head.getUpperBound(),
2432 subst(l2.head.getUpperBound(),
2433 s.tvars,
2434 t.tvars))) {
2435 l1 = l1.tail;
2436 l2 = l2.tail;
2437 }
2438 return l1.isEmpty() && l2.isEmpty();
2439 }
2440 // </editor-fold>
2442 // <editor-fold defaultstate="collapsed" desc="newInstances">
2443 /** Create new vector of type variables from list of variables
2444 * changing all recursive bounds from old to new list.
2445 */
2446 public List<Type> newInstances(List<Type> tvars) {
2447 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2448 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2449 TypeVar tv = (TypeVar) l.head;
2450 tv.bound = subst(tv.bound, tvars, tvars1);
2451 }
2452 return tvars1;
2453 }
2454 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2455 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2456 };
2457 // </editor-fold>
2459 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2460 return original.accept(methodWithParameters, newParams);
2461 }
2462 // where
2463 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2464 public Type visitType(Type t, List<Type> newParams) {
2465 throw new IllegalArgumentException("Not a method type: " + t);
2466 }
2467 public Type visitMethodType(MethodType t, List<Type> newParams) {
2468 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2469 }
2470 public Type visitForAll(ForAll t, List<Type> newParams) {
2471 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2472 }
2473 };
2475 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2476 return original.accept(methodWithThrown, newThrown);
2477 }
2478 // where
2479 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2480 public Type visitType(Type t, List<Type> newThrown) {
2481 throw new IllegalArgumentException("Not a method type: " + t);
2482 }
2483 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2484 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2485 }
2486 public Type visitForAll(ForAll t, List<Type> newThrown) {
2487 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2488 }
2489 };
2491 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2492 return original.accept(methodWithReturn, newReturn);
2493 }
2494 // where
2495 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2496 public Type visitType(Type t, Type newReturn) {
2497 throw new IllegalArgumentException("Not a method type: " + t);
2498 }
2499 public Type visitMethodType(MethodType t, Type newReturn) {
2500 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2501 }
2502 public Type visitForAll(ForAll t, Type newReturn) {
2503 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2504 }
2505 };
2507 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2508 public Type createErrorType(Type originalType) {
2509 return new ErrorType(originalType, syms.errSymbol);
2510 }
2512 public Type createErrorType(ClassSymbol c, Type originalType) {
2513 return new ErrorType(c, originalType);
2514 }
2516 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2517 return new ErrorType(name, container, originalType);
2518 }
2519 // </editor-fold>
2521 // <editor-fold defaultstate="collapsed" desc="rank">
2522 /**
2523 * The rank of a class is the length of the longest path between
2524 * the class and java.lang.Object in the class inheritance
2525 * graph. Undefined for all but reference types.
2526 */
2527 public int rank(Type t) {
2528 switch(t.tag) {
2529 case CLASS: {
2530 ClassType cls = (ClassType)t;
2531 if (cls.rank_field < 0) {
2532 Name fullname = cls.tsym.getQualifiedName();
2533 if (fullname == names.java_lang_Object)
2534 cls.rank_field = 0;
2535 else {
2536 int r = rank(supertype(cls));
2537 for (List<Type> l = interfaces(cls);
2538 l.nonEmpty();
2539 l = l.tail) {
2540 if (rank(l.head) > r)
2541 r = rank(l.head);
2542 }
2543 cls.rank_field = r + 1;
2544 }
2545 }
2546 return cls.rank_field;
2547 }
2548 case TYPEVAR: {
2549 TypeVar tvar = (TypeVar)t;
2550 if (tvar.rank_field < 0) {
2551 int r = rank(supertype(tvar));
2552 for (List<Type> l = interfaces(tvar);
2553 l.nonEmpty();
2554 l = l.tail) {
2555 if (rank(l.head) > r) r = rank(l.head);
2556 }
2557 tvar.rank_field = r + 1;
2558 }
2559 return tvar.rank_field;
2560 }
2561 case ERROR:
2562 return 0;
2563 default:
2564 throw new AssertionError();
2565 }
2566 }
2567 // </editor-fold>
2569 /**
2570 * Helper method for generating a string representation of a given type
2571 * accordingly to a given locale
2572 */
2573 public String toString(Type t, Locale locale) {
2574 return Printer.createStandardPrinter(messages).visit(t, locale);
2575 }
2577 /**
2578 * Helper method for generating a string representation of a given type
2579 * accordingly to a given locale
2580 */
2581 public String toString(Symbol t, Locale locale) {
2582 return Printer.createStandardPrinter(messages).visit(t, locale);
2583 }
2585 // <editor-fold defaultstate="collapsed" desc="toString">
2586 /**
2587 * This toString is slightly more descriptive than the one on Type.
2588 *
2589 * @deprecated Types.toString(Type t, Locale l) provides better support
2590 * for localization
2591 */
2592 @Deprecated
2593 public String toString(Type t) {
2594 if (t.tag == FORALL) {
2595 ForAll forAll = (ForAll)t;
2596 return typaramsString(forAll.tvars) + forAll.qtype;
2597 }
2598 return "" + t;
2599 }
2600 // where
2601 private String typaramsString(List<Type> tvars) {
2602 StringBuilder s = new StringBuilder();
2603 s.append('<');
2604 boolean first = true;
2605 for (Type t : tvars) {
2606 if (!first) s.append(", ");
2607 first = false;
2608 appendTyparamString(((TypeVar)t), s);
2609 }
2610 s.append('>');
2611 return s.toString();
2612 }
2613 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2614 buf.append(t);
2615 if (t.bound == null ||
2616 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2617 return;
2618 buf.append(" extends "); // Java syntax; no need for i18n
2619 Type bound = t.bound;
2620 if (!bound.isCompound()) {
2621 buf.append(bound);
2622 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2623 buf.append(supertype(t));
2624 for (Type intf : interfaces(t)) {
2625 buf.append('&');
2626 buf.append(intf);
2627 }
2628 } else {
2629 // No superclass was given in bounds.
2630 // In this case, supertype is Object, erasure is first interface.
2631 boolean first = true;
2632 for (Type intf : interfaces(t)) {
2633 if (!first) buf.append('&');
2634 first = false;
2635 buf.append(intf);
2636 }
2637 }
2638 }
2639 // </editor-fold>
2641 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2642 /**
2643 * A cache for closures.
2644 *
2645 * <p>A closure is a list of all the supertypes and interfaces of
2646 * a class or interface type, ordered by ClassSymbol.precedes
2647 * (that is, subclasses come first, arbitrary but fixed
2648 * otherwise).
2649 */
2650 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2652 /**
2653 * Returns the closure of a class or interface type.
2654 */
2655 public List<Type> closure(Type t) {
2656 List<Type> cl = closureCache.get(t);
2657 if (cl == null) {
2658 Type st = supertype(t);
2659 if (!t.isCompound()) {
2660 if (st.tag == CLASS) {
2661 cl = insert(closure(st), t);
2662 } else if (st.tag == TYPEVAR) {
2663 cl = closure(st).prepend(t);
2664 } else {
2665 cl = List.of(t);
2666 }
2667 } else {
2668 cl = closure(supertype(t));
2669 }
2670 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2671 cl = union(cl, closure(l.head));
2672 closureCache.put(t, cl);
2673 }
2674 return cl;
2675 }
2677 /**
2678 * Insert a type in a closure
2679 */
2680 public List<Type> insert(List<Type> cl, Type t) {
2681 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2682 return cl.prepend(t);
2683 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2684 return insert(cl.tail, t).prepend(cl.head);
2685 } else {
2686 return cl;
2687 }
2688 }
2690 /**
2691 * Form the union of two closures
2692 */
2693 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2694 if (cl1.isEmpty()) {
2695 return cl2;
2696 } else if (cl2.isEmpty()) {
2697 return cl1;
2698 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2699 return union(cl1.tail, cl2).prepend(cl1.head);
2700 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2701 return union(cl1, cl2.tail).prepend(cl2.head);
2702 } else {
2703 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2704 }
2705 }
2707 /**
2708 * Intersect two closures
2709 */
2710 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2711 if (cl1 == cl2)
2712 return cl1;
2713 if (cl1.isEmpty() || cl2.isEmpty())
2714 return List.nil();
2715 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2716 return intersect(cl1.tail, cl2);
2717 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2718 return intersect(cl1, cl2.tail);
2719 if (isSameType(cl1.head, cl2.head))
2720 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2721 if (cl1.head.tsym == cl2.head.tsym &&
2722 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2723 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2724 Type merge = merge(cl1.head,cl2.head);
2725 return intersect(cl1.tail, cl2.tail).prepend(merge);
2726 }
2727 if (cl1.head.isRaw() || cl2.head.isRaw())
2728 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2729 }
2730 return intersect(cl1.tail, cl2.tail);
2731 }
2732 // where
2733 class TypePair {
2734 final Type t1;
2735 final Type t2;
2736 TypePair(Type t1, Type t2) {
2737 this.t1 = t1;
2738 this.t2 = t2;
2739 }
2740 @Override
2741 public int hashCode() {
2742 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
2743 }
2744 @Override
2745 public boolean equals(Object obj) {
2746 if (!(obj instanceof TypePair))
2747 return false;
2748 TypePair typePair = (TypePair)obj;
2749 return isSameType(t1, typePair.t1)
2750 && isSameType(t2, typePair.t2);
2751 }
2752 }
2753 Set<TypePair> mergeCache = new HashSet<TypePair>();
2754 private Type merge(Type c1, Type c2) {
2755 ClassType class1 = (ClassType) c1;
2756 List<Type> act1 = class1.getTypeArguments();
2757 ClassType class2 = (ClassType) c2;
2758 List<Type> act2 = class2.getTypeArguments();
2759 ListBuffer<Type> merged = new ListBuffer<Type>();
2760 List<Type> typarams = class1.tsym.type.getTypeArguments();
2762 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2763 if (containsType(act1.head, act2.head)) {
2764 merged.append(act1.head);
2765 } else if (containsType(act2.head, act1.head)) {
2766 merged.append(act2.head);
2767 } else {
2768 TypePair pair = new TypePair(c1, c2);
2769 Type m;
2770 if (mergeCache.add(pair)) {
2771 m = new WildcardType(lub(upperBound(act1.head),
2772 upperBound(act2.head)),
2773 BoundKind.EXTENDS,
2774 syms.boundClass);
2775 mergeCache.remove(pair);
2776 } else {
2777 m = new WildcardType(syms.objectType,
2778 BoundKind.UNBOUND,
2779 syms.boundClass);
2780 }
2781 merged.append(m.withTypeVar(typarams.head));
2782 }
2783 act1 = act1.tail;
2784 act2 = act2.tail;
2785 typarams = typarams.tail;
2786 }
2787 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2788 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2789 }
2791 /**
2792 * Return the minimum type of a closure, a compound type if no
2793 * unique minimum exists.
2794 */
2795 private Type compoundMin(List<Type> cl) {
2796 if (cl.isEmpty()) return syms.objectType;
2797 List<Type> compound = closureMin(cl);
2798 if (compound.isEmpty())
2799 return null;
2800 else if (compound.tail.isEmpty())
2801 return compound.head;
2802 else
2803 return makeCompoundType(compound);
2804 }
2806 /**
2807 * Return the minimum types of a closure, suitable for computing
2808 * compoundMin or glb.
2809 */
2810 private List<Type> closureMin(List<Type> cl) {
2811 ListBuffer<Type> classes = lb();
2812 ListBuffer<Type> interfaces = lb();
2813 while (!cl.isEmpty()) {
2814 Type current = cl.head;
2815 if (current.isInterface())
2816 interfaces.append(current);
2817 else
2818 classes.append(current);
2819 ListBuffer<Type> candidates = lb();
2820 for (Type t : cl.tail) {
2821 if (!isSubtypeNoCapture(current, t))
2822 candidates.append(t);
2823 }
2824 cl = candidates.toList();
2825 }
2826 return classes.appendList(interfaces).toList();
2827 }
2829 /**
2830 * Return the least upper bound of pair of types. if the lub does
2831 * not exist return null.
2832 */
2833 public Type lub(Type t1, Type t2) {
2834 return lub(List.of(t1, t2));
2835 }
2837 /**
2838 * Return the least upper bound (lub) of set of types. If the lub
2839 * does not exist return the type of null (bottom).
2840 */
2841 public Type lub(List<Type> ts) {
2842 final int ARRAY_BOUND = 1;
2843 final int CLASS_BOUND = 2;
2844 int boundkind = 0;
2845 for (Type t : ts) {
2846 switch (t.tag) {
2847 case CLASS:
2848 boundkind |= CLASS_BOUND;
2849 break;
2850 case ARRAY:
2851 boundkind |= ARRAY_BOUND;
2852 break;
2853 case TYPEVAR:
2854 do {
2855 t = t.getUpperBound();
2856 } while (t.tag == TYPEVAR);
2857 if (t.tag == ARRAY) {
2858 boundkind |= ARRAY_BOUND;
2859 } else {
2860 boundkind |= CLASS_BOUND;
2861 }
2862 break;
2863 default:
2864 if (t.isPrimitive())
2865 return syms.errType;
2866 }
2867 }
2868 switch (boundkind) {
2869 case 0:
2870 return syms.botType;
2872 case ARRAY_BOUND:
2873 // calculate lub(A[], B[])
2874 List<Type> elements = Type.map(ts, elemTypeFun);
2875 for (Type t : elements) {
2876 if (t.isPrimitive()) {
2877 // if a primitive type is found, then return
2878 // arraySuperType unless all the types are the
2879 // same
2880 Type first = ts.head;
2881 for (Type s : ts.tail) {
2882 if (!isSameType(first, s)) {
2883 // lub(int[], B[]) is Cloneable & Serializable
2884 return arraySuperType();
2885 }
2886 }
2887 // all the array types are the same, return one
2888 // lub(int[], int[]) is int[]
2889 return first;
2890 }
2891 }
2892 // lub(A[], B[]) is lub(A, B)[]
2893 return new ArrayType(lub(elements), syms.arrayClass);
2895 case CLASS_BOUND:
2896 // calculate lub(A, B)
2897 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2898 ts = ts.tail;
2899 Assert.check(!ts.isEmpty());
2900 //step 1 - compute erased candidate set (EC)
2901 List<Type> cl = erasedSupertypes(ts.head);
2902 for (Type t : ts.tail) {
2903 if (t.tag == CLASS || t.tag == TYPEVAR)
2904 cl = intersect(cl, erasedSupertypes(t));
2905 }
2906 //step 2 - compute minimal erased candidate set (MEC)
2907 List<Type> mec = closureMin(cl);
2908 //step 3 - for each element G in MEC, compute lci(Inv(G))
2909 List<Type> candidates = List.nil();
2910 for (Type erasedSupertype : mec) {
2911 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
2912 for (Type t : ts) {
2913 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
2914 }
2915 candidates = candidates.appendList(lci);
2916 }
2917 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
2918 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
2919 return compoundMin(candidates);
2921 default:
2922 // calculate lub(A, B[])
2923 List<Type> classes = List.of(arraySuperType());
2924 for (Type t : ts) {
2925 if (t.tag != ARRAY) // Filter out any arrays
2926 classes = classes.prepend(t);
2927 }
2928 // lub(A, B[]) is lub(A, arraySuperType)
2929 return lub(classes);
2930 }
2931 }
2932 // where
2933 List<Type> erasedSupertypes(Type t) {
2934 ListBuffer<Type> buf = lb();
2935 for (Type sup : closure(t)) {
2936 if (sup.tag == TYPEVAR) {
2937 buf.append(sup);
2938 } else {
2939 buf.append(erasure(sup));
2940 }
2941 }
2942 return buf.toList();
2943 }
2945 private Type arraySuperType = null;
2946 private Type arraySuperType() {
2947 // initialized lazily to avoid problems during compiler startup
2948 if (arraySuperType == null) {
2949 synchronized (this) {
2950 if (arraySuperType == null) {
2951 // JLS 10.8: all arrays implement Cloneable and Serializable.
2952 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2953 syms.cloneableType),
2954 syms.objectType);
2955 }
2956 }
2957 }
2958 return arraySuperType;
2959 }
2960 // </editor-fold>
2962 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2963 public Type glb(List<Type> ts) {
2964 Type t1 = ts.head;
2965 for (Type t2 : ts.tail) {
2966 if (t1.isErroneous())
2967 return t1;
2968 t1 = glb(t1, t2);
2969 }
2970 return t1;
2971 }
2972 //where
2973 public Type glb(Type t, Type s) {
2974 if (s == null)
2975 return t;
2976 else if (t.isPrimitive() || s.isPrimitive())
2977 return syms.errType;
2978 else if (isSubtypeNoCapture(t, s))
2979 return t;
2980 else if (isSubtypeNoCapture(s, t))
2981 return s;
2983 List<Type> closure = union(closure(t), closure(s));
2984 List<Type> bounds = closureMin(closure);
2986 if (bounds.isEmpty()) { // length == 0
2987 return syms.objectType;
2988 } else if (bounds.tail.isEmpty()) { // length == 1
2989 return bounds.head;
2990 } else { // length > 1
2991 int classCount = 0;
2992 for (Type bound : bounds)
2993 if (!bound.isInterface())
2994 classCount++;
2995 if (classCount > 1)
2996 return createErrorType(t);
2997 }
2998 return makeCompoundType(bounds);
2999 }
3000 // </editor-fold>
3002 // <editor-fold defaultstate="collapsed" desc="hashCode">
3003 /**
3004 * Compute a hash code on a type.
3005 */
3006 public static int hashCode(Type t) {
3007 return hashCode.visit(t);
3008 }
3009 // where
3010 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3012 public Integer visitType(Type t, Void ignored) {
3013 return t.tag;
3014 }
3016 @Override
3017 public Integer visitClassType(ClassType t, Void ignored) {
3018 int result = visit(t.getEnclosingType());
3019 result *= 127;
3020 result += t.tsym.flatName().hashCode();
3021 for (Type s : t.getTypeArguments()) {
3022 result *= 127;
3023 result += visit(s);
3024 }
3025 return result;
3026 }
3028 @Override
3029 public Integer visitWildcardType(WildcardType t, Void ignored) {
3030 int result = t.kind.hashCode();
3031 if (t.type != null) {
3032 result *= 127;
3033 result += visit(t.type);
3034 }
3035 return result;
3036 }
3038 @Override
3039 public Integer visitArrayType(ArrayType t, Void ignored) {
3040 return visit(t.elemtype) + 12;
3041 }
3043 @Override
3044 public Integer visitTypeVar(TypeVar t, Void ignored) {
3045 return System.identityHashCode(t.tsym);
3046 }
3048 @Override
3049 public Integer visitUndetVar(UndetVar t, Void ignored) {
3050 return System.identityHashCode(t);
3051 }
3053 @Override
3054 public Integer visitErrorType(ErrorType t, Void ignored) {
3055 return 0;
3056 }
3057 };
3058 // </editor-fold>
3060 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3061 /**
3062 * Does t have a result that is a subtype of the result type of s,
3063 * suitable for covariant returns? It is assumed that both types
3064 * are (possibly polymorphic) method types. Monomorphic method
3065 * types are handled in the obvious way. Polymorphic method types
3066 * require renaming all type variables of one to corresponding
3067 * type variables in the other, where correspondence is by
3068 * position in the type parameter list. */
3069 public boolean resultSubtype(Type t, Type s, Warner warner) {
3070 List<Type> tvars = t.getTypeArguments();
3071 List<Type> svars = s.getTypeArguments();
3072 Type tres = t.getReturnType();
3073 Type sres = subst(s.getReturnType(), svars, tvars);
3074 return covariantReturnType(tres, sres, warner);
3075 }
3077 /**
3078 * Return-Type-Substitutable.
3079 * @jls section 8.4.5
3080 */
3081 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3082 if (hasSameArgs(r1, r2))
3083 return resultSubtype(r1, r2, Warner.noWarnings);
3084 else
3085 return covariantReturnType(r1.getReturnType(),
3086 erasure(r2.getReturnType()),
3087 Warner.noWarnings);
3088 }
3090 public boolean returnTypeSubstitutable(Type r1,
3091 Type r2, Type r2res,
3092 Warner warner) {
3093 if (isSameType(r1.getReturnType(), r2res))
3094 return true;
3095 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3096 return false;
3098 if (hasSameArgs(r1, r2))
3099 return covariantReturnType(r1.getReturnType(), r2res, warner);
3100 if (!allowCovariantReturns)
3101 return false;
3102 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3103 return true;
3104 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3105 return false;
3106 warner.warn(LintCategory.UNCHECKED);
3107 return true;
3108 }
3110 /**
3111 * Is t an appropriate return type in an overrider for a
3112 * method that returns s?
3113 */
3114 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3115 return
3116 isSameType(t, s) ||
3117 allowCovariantReturns &&
3118 !t.isPrimitive() &&
3119 !s.isPrimitive() &&
3120 isAssignable(t, s, warner);
3121 }
3122 // </editor-fold>
3124 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3125 /**
3126 * Return the class that boxes the given primitive.
3127 */
3128 public ClassSymbol boxedClass(Type t) {
3129 return reader.enterClass(syms.boxedName[t.tag]);
3130 }
3132 /**
3133 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3134 */
3135 public Type boxedTypeOrType(Type t) {
3136 return t.isPrimitive() ?
3137 boxedClass(t).type :
3138 t;
3139 }
3141 /**
3142 * Return the primitive type corresponding to a boxed type.
3143 */
3144 public Type unboxedType(Type t) {
3145 if (allowBoxing) {
3146 for (int i=0; i<syms.boxedName.length; i++) {
3147 Name box = syms.boxedName[i];
3148 if (box != null &&
3149 asSuper(t, reader.enterClass(box)) != null)
3150 return syms.typeOfTag[i];
3151 }
3152 }
3153 return Type.noType;
3154 }
3155 // </editor-fold>
3157 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3158 /*
3159 * JLS 5.1.10 Capture Conversion:
3160 *
3161 * Let G name a generic type declaration with n formal type
3162 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3163 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3164 * where, for 1 <= i <= n:
3165 *
3166 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3167 * Si is a fresh type variable whose upper bound is
3168 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3169 * type.
3170 *
3171 * + If Ti is a wildcard type argument of the form ? extends Bi,
3172 * then Si is a fresh type variable whose upper bound is
3173 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3174 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3175 * a compile-time error if for any two classes (not interfaces)
3176 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3177 *
3178 * + If Ti is a wildcard type argument of the form ? super Bi,
3179 * then Si is a fresh type variable whose upper bound is
3180 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3181 *
3182 * + Otherwise, Si = Ti.
3183 *
3184 * Capture conversion on any type other than a parameterized type
3185 * (4.5) acts as an identity conversion (5.1.1). Capture
3186 * conversions never require a special action at run time and
3187 * therefore never throw an exception at run time.
3188 *
3189 * Capture conversion is not applied recursively.
3190 */
3191 /**
3192 * Capture conversion as specified by the JLS.
3193 */
3195 public List<Type> capture(List<Type> ts) {
3196 List<Type> buf = List.nil();
3197 for (Type t : ts) {
3198 buf = buf.prepend(capture(t));
3199 }
3200 return buf.reverse();
3201 }
3202 public Type capture(Type t) {
3203 if (t.tag != CLASS)
3204 return t;
3205 if (t.getEnclosingType() != Type.noType) {
3206 Type capturedEncl = capture(t.getEnclosingType());
3207 if (capturedEncl != t.getEnclosingType()) {
3208 Type type1 = memberType(capturedEncl, t.tsym);
3209 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3210 }
3211 }
3212 ClassType cls = (ClassType)t;
3213 if (cls.isRaw() || !cls.isParameterized())
3214 return cls;
3216 ClassType G = (ClassType)cls.asElement().asType();
3217 List<Type> A = G.getTypeArguments();
3218 List<Type> T = cls.getTypeArguments();
3219 List<Type> S = freshTypeVariables(T);
3221 List<Type> currentA = A;
3222 List<Type> currentT = T;
3223 List<Type> currentS = S;
3224 boolean captured = false;
3225 while (!currentA.isEmpty() &&
3226 !currentT.isEmpty() &&
3227 !currentS.isEmpty()) {
3228 if (currentS.head != currentT.head) {
3229 captured = true;
3230 WildcardType Ti = (WildcardType)currentT.head;
3231 Type Ui = currentA.head.getUpperBound();
3232 CapturedType Si = (CapturedType)currentS.head;
3233 if (Ui == null)
3234 Ui = syms.objectType;
3235 switch (Ti.kind) {
3236 case UNBOUND:
3237 Si.bound = subst(Ui, A, S);
3238 Si.lower = syms.botType;
3239 break;
3240 case EXTENDS:
3241 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3242 Si.lower = syms.botType;
3243 break;
3244 case SUPER:
3245 Si.bound = subst(Ui, A, S);
3246 Si.lower = Ti.getSuperBound();
3247 break;
3248 }
3249 if (Si.bound == Si.lower)
3250 currentS.head = Si.bound;
3251 }
3252 currentA = currentA.tail;
3253 currentT = currentT.tail;
3254 currentS = currentS.tail;
3255 }
3256 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3257 return erasure(t); // some "rare" type involved
3259 if (captured)
3260 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3261 else
3262 return t;
3263 }
3264 // where
3265 public List<Type> freshTypeVariables(List<Type> types) {
3266 ListBuffer<Type> result = lb();
3267 for (Type t : types) {
3268 if (t.tag == WILDCARD) {
3269 Type bound = ((WildcardType)t).getExtendsBound();
3270 if (bound == null)
3271 bound = syms.objectType;
3272 result.append(new CapturedType(capturedName,
3273 syms.noSymbol,
3274 bound,
3275 syms.botType,
3276 (WildcardType)t));
3277 } else {
3278 result.append(t);
3279 }
3280 }
3281 return result.toList();
3282 }
3283 // </editor-fold>
3285 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3286 private List<Type> upperBounds(List<Type> ss) {
3287 if (ss.isEmpty()) return ss;
3288 Type head = upperBound(ss.head);
3289 List<Type> tail = upperBounds(ss.tail);
3290 if (head != ss.head || tail != ss.tail)
3291 return tail.prepend(head);
3292 else
3293 return ss;
3294 }
3296 private boolean sideCast(Type from, Type to, Warner warn) {
3297 // We are casting from type $from$ to type $to$, which are
3298 // non-final unrelated types. This method
3299 // tries to reject a cast by transferring type parameters
3300 // from $to$ to $from$ by common superinterfaces.
3301 boolean reverse = false;
3302 Type target = to;
3303 if ((to.tsym.flags() & INTERFACE) == 0) {
3304 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3305 reverse = true;
3306 to = from;
3307 from = target;
3308 }
3309 List<Type> commonSupers = superClosure(to, erasure(from));
3310 boolean giveWarning = commonSupers.isEmpty();
3311 // The arguments to the supers could be unified here to
3312 // get a more accurate analysis
3313 while (commonSupers.nonEmpty()) {
3314 Type t1 = asSuper(from, commonSupers.head.tsym);
3315 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3316 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3317 return false;
3318 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3319 commonSupers = commonSupers.tail;
3320 }
3321 if (giveWarning && !isReifiable(reverse ? from : to))
3322 warn.warn(LintCategory.UNCHECKED);
3323 if (!allowCovariantReturns)
3324 // reject if there is a common method signature with
3325 // incompatible return types.
3326 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3327 return true;
3328 }
3330 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3331 // We are casting from type $from$ to type $to$, which are
3332 // unrelated types one of which is final and the other of
3333 // which is an interface. This method
3334 // tries to reject a cast by transferring type parameters
3335 // from the final class to the interface.
3336 boolean reverse = false;
3337 Type target = to;
3338 if ((to.tsym.flags() & INTERFACE) == 0) {
3339 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3340 reverse = true;
3341 to = from;
3342 from = target;
3343 }
3344 Assert.check((from.tsym.flags() & FINAL) != 0);
3345 Type t1 = asSuper(from, to.tsym);
3346 if (t1 == null) return false;
3347 Type t2 = to;
3348 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3349 return false;
3350 if (!allowCovariantReturns)
3351 // reject if there is a common method signature with
3352 // incompatible return types.
3353 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3354 if (!isReifiable(target) &&
3355 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3356 warn.warn(LintCategory.UNCHECKED);
3357 return true;
3358 }
3360 private boolean giveWarning(Type from, Type to) {
3361 Type subFrom = asSub(from, to.tsym);
3362 return to.isParameterized() &&
3363 (!(isUnbounded(to) ||
3364 isSubtype(from, to) ||
3365 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3366 }
3368 private List<Type> superClosure(Type t, Type s) {
3369 List<Type> cl = List.nil();
3370 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3371 if (isSubtype(s, erasure(l.head))) {
3372 cl = insert(cl, l.head);
3373 } else {
3374 cl = union(cl, superClosure(l.head, s));
3375 }
3376 }
3377 return cl;
3378 }
3380 private boolean containsTypeEquivalent(Type t, Type s) {
3381 return
3382 isSameType(t, s) || // shortcut
3383 containsType(t, s) && containsType(s, t);
3384 }
3386 // <editor-fold defaultstate="collapsed" desc="adapt">
3387 /**
3388 * Adapt a type by computing a substitution which maps a source
3389 * type to a target type.
3390 *
3391 * @param source the source type
3392 * @param target the target type
3393 * @param from the type variables of the computed substitution
3394 * @param to the types of the computed substitution.
3395 */
3396 public void adapt(Type source,
3397 Type target,
3398 ListBuffer<Type> from,
3399 ListBuffer<Type> to) throws AdaptFailure {
3400 new Adapter(from, to).adapt(source, target);
3401 }
3403 class Adapter extends SimpleVisitor<Void, Type> {
3405 ListBuffer<Type> from;
3406 ListBuffer<Type> to;
3407 Map<Symbol,Type> mapping;
3409 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3410 this.from = from;
3411 this.to = to;
3412 mapping = new HashMap<Symbol,Type>();
3413 }
3415 public void adapt(Type source, Type target) throws AdaptFailure {
3416 visit(source, target);
3417 List<Type> fromList = from.toList();
3418 List<Type> toList = to.toList();
3419 while (!fromList.isEmpty()) {
3420 Type val = mapping.get(fromList.head.tsym);
3421 if (toList.head != val)
3422 toList.head = val;
3423 fromList = fromList.tail;
3424 toList = toList.tail;
3425 }
3426 }
3428 @Override
3429 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3430 if (target.tag == CLASS)
3431 adaptRecursive(source.allparams(), target.allparams());
3432 return null;
3433 }
3435 @Override
3436 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3437 if (target.tag == ARRAY)
3438 adaptRecursive(elemtype(source), elemtype(target));
3439 return null;
3440 }
3442 @Override
3443 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3444 if (source.isExtendsBound())
3445 adaptRecursive(upperBound(source), upperBound(target));
3446 else if (source.isSuperBound())
3447 adaptRecursive(lowerBound(source), lowerBound(target));
3448 return null;
3449 }
3451 @Override
3452 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3453 // Check to see if there is
3454 // already a mapping for $source$, in which case
3455 // the old mapping will be merged with the new
3456 Type val = mapping.get(source.tsym);
3457 if (val != null) {
3458 if (val.isSuperBound() && target.isSuperBound()) {
3459 val = isSubtype(lowerBound(val), lowerBound(target))
3460 ? target : val;
3461 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3462 val = isSubtype(upperBound(val), upperBound(target))
3463 ? val : target;
3464 } else if (!isSameType(val, target)) {
3465 throw new AdaptFailure();
3466 }
3467 } else {
3468 val = target;
3469 from.append(source);
3470 to.append(target);
3471 }
3472 mapping.put(source.tsym, val);
3473 return null;
3474 }
3476 @Override
3477 public Void visitType(Type source, Type target) {
3478 return null;
3479 }
3481 private Set<TypePair> cache = new HashSet<TypePair>();
3483 private void adaptRecursive(Type source, Type target) {
3484 TypePair pair = new TypePair(source, target);
3485 if (cache.add(pair)) {
3486 try {
3487 visit(source, target);
3488 } finally {
3489 cache.remove(pair);
3490 }
3491 }
3492 }
3494 private void adaptRecursive(List<Type> source, List<Type> target) {
3495 if (source.length() == target.length()) {
3496 while (source.nonEmpty()) {
3497 adaptRecursive(source.head, target.head);
3498 source = source.tail;
3499 target = target.tail;
3500 }
3501 }
3502 }
3503 }
3505 public static class AdaptFailure extends RuntimeException {
3506 static final long serialVersionUID = -7490231548272701566L;
3507 }
3509 private void adaptSelf(Type t,
3510 ListBuffer<Type> from,
3511 ListBuffer<Type> to) {
3512 try {
3513 //if (t.tsym.type != t)
3514 adapt(t.tsym.type, t, from, to);
3515 } catch (AdaptFailure ex) {
3516 // Adapt should never fail calculating a mapping from
3517 // t.tsym.type to t as there can be no merge problem.
3518 throw new AssertionError(ex);
3519 }
3520 }
3521 // </editor-fold>
3523 /**
3524 * Rewrite all type variables (universal quantifiers) in the given
3525 * type to wildcards (existential quantifiers). This is used to
3526 * determine if a cast is allowed. For example, if high is true
3527 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3528 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3529 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3530 * List<Integer>} with a warning.
3531 * @param t a type
3532 * @param high if true return an upper bound; otherwise a lower
3533 * bound
3534 * @param rewriteTypeVars only rewrite captured wildcards if false;
3535 * otherwise rewrite all type variables
3536 * @return the type rewritten with wildcards (existential
3537 * quantifiers) only
3538 */
3539 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3540 return new Rewriter(high, rewriteTypeVars).visit(t);
3541 }
3543 class Rewriter extends UnaryVisitor<Type> {
3545 boolean high;
3546 boolean rewriteTypeVars;
3548 Rewriter(boolean high, boolean rewriteTypeVars) {
3549 this.high = high;
3550 this.rewriteTypeVars = rewriteTypeVars;
3551 }
3553 @Override
3554 public Type visitClassType(ClassType t, Void s) {
3555 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3556 boolean changed = false;
3557 for (Type arg : t.allparams()) {
3558 Type bound = visit(arg);
3559 if (arg != bound) {
3560 changed = true;
3561 }
3562 rewritten.append(bound);
3563 }
3564 if (changed)
3565 return subst(t.tsym.type,
3566 t.tsym.type.allparams(),
3567 rewritten.toList());
3568 else
3569 return t;
3570 }
3572 public Type visitType(Type t, Void s) {
3573 return high ? upperBound(t) : lowerBound(t);
3574 }
3576 @Override
3577 public Type visitCapturedType(CapturedType t, Void s) {
3578 Type w_bound = t.wildcard.type;
3579 Type bound = w_bound.contains(t) ?
3580 erasure(w_bound) :
3581 visit(w_bound);
3582 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
3583 }
3585 @Override
3586 public Type visitTypeVar(TypeVar t, Void s) {
3587 if (rewriteTypeVars) {
3588 Type bound = t.bound.contains(t) ?
3589 erasure(t.bound) :
3590 visit(t.bound);
3591 return rewriteAsWildcardType(bound, t, EXTENDS);
3592 } else {
3593 return t;
3594 }
3595 }
3597 @Override
3598 public Type visitWildcardType(WildcardType t, Void s) {
3599 Type bound2 = visit(t.type);
3600 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
3601 }
3603 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
3604 switch (bk) {
3605 case EXTENDS: return high ?
3606 makeExtendsWildcard(B(bound), formal) :
3607 makeExtendsWildcard(syms.objectType, formal);
3608 case SUPER: return high ?
3609 makeSuperWildcard(syms.botType, formal) :
3610 makeSuperWildcard(B(bound), formal);
3611 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
3612 default:
3613 Assert.error("Invalid bound kind " + bk);
3614 return null;
3615 }
3616 }
3618 Type B(Type t) {
3619 while (t.tag == WILDCARD) {
3620 WildcardType w = (WildcardType)t;
3621 t = high ?
3622 w.getExtendsBound() :
3623 w.getSuperBound();
3624 if (t == null) {
3625 t = high ? syms.objectType : syms.botType;
3626 }
3627 }
3628 return t;
3629 }
3630 }
3633 /**
3634 * Create a wildcard with the given upper (extends) bound; create
3635 * an unbounded wildcard if bound is Object.
3636 *
3637 * @param bound the upper bound
3638 * @param formal the formal type parameter that will be
3639 * substituted by the wildcard
3640 */
3641 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3642 if (bound == syms.objectType) {
3643 return new WildcardType(syms.objectType,
3644 BoundKind.UNBOUND,
3645 syms.boundClass,
3646 formal);
3647 } else {
3648 return new WildcardType(bound,
3649 BoundKind.EXTENDS,
3650 syms.boundClass,
3651 formal);
3652 }
3653 }
3655 /**
3656 * Create a wildcard with the given lower (super) bound; create an
3657 * unbounded wildcard if bound is bottom (type of {@code null}).
3658 *
3659 * @param bound the lower bound
3660 * @param formal the formal type parameter that will be
3661 * substituted by the wildcard
3662 */
3663 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3664 if (bound.tag == BOT) {
3665 return new WildcardType(syms.objectType,
3666 BoundKind.UNBOUND,
3667 syms.boundClass,
3668 formal);
3669 } else {
3670 return new WildcardType(bound,
3671 BoundKind.SUPER,
3672 syms.boundClass,
3673 formal);
3674 }
3675 }
3677 /**
3678 * A wrapper for a type that allows use in sets.
3679 */
3680 class SingletonType {
3681 final Type t;
3682 SingletonType(Type t) {
3683 this.t = t;
3684 }
3685 public int hashCode() {
3686 return Types.hashCode(t);
3687 }
3688 public boolean equals(Object obj) {
3689 return (obj instanceof SingletonType) &&
3690 isSameType(t, ((SingletonType)obj).t);
3691 }
3692 public String toString() {
3693 return t.toString();
3694 }
3695 }
3696 // </editor-fold>
3698 // <editor-fold defaultstate="collapsed" desc="Visitors">
3699 /**
3700 * A default visitor for types. All visitor methods except
3701 * visitType are implemented by delegating to visitType. Concrete
3702 * subclasses must provide an implementation of visitType and can
3703 * override other methods as needed.
3704 *
3705 * @param <R> the return type of the operation implemented by this
3706 * visitor; use Void if no return type is needed.
3707 * @param <S> the type of the second argument (the first being the
3708 * type itself) of the operation implemented by this visitor; use
3709 * Void if a second argument is not needed.
3710 */
3711 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3712 final public R visit(Type t, S s) { return t.accept(this, s); }
3713 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3714 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3715 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3716 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3717 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3718 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3719 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3720 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3721 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3722 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3723 }
3725 /**
3726 * A default visitor for symbols. All visitor methods except
3727 * visitSymbol are implemented by delegating to visitSymbol. Concrete
3728 * subclasses must provide an implementation of visitSymbol and can
3729 * override other methods as needed.
3730 *
3731 * @param <R> the return type of the operation implemented by this
3732 * visitor; use Void if no return type is needed.
3733 * @param <S> the type of the second argument (the first being the
3734 * symbol itself) of the operation implemented by this visitor; use
3735 * Void if a second argument is not needed.
3736 */
3737 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
3738 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
3739 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
3740 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
3741 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
3742 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
3743 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
3744 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
3745 }
3747 /**
3748 * A <em>simple</em> visitor for types. This visitor is simple as
3749 * captured wildcards, for-all types (generic methods), and
3750 * undetermined type variables (part of inference) are hidden.
3751 * Captured wildcards are hidden by treating them as type
3752 * variables and the rest are hidden by visiting their qtypes.
3753 *
3754 * @param <R> the return type of the operation implemented by this
3755 * visitor; use Void if no return type is needed.
3756 * @param <S> the type of the second argument (the first being the
3757 * type itself) of the operation implemented by this visitor; use
3758 * Void if a second argument is not needed.
3759 */
3760 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3761 @Override
3762 public R visitCapturedType(CapturedType t, S s) {
3763 return visitTypeVar(t, s);
3764 }
3765 @Override
3766 public R visitForAll(ForAll t, S s) {
3767 return visit(t.qtype, s);
3768 }
3769 @Override
3770 public R visitUndetVar(UndetVar t, S s) {
3771 return visit(t.qtype, s);
3772 }
3773 }
3775 /**
3776 * A plain relation on types. That is a 2-ary function on the
3777 * form Type × Type → Boolean.
3778 * <!-- In plain text: Type x Type -> Boolean -->
3779 */
3780 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3782 /**
3783 * A convenience visitor for implementing operations that only
3784 * require one argument (the type itself), that is, unary
3785 * operations.
3786 *
3787 * @param <R> the return type of the operation implemented by this
3788 * visitor; use Void if no return type is needed.
3789 */
3790 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3791 final public R visit(Type t) { return t.accept(this, null); }
3792 }
3794 /**
3795 * A visitor for implementing a mapping from types to types. The
3796 * default behavior of this class is to implement the identity
3797 * mapping (mapping a type to itself). This can be overridden in
3798 * subclasses.
3799 *
3800 * @param <S> the type of the second argument (the first being the
3801 * type itself) of this mapping; use Void if a second argument is
3802 * not needed.
3803 */
3804 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3805 final public Type visit(Type t) { return t.accept(this, null); }
3806 public Type visitType(Type t, S s) { return t; }
3807 }
3808 // </editor-fold>
3811 // <editor-fold defaultstate="collapsed" desc="Annotation support">
3813 public RetentionPolicy getRetention(Attribute.Compound a) {
3814 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
3815 Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
3816 if (c != null) {
3817 Attribute value = c.member(names.value);
3818 if (value != null && value instanceof Attribute.Enum) {
3819 Name levelName = ((Attribute.Enum)value).value.name;
3820 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
3821 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
3822 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
3823 else ;// /* fail soft */ throw new AssertionError(levelName);
3824 }
3825 }
3826 return vis;
3827 }
3828 // </editor-fold>
3829 }