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