Tue, 09 Oct 2012 19:31:58 -0700
8000208: fix langtools javadoc comment issues
Reviewed-by: bpatel, 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.code.Attribute.RetentionPolicy;
32 import com.sun.tools.javac.code.Lint.LintCategory;
33 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
34 import com.sun.tools.javac.comp.Check;
35 import com.sun.tools.javac.jvm.ClassReader;
36 import com.sun.tools.javac.util.*;
37 import com.sun.tools.javac.util.List;
38 import static com.sun.tools.javac.code.BoundKind.*;
39 import static com.sun.tools.javac.code.Flags.*;
40 import static com.sun.tools.javac.code.Scope.*;
41 import static com.sun.tools.javac.code.Symbol.*;
42 import static com.sun.tools.javac.code.Type.*;
43 import static com.sun.tools.javac.code.TypeTags.*;
44 import static com.sun.tools.javac.util.ListBuffer.lb;
46 /**
47 * Utility class containing various operations on types.
48 *
49 * <p>Unless other names are more illustrative, the following naming
50 * conventions should be observed in this file:
51 *
52 * <dl>
53 * <dt>t</dt>
54 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
55 * <dt>s</dt>
56 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
57 * <dt>ts</dt>
58 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
59 * <dt>ss</dt>
60 * <dd>A second list of types should be named ss.</dd>
61 * </dl>
62 *
63 * <p><b>This is NOT part of any supported API.
64 * If you write code that depends on this, you do so at your own risk.
65 * This code and its internal interfaces are subject to change or
66 * deletion without notice.</b>
67 */
68 public class Types {
69 protected static final Context.Key<Types> typesKey =
70 new Context.Key<Types>();
72 final Symtab syms;
73 final JavacMessages messages;
74 final Names names;
75 final boolean allowBoxing;
76 final boolean allowCovariantReturns;
77 final boolean allowObjectToPrimitiveCast;
78 final ClassReader reader;
79 final Check chk;
80 JCDiagnostic.Factory diags;
81 List<Warner> warnStack = List.nil();
82 final Name capturedName;
83 private final FunctionDescriptorLookupError functionDescriptorLookupError;
85 // <editor-fold defaultstate="collapsed" desc="Instantiating">
86 public static Types instance(Context context) {
87 Types instance = context.get(typesKey);
88 if (instance == null)
89 instance = new Types(context);
90 return instance;
91 }
93 protected Types(Context context) {
94 context.put(typesKey, this);
95 syms = Symtab.instance(context);
96 names = Names.instance(context);
97 Source source = Source.instance(context);
98 allowBoxing = source.allowBoxing();
99 allowCovariantReturns = source.allowCovariantReturns();
100 allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
101 reader = ClassReader.instance(context);
102 chk = Check.instance(context);
103 capturedName = names.fromString("<captured wildcard>");
104 messages = JavacMessages.instance(context);
105 diags = JCDiagnostic.Factory.instance(context);
106 functionDescriptorLookupError = new FunctionDescriptorLookupError();
107 }
108 // </editor-fold>
110 // <editor-fold defaultstate="collapsed" desc="upperBound">
111 /**
112 * The "rvalue conversion".<br>
113 * The upper bound of most types is the type
114 * itself. Wildcards, on the other hand have upper
115 * and lower bounds.
116 * @param t a type
117 * @return the upper bound of the given type
118 */
119 public Type upperBound(Type t) {
120 return upperBound.visit(t);
121 }
122 // where
123 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
125 @Override
126 public Type visitWildcardType(WildcardType t, Void ignored) {
127 if (t.isSuperBound())
128 return t.bound == null ? syms.objectType : t.bound.bound;
129 else
130 return visit(t.type);
131 }
133 @Override
134 public Type visitCapturedType(CapturedType t, Void ignored) {
135 return visit(t.bound);
136 }
137 };
138 // </editor-fold>
140 // <editor-fold defaultstate="collapsed" desc="lowerBound">
141 /**
142 * The "lvalue conversion".<br>
143 * The lower bound of most types is the type
144 * itself. Wildcards, on the other hand have upper
145 * and lower bounds.
146 * @param t a type
147 * @return the lower bound of the given type
148 */
149 public Type lowerBound(Type t) {
150 return lowerBound.visit(t);
151 }
152 // where
153 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
155 @Override
156 public Type visitWildcardType(WildcardType t, Void ignored) {
157 return t.isExtendsBound() ? syms.botType : visit(t.type);
158 }
160 @Override
161 public Type visitCapturedType(CapturedType t, Void ignored) {
162 return visit(t.getLowerBound());
163 }
164 };
165 // </editor-fold>
167 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
168 /**
169 * Checks that all the arguments to a class are unbounded
170 * wildcards or something else that doesn't make any restrictions
171 * on the arguments. If a class isUnbounded, a raw super- or
172 * subclass can be cast to it without a warning.
173 * @param t a type
174 * @return true iff the given type is unbounded or raw
175 */
176 public boolean isUnbounded(Type t) {
177 return isUnbounded.visit(t);
178 }
179 // where
180 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
182 public Boolean visitType(Type t, Void ignored) {
183 return true;
184 }
186 @Override
187 public Boolean visitClassType(ClassType t, Void ignored) {
188 List<Type> parms = t.tsym.type.allparams();
189 List<Type> args = t.allparams();
190 while (parms.nonEmpty()) {
191 WildcardType unb = new WildcardType(syms.objectType,
192 BoundKind.UNBOUND,
193 syms.boundClass,
194 (TypeVar)parms.head);
195 if (!containsType(args.head, unb))
196 return false;
197 parms = parms.tail;
198 args = args.tail;
199 }
200 return true;
201 }
202 };
203 // </editor-fold>
205 // <editor-fold defaultstate="collapsed" desc="asSub">
206 /**
207 * Return the least specific subtype of t that starts with symbol
208 * sym. If none exists, return null. The least specific subtype
209 * is determined as follows:
210 *
211 * <p>If there is exactly one parameterized instance of sym that is a
212 * subtype of t, that parameterized instance is returned.<br>
213 * Otherwise, if the plain type or raw type `sym' is a subtype of
214 * type t, the type `sym' itself is returned. Otherwise, null is
215 * returned.
216 */
217 public Type asSub(Type t, Symbol sym) {
218 return asSub.visit(t, sym);
219 }
220 // where
221 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
223 public Type visitType(Type t, Symbol sym) {
224 return null;
225 }
227 @Override
228 public Type visitClassType(ClassType t, Symbol sym) {
229 if (t.tsym == sym)
230 return t;
231 Type base = asSuper(sym.type, t.tsym);
232 if (base == null)
233 return null;
234 ListBuffer<Type> from = new ListBuffer<Type>();
235 ListBuffer<Type> to = new ListBuffer<Type>();
236 try {
237 adapt(base, t, from, to);
238 } catch (AdaptFailure ex) {
239 return null;
240 }
241 Type res = subst(sym.type, from.toList(), to.toList());
242 if (!isSubtype(res, t))
243 return null;
244 ListBuffer<Type> openVars = new ListBuffer<Type>();
245 for (List<Type> l = sym.type.allparams();
246 l.nonEmpty(); l = l.tail)
247 if (res.contains(l.head) && !t.contains(l.head))
248 openVars.append(l.head);
249 if (openVars.nonEmpty()) {
250 if (t.isRaw()) {
251 // The subtype of a raw type is raw
252 res = erasure(res);
253 } else {
254 // Unbound type arguments default to ?
255 List<Type> opens = openVars.toList();
256 ListBuffer<Type> qs = new ListBuffer<Type>();
257 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
258 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
259 }
260 res = subst(res, opens, qs.toList());
261 }
262 }
263 return res;
264 }
266 @Override
267 public Type visitErrorType(ErrorType t, Symbol sym) {
268 return t;
269 }
270 };
271 // </editor-fold>
273 // <editor-fold defaultstate="collapsed" desc="isConvertible">
274 /**
275 * Is t a subtype of or convertible via boxing/unboxing
276 * conversion to s?
277 */
278 public boolean isConvertible(Type t, Type s, Warner warn) {
279 if (t.tag == ERROR)
280 return true;
281 boolean tPrimitive = t.isPrimitive();
282 boolean sPrimitive = s.isPrimitive();
283 if (tPrimitive == sPrimitive) {
284 return isSubtypeUnchecked(t, s, warn);
285 }
286 if (!allowBoxing) return false;
287 return tPrimitive
288 ? isSubtype(boxedClass(t).type, s)
289 : isSubtype(unboxedType(t), s);
290 }
292 /**
293 * Is t a subtype of or convertiable via boxing/unboxing
294 * convertions to s?
295 */
296 public boolean isConvertible(Type t, Type s) {
297 return isConvertible(t, s, Warner.noWarnings);
298 }
299 // </editor-fold>
301 // <editor-fold defaultstate="collapsed" desc="findSam">
303 /**
304 * Exception used to report a function descriptor lookup failure. The exception
305 * wraps a diagnostic that can be used to generate more details error
306 * messages.
307 */
308 public static class FunctionDescriptorLookupError extends RuntimeException {
309 private static final long serialVersionUID = 0;
311 JCDiagnostic diagnostic;
313 FunctionDescriptorLookupError() {
314 this.diagnostic = null;
315 }
317 FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
318 this.diagnostic = diag;
319 return this;
320 }
322 public JCDiagnostic getDiagnostic() {
323 return diagnostic;
324 }
325 }
327 /**
328 * A cache that keeps track of function descriptors associated with given
329 * functional interfaces.
330 */
331 class DescriptorCache {
333 private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
335 class FunctionDescriptor {
336 Symbol descSym;
338 FunctionDescriptor(Symbol descSym) {
339 this.descSym = descSym;
340 }
342 public Symbol getSymbol() {
343 return descSym;
344 }
346 public Type getType(Type origin) {
347 return memberType(origin, descSym);
348 }
349 }
351 class Entry {
352 final FunctionDescriptor cachedDescRes;
353 final int prevMark;
355 public Entry(FunctionDescriptor cachedDescRes,
356 int prevMark) {
357 this.cachedDescRes = cachedDescRes;
358 this.prevMark = prevMark;
359 }
361 boolean matches(int mark) {
362 return this.prevMark == mark;
363 }
364 }
366 FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
367 Entry e = _map.get(origin);
368 CompoundScope members = membersClosure(origin.type, false);
369 if (e == null ||
370 !e.matches(members.getMark())) {
371 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
372 _map.put(origin, new Entry(descRes, members.getMark()));
373 return descRes;
374 }
375 else {
376 return e.cachedDescRes;
377 }
378 }
380 /**
381 * Scope filter used to skip methods that should be ignored during
382 * function interface conversion (such as methods overridden by
383 * j.l.Object)
384 */
385 class DescriptorFilter implements Filter<Symbol> {
387 TypeSymbol origin;
389 DescriptorFilter(TypeSymbol origin) {
390 this.origin = origin;
391 }
393 @Override
394 public boolean accepts(Symbol sym) {
395 return sym.kind == Kinds.MTH &&
396 (sym.flags() & ABSTRACT) != 0 &&
397 !overridesObjectMethod(origin, sym) &&
398 notOverridden(sym);
399 }
401 private boolean notOverridden(Symbol msym) {
402 Symbol impl = ((MethodSymbol)msym).implementation(origin, Types.this, false);
403 return impl == null || (impl.flags() & ABSTRACT) != 0;
404 }
405 };
407 /**
408 * Compute the function descriptor associated with a given functional interface
409 */
410 public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
411 if (!origin.isInterface()) {
412 //t must be an interface
413 throw failure("not.a.functional.intf");
414 }
416 final ListBuffer<Symbol> abstracts = ListBuffer.lb();
417 for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
418 Type mtype = memberType(origin.type, sym);
419 if (abstracts.isEmpty() ||
420 (sym.name == abstracts.first().name &&
421 overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
422 abstracts.append(sym);
423 } else {
424 //the target method(s) should be the only abstract members of t
425 throw failure("not.a.functional.intf.1",
426 diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
427 }
428 }
429 if (abstracts.isEmpty()) {
430 //t must define a suitable non-generic method
431 throw failure("not.a.functional.intf.1",
432 diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
433 } else if (abstracts.size() == 1) {
434 if (abstracts.first().type.tag == FORALL) {
435 throw failure("invalid.generic.desc.in.functional.intf",
436 abstracts.first(),
437 Kinds.kindName(origin),
438 origin);
439 } else {
440 return new FunctionDescriptor(abstracts.first());
441 }
442 } else { // size > 1
443 for (Symbol msym : abstracts) {
444 if (msym.type.tag == FORALL) {
445 throw failure("invalid.generic.desc.in.functional.intf",
446 abstracts.first(),
447 Kinds.kindName(origin),
448 origin);
449 }
450 }
451 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
452 if (descRes == null) {
453 //we can get here if the functional interface is ill-formed
454 ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
455 for (Symbol desc : abstracts) {
456 String key = desc.type.getThrownTypes().nonEmpty() ?
457 "descriptor.throws" : "descriptor";
458 descriptors.append(diags.fragment(key, desc.name,
459 desc.type.getParameterTypes(),
460 desc.type.getReturnType(),
461 desc.type.getThrownTypes()));
462 }
463 JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
464 new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
465 Kinds.kindName(origin), origin), descriptors.toList());
466 throw failure(incompatibleDescriptors);
467 }
468 return descRes;
469 }
470 }
472 /**
473 * Compute a synthetic type for the target descriptor given a list
474 * of override-equivalent methods in the functional interface type.
475 * The resulting method type is a method type that is override-equivalent
476 * and return-type substitutable with each method in the original list.
477 */
478 private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
479 //pick argument types - simply take the signature that is a
480 //subsignature of all other signatures in the list (as per JLS 8.4.2)
481 List<Symbol> mostSpecific = List.nil();
482 outer: for (Symbol msym1 : methodSyms) {
483 Type mt1 = memberType(origin.type, msym1);
484 for (Symbol msym2 : methodSyms) {
485 Type mt2 = memberType(origin.type, msym2);
486 if (!isSubSignature(mt1, mt2)) {
487 continue outer;
488 }
489 }
490 mostSpecific = mostSpecific.prepend(msym1);
491 }
492 if (mostSpecific.isEmpty()) {
493 return null;
494 }
497 //pick return types - this is done in two phases: (i) first, the most
498 //specific return type is chosen using strict subtyping; if this fails,
499 //a second attempt is made using return type substitutability (see JLS 8.4.5)
500 boolean phase2 = false;
501 Symbol bestSoFar = null;
502 while (bestSoFar == null) {
503 outer: for (Symbol msym1 : mostSpecific) {
504 Type mt1 = memberType(origin.type, msym1);
505 for (Symbol msym2 : methodSyms) {
506 Type mt2 = memberType(origin.type, msym2);
507 if (phase2 ?
508 !returnTypeSubstitutable(mt1, mt2) :
509 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
510 continue outer;
511 }
512 }
513 bestSoFar = msym1;
514 }
515 if (phase2) {
516 break;
517 } else {
518 phase2 = true;
519 }
520 }
521 if (bestSoFar == null) return null;
523 //merge thrown types - form the intersection of all the thrown types in
524 //all the signatures in the list
525 List<Type> thrown = null;
526 for (Symbol msym1 : methodSyms) {
527 Type mt1 = memberType(origin.type, msym1);
528 thrown = (thrown == null) ?
529 mt1.getThrownTypes() :
530 chk.intersect(mt1.getThrownTypes(), thrown);
531 }
533 final List<Type> thrown1 = thrown;
534 return new FunctionDescriptor(bestSoFar) {
535 @Override
536 public Type getType(Type origin) {
537 Type mt = memberType(origin, getSymbol());
538 return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
539 }
540 };
541 }
543 boolean isSubtypeInternal(Type s, Type t) {
544 return (s.isPrimitive() && t.isPrimitive()) ?
545 isSameType(t, s) :
546 isSubtype(s, t);
547 }
549 FunctionDescriptorLookupError failure(String msg, Object... args) {
550 return failure(diags.fragment(msg, args));
551 }
553 FunctionDescriptorLookupError failure(JCDiagnostic diag) {
554 return functionDescriptorLookupError.setMessage(diag);
555 }
556 }
558 private DescriptorCache descCache = new DescriptorCache();
560 /**
561 * Find the method descriptor associated to this class symbol - if the
562 * symbol 'origin' is not a functional interface, an exception is thrown.
563 */
564 public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
565 return descCache.get(origin).getSymbol();
566 }
568 /**
569 * Find the type of the method descriptor associated to this class symbol -
570 * if the symbol 'origin' is not a functional interface, an exception is thrown.
571 */
572 public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
573 return descCache.get(origin.tsym).getType(origin);
574 }
576 /**
577 * Is given type a functional interface?
578 */
579 public boolean isFunctionalInterface(TypeSymbol tsym) {
580 try {
581 findDescriptorSymbol(tsym);
582 return true;
583 } catch (FunctionDescriptorLookupError ex) {
584 return false;
585 }
586 }
587 // </editor-fold>
589 // <editor-fold defaultstate="collapsed" desc="isSubtype">
590 /**
591 * Is t an unchecked subtype of s?
592 */
593 public boolean isSubtypeUnchecked(Type t, Type s) {
594 return isSubtypeUnchecked(t, s, Warner.noWarnings);
595 }
596 /**
597 * Is t an unchecked subtype of s?
598 */
599 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
600 boolean result = isSubtypeUncheckedInternal(t, s, warn);
601 if (result) {
602 checkUnsafeVarargsConversion(t, s, warn);
603 }
604 return result;
605 }
606 //where
607 private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
608 if (t.tag == ARRAY && s.tag == ARRAY) {
609 if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
610 return isSameType(elemtype(t), elemtype(s));
611 } else {
612 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
613 }
614 } else if (isSubtype(t, s)) {
615 return true;
616 }
617 else if (t.tag == TYPEVAR) {
618 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
619 }
620 else if (!s.isRaw()) {
621 Type t2 = asSuper(t, s.tsym);
622 if (t2 != null && t2.isRaw()) {
623 if (isReifiable(s))
624 warn.silentWarn(LintCategory.UNCHECKED);
625 else
626 warn.warn(LintCategory.UNCHECKED);
627 return true;
628 }
629 }
630 return false;
631 }
633 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
634 if (t.tag != ARRAY || isReifiable(t)) return;
635 ArrayType from = (ArrayType)t;
636 boolean shouldWarn = false;
637 switch (s.tag) {
638 case ARRAY:
639 ArrayType to = (ArrayType)s;
640 shouldWarn = from.isVarargs() &&
641 !to.isVarargs() &&
642 !isReifiable(from);
643 break;
644 case CLASS:
645 shouldWarn = from.isVarargs();
646 break;
647 }
648 if (shouldWarn) {
649 warn.warn(LintCategory.VARARGS);
650 }
651 }
653 /**
654 * Is t a subtype of s?<br>
655 * (not defined for Method and ForAll types)
656 */
657 final public boolean isSubtype(Type t, Type s) {
658 return isSubtype(t, s, true);
659 }
660 final public boolean isSubtypeNoCapture(Type t, Type s) {
661 return isSubtype(t, s, false);
662 }
663 public boolean isSubtype(Type t, Type s, boolean capture) {
664 if (t == s)
665 return true;
667 if (s.tag >= firstPartialTag)
668 return isSuperType(s, t);
670 if (s.isCompound()) {
671 for (Type s2 : interfaces(s).prepend(supertype(s))) {
672 if (!isSubtype(t, s2, capture))
673 return false;
674 }
675 return true;
676 }
678 Type lower = lowerBound(s);
679 if (s != lower)
680 return isSubtype(capture ? capture(t) : t, lower, false);
682 return isSubtype.visit(capture ? capture(t) : t, s);
683 }
684 // where
685 private TypeRelation isSubtype = new TypeRelation()
686 {
687 public Boolean visitType(Type t, Type s) {
688 switch (t.tag) {
689 case BYTE: case CHAR:
690 return (t.tag == s.tag ||
691 t.tag + 2 <= s.tag && s.tag <= DOUBLE);
692 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
693 return t.tag <= s.tag && s.tag <= DOUBLE;
694 case BOOLEAN: case VOID:
695 return t.tag == s.tag;
696 case TYPEVAR:
697 return isSubtypeNoCapture(t.getUpperBound(), s);
698 case BOT:
699 return
700 s.tag == BOT || s.tag == CLASS ||
701 s.tag == ARRAY || s.tag == TYPEVAR;
702 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
703 case NONE:
704 return false;
705 default:
706 throw new AssertionError("isSubtype " + t.tag);
707 }
708 }
710 private Set<TypePair> cache = new HashSet<TypePair>();
712 private boolean containsTypeRecursive(Type t, Type s) {
713 TypePair pair = new TypePair(t, s);
714 if (cache.add(pair)) {
715 try {
716 return containsType(t.getTypeArguments(),
717 s.getTypeArguments());
718 } finally {
719 cache.remove(pair);
720 }
721 } else {
722 return containsType(t.getTypeArguments(),
723 rewriteSupers(s).getTypeArguments());
724 }
725 }
727 private Type rewriteSupers(Type t) {
728 if (!t.isParameterized())
729 return t;
730 ListBuffer<Type> from = lb();
731 ListBuffer<Type> to = lb();
732 adaptSelf(t, from, to);
733 if (from.isEmpty())
734 return t;
735 ListBuffer<Type> rewrite = lb();
736 boolean changed = false;
737 for (Type orig : to.toList()) {
738 Type s = rewriteSupers(orig);
739 if (s.isSuperBound() && !s.isExtendsBound()) {
740 s = new WildcardType(syms.objectType,
741 BoundKind.UNBOUND,
742 syms.boundClass);
743 changed = true;
744 } else if (s != orig) {
745 s = new WildcardType(upperBound(s),
746 BoundKind.EXTENDS,
747 syms.boundClass);
748 changed = true;
749 }
750 rewrite.append(s);
751 }
752 if (changed)
753 return subst(t.tsym.type, from.toList(), rewrite.toList());
754 else
755 return t;
756 }
758 @Override
759 public Boolean visitClassType(ClassType t, Type s) {
760 Type sup = asSuper(t, s.tsym);
761 return sup != null
762 && sup.tsym == s.tsym
763 // You're not allowed to write
764 // Vector<Object> vec = new Vector<String>();
765 // But with wildcards you can write
766 // Vector<? extends Object> vec = new Vector<String>();
767 // which means that subtype checking must be done
768 // here instead of same-type checking (via containsType).
769 && (!s.isParameterized() || containsTypeRecursive(s, sup))
770 && isSubtypeNoCapture(sup.getEnclosingType(),
771 s.getEnclosingType());
772 }
774 @Override
775 public Boolean visitArrayType(ArrayType t, Type s) {
776 if (s.tag == ARRAY) {
777 if (t.elemtype.tag <= lastBaseTag)
778 return isSameType(t.elemtype, elemtype(s));
779 else
780 return isSubtypeNoCapture(t.elemtype, elemtype(s));
781 }
783 if (s.tag == CLASS) {
784 Name sname = s.tsym.getQualifiedName();
785 return sname == names.java_lang_Object
786 || sname == names.java_lang_Cloneable
787 || sname == names.java_io_Serializable;
788 }
790 return false;
791 }
793 @Override
794 public Boolean visitUndetVar(UndetVar t, Type s) {
795 //todo: test against origin needed? or replace with substitution?
796 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
797 return true;
798 } else if (s.tag == BOT) {
799 //if 's' is 'null' there's no instantiated type U for which
800 //U <: s (but 'null' itself, which is not a valid type)
801 return false;
802 }
804 t.addBound(InferenceBound.UPPER, s, Types.this);
805 return true;
806 }
808 @Override
809 public Boolean visitErrorType(ErrorType t, Type s) {
810 return true;
811 }
812 };
814 /**
815 * Is t a subtype of every type in given list `ts'?<br>
816 * (not defined for Method and ForAll types)<br>
817 * Allows unchecked conversions.
818 */
819 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
820 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
821 if (!isSubtypeUnchecked(t, l.head, warn))
822 return false;
823 return true;
824 }
826 /**
827 * Are corresponding elements of ts subtypes of ss? If lists are
828 * of different length, return false.
829 */
830 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
831 while (ts.tail != null && ss.tail != null
832 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
833 isSubtype(ts.head, ss.head)) {
834 ts = ts.tail;
835 ss = ss.tail;
836 }
837 return ts.tail == null && ss.tail == null;
838 /*inlined: ts.isEmpty() && ss.isEmpty();*/
839 }
841 /**
842 * Are corresponding elements of ts subtypes of ss, allowing
843 * unchecked conversions? If lists are of different length,
844 * return false.
845 **/
846 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
847 while (ts.tail != null && ss.tail != null
848 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
849 isSubtypeUnchecked(ts.head, ss.head, warn)) {
850 ts = ts.tail;
851 ss = ss.tail;
852 }
853 return ts.tail == null && ss.tail == null;
854 /*inlined: ts.isEmpty() && ss.isEmpty();*/
855 }
856 // </editor-fold>
858 // <editor-fold defaultstate="collapsed" desc="isSuperType">
859 /**
860 * Is t a supertype of s?
861 */
862 public boolean isSuperType(Type t, Type s) {
863 switch (t.tag) {
864 case ERROR:
865 return true;
866 case UNDETVAR: {
867 UndetVar undet = (UndetVar)t;
868 if (t == s ||
869 undet.qtype == s ||
870 s.tag == ERROR ||
871 s.tag == BOT) return true;
872 undet.addBound(InferenceBound.LOWER, s, this);
873 return true;
874 }
875 default:
876 return isSubtype(s, t);
877 }
878 }
879 // </editor-fold>
881 // <editor-fold defaultstate="collapsed" desc="isSameType">
882 /**
883 * Are corresponding elements of the lists the same type? If
884 * lists are of different length, return false.
885 */
886 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
887 while (ts.tail != null && ss.tail != null
888 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
889 isSameType(ts.head, ss.head)) {
890 ts = ts.tail;
891 ss = ss.tail;
892 }
893 return ts.tail == null && ss.tail == null;
894 /*inlined: ts.isEmpty() && ss.isEmpty();*/
895 }
897 /**
898 * Is t the same type as s?
899 */
900 public boolean isSameType(Type t, Type s) {
901 return isSameType.visit(t, s);
902 }
903 // where
904 private TypeRelation isSameType = new TypeRelation() {
906 public Boolean visitType(Type t, Type s) {
907 if (t == s)
908 return true;
910 if (s.tag >= firstPartialTag)
911 return visit(s, t);
913 switch (t.tag) {
914 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
915 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
916 return t.tag == s.tag;
917 case TYPEVAR: {
918 if (s.tag == TYPEVAR) {
919 //type-substitution does not preserve type-var types
920 //check that type var symbols and bounds are indeed the same
921 return t.tsym == s.tsym &&
922 visit(t.getUpperBound(), s.getUpperBound());
923 }
924 else {
925 //special case for s == ? super X, where upper(s) = u
926 //check that u == t, where u has been set by Type.withTypeVar
927 return s.isSuperBound() &&
928 !s.isExtendsBound() &&
929 visit(t, upperBound(s));
930 }
931 }
932 default:
933 throw new AssertionError("isSameType " + t.tag);
934 }
935 }
937 @Override
938 public Boolean visitWildcardType(WildcardType t, Type s) {
939 if (s.tag >= firstPartialTag)
940 return visit(s, t);
941 else
942 return false;
943 }
945 @Override
946 public Boolean visitClassType(ClassType t, Type s) {
947 if (t == s)
948 return true;
950 if (s.tag >= firstPartialTag)
951 return visit(s, t);
953 if (s.isSuperBound() && !s.isExtendsBound())
954 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
956 if (t.isCompound() && s.isCompound()) {
957 if (!visit(supertype(t), supertype(s)))
958 return false;
960 HashSet<SingletonType> set = new HashSet<SingletonType>();
961 for (Type x : interfaces(t))
962 set.add(new SingletonType(x));
963 for (Type x : interfaces(s)) {
964 if (!set.remove(new SingletonType(x)))
965 return false;
966 }
967 return (set.isEmpty());
968 }
969 return t.tsym == s.tsym
970 && visit(t.getEnclosingType(), s.getEnclosingType())
971 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
972 }
974 @Override
975 public Boolean visitArrayType(ArrayType t, Type s) {
976 if (t == s)
977 return true;
979 if (s.tag >= firstPartialTag)
980 return visit(s, t);
982 return s.tag == ARRAY
983 && containsTypeEquivalent(t.elemtype, elemtype(s));
984 }
986 @Override
987 public Boolean visitMethodType(MethodType t, Type s) {
988 // isSameType for methods does not take thrown
989 // exceptions into account!
990 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
991 }
993 @Override
994 public Boolean visitPackageType(PackageType t, Type s) {
995 return t == s;
996 }
998 @Override
999 public Boolean visitForAll(ForAll t, Type s) {
1000 if (s.tag != FORALL)
1001 return false;
1003 ForAll forAll = (ForAll)s;
1004 return hasSameBounds(t, forAll)
1005 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1006 }
1008 @Override
1009 public Boolean visitUndetVar(UndetVar t, Type s) {
1010 if (s.tag == WILDCARD)
1011 // FIXME, this might be leftovers from before capture conversion
1012 return false;
1014 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
1015 return true;
1017 t.addBound(InferenceBound.EQ, s, Types.this);
1019 return true;
1020 }
1022 @Override
1023 public Boolean visitErrorType(ErrorType t, Type s) {
1024 return true;
1025 }
1026 };
1027 // </editor-fold>
1029 // <editor-fold defaultstate="collapsed" desc="Contains Type">
1030 public boolean containedBy(Type t, Type s) {
1031 switch (t.tag) {
1032 case UNDETVAR:
1033 if (s.tag == WILDCARD) {
1034 UndetVar undetvar = (UndetVar)t;
1035 WildcardType wt = (WildcardType)s;
1036 switch(wt.kind) {
1037 case UNBOUND: //similar to ? extends Object
1038 case EXTENDS: {
1039 Type bound = upperBound(s);
1040 undetvar.addBound(InferenceBound.UPPER, bound, this);
1041 break;
1042 }
1043 case SUPER: {
1044 Type bound = lowerBound(s);
1045 undetvar.addBound(InferenceBound.LOWER, bound, this);
1046 break;
1047 }
1048 }
1049 return true;
1050 } else {
1051 return isSameType(t, s);
1052 }
1053 case ERROR:
1054 return true;
1055 default:
1056 return containsType(s, t);
1057 }
1058 }
1060 boolean containsType(List<Type> ts, List<Type> ss) {
1061 while (ts.nonEmpty() && ss.nonEmpty()
1062 && containsType(ts.head, ss.head)) {
1063 ts = ts.tail;
1064 ss = ss.tail;
1065 }
1066 return ts.isEmpty() && ss.isEmpty();
1067 }
1069 /**
1070 * Check if t contains s.
1071 *
1072 * <p>T contains S if:
1073 *
1074 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1075 *
1076 * <p>This relation is only used by ClassType.isSubtype(), that
1077 * is,
1078 *
1079 * <p>{@code C<S> <: C<T> if T contains S.}
1080 *
1081 * <p>Because of F-bounds, this relation can lead to infinite
1082 * recursion. Thus we must somehow break that recursion. Notice
1083 * that containsType() is only called from ClassType.isSubtype().
1084 * Since the arguments have already been checked against their
1085 * bounds, we know:
1086 *
1087 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1088 *
1089 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1090 *
1091 * @param t a type
1092 * @param s a type
1093 */
1094 public boolean containsType(Type t, Type s) {
1095 return containsType.visit(t, s);
1096 }
1097 // where
1098 private TypeRelation containsType = new TypeRelation() {
1100 private Type U(Type t) {
1101 while (t.tag == WILDCARD) {
1102 WildcardType w = (WildcardType)t;
1103 if (w.isSuperBound())
1104 return w.bound == null ? syms.objectType : w.bound.bound;
1105 else
1106 t = w.type;
1107 }
1108 return t;
1109 }
1111 private Type L(Type t) {
1112 while (t.tag == WILDCARD) {
1113 WildcardType w = (WildcardType)t;
1114 if (w.isExtendsBound())
1115 return syms.botType;
1116 else
1117 t = w.type;
1118 }
1119 return t;
1120 }
1122 public Boolean visitType(Type t, Type s) {
1123 if (s.tag >= firstPartialTag)
1124 return containedBy(s, t);
1125 else
1126 return isSameType(t, s);
1127 }
1129 // void debugContainsType(WildcardType t, Type s) {
1130 // System.err.println();
1131 // System.err.format(" does %s contain %s?%n", t, s);
1132 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1133 // upperBound(s), s, t, U(t),
1134 // t.isSuperBound()
1135 // || isSubtypeNoCapture(upperBound(s), U(t)));
1136 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1137 // L(t), t, s, lowerBound(s),
1138 // t.isExtendsBound()
1139 // || isSubtypeNoCapture(L(t), lowerBound(s)));
1140 // System.err.println();
1141 // }
1143 @Override
1144 public Boolean visitWildcardType(WildcardType t, Type s) {
1145 if (s.tag >= firstPartialTag)
1146 return containedBy(s, t);
1147 else {
1148 // debugContainsType(t, s);
1149 return isSameWildcard(t, s)
1150 || isCaptureOf(s, t)
1151 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
1152 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
1153 }
1154 }
1156 @Override
1157 public Boolean visitUndetVar(UndetVar t, Type s) {
1158 if (s.tag != WILDCARD)
1159 return isSameType(t, s);
1160 else
1161 return false;
1162 }
1164 @Override
1165 public Boolean visitErrorType(ErrorType t, Type s) {
1166 return true;
1167 }
1168 };
1170 public boolean isCaptureOf(Type s, WildcardType t) {
1171 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
1172 return false;
1173 return isSameWildcard(t, ((CapturedType)s).wildcard);
1174 }
1176 public boolean isSameWildcard(WildcardType t, Type s) {
1177 if (s.tag != WILDCARD)
1178 return false;
1179 WildcardType w = (WildcardType)s;
1180 return w.kind == t.kind && w.type == t.type;
1181 }
1183 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1184 while (ts.nonEmpty() && ss.nonEmpty()
1185 && containsTypeEquivalent(ts.head, ss.head)) {
1186 ts = ts.tail;
1187 ss = ss.tail;
1188 }
1189 return ts.isEmpty() && ss.isEmpty();
1190 }
1191 // </editor-fold>
1193 // <editor-fold defaultstate="collapsed" desc="isCastable">
1194 public boolean isCastable(Type t, Type s) {
1195 return isCastable(t, s, Warner.noWarnings);
1196 }
1198 /**
1199 * Is t is castable to s?<br>
1200 * s is assumed to be an erased type.<br>
1201 * (not defined for Method and ForAll types).
1202 */
1203 public boolean isCastable(Type t, Type s, Warner warn) {
1204 if (t == s)
1205 return true;
1207 if (t.isPrimitive() != s.isPrimitive())
1208 return allowBoxing && (
1209 isConvertible(t, s, warn)
1210 || (allowObjectToPrimitiveCast &&
1211 s.isPrimitive() &&
1212 isSubtype(boxedClass(s).type, t)));
1213 if (warn != warnStack.head) {
1214 try {
1215 warnStack = warnStack.prepend(warn);
1216 checkUnsafeVarargsConversion(t, s, warn);
1217 return isCastable.visit(t,s);
1218 } finally {
1219 warnStack = warnStack.tail;
1220 }
1221 } else {
1222 return isCastable.visit(t,s);
1223 }
1224 }
1225 // where
1226 private TypeRelation isCastable = new TypeRelation() {
1228 public Boolean visitType(Type t, Type s) {
1229 if (s.tag == ERROR)
1230 return true;
1232 switch (t.tag) {
1233 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1234 case DOUBLE:
1235 return s.tag <= DOUBLE;
1236 case BOOLEAN:
1237 return s.tag == BOOLEAN;
1238 case VOID:
1239 return false;
1240 case BOT:
1241 return isSubtype(t, s);
1242 default:
1243 throw new AssertionError();
1244 }
1245 }
1247 @Override
1248 public Boolean visitWildcardType(WildcardType t, Type s) {
1249 return isCastable(upperBound(t), s, warnStack.head);
1250 }
1252 @Override
1253 public Boolean visitClassType(ClassType t, Type s) {
1254 if (s.tag == ERROR || s.tag == BOT)
1255 return true;
1257 if (s.tag == TYPEVAR) {
1258 if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
1259 warnStack.head.warn(LintCategory.UNCHECKED);
1260 return true;
1261 } else {
1262 return false;
1263 }
1264 }
1266 if (t.isCompound()) {
1267 Warner oldWarner = warnStack.head;
1268 warnStack.head = Warner.noWarnings;
1269 if (!visit(supertype(t), s))
1270 return false;
1271 for (Type intf : interfaces(t)) {
1272 if (!visit(intf, s))
1273 return false;
1274 }
1275 if (warnStack.head.hasLint(LintCategory.UNCHECKED))
1276 oldWarner.warn(LintCategory.UNCHECKED);
1277 return true;
1278 }
1280 if (s.isCompound()) {
1281 // call recursively to reuse the above code
1282 return visitClassType((ClassType)s, t);
1283 }
1285 if (s.tag == CLASS || s.tag == ARRAY) {
1286 boolean upcast;
1287 if ((upcast = isSubtype(erasure(t), erasure(s)))
1288 || isSubtype(erasure(s), erasure(t))) {
1289 if (!upcast && s.tag == ARRAY) {
1290 if (!isReifiable(s))
1291 warnStack.head.warn(LintCategory.UNCHECKED);
1292 return true;
1293 } else if (s.isRaw()) {
1294 return true;
1295 } else if (t.isRaw()) {
1296 if (!isUnbounded(s))
1297 warnStack.head.warn(LintCategory.UNCHECKED);
1298 return true;
1299 }
1300 // Assume |a| <: |b|
1301 final Type a = upcast ? t : s;
1302 final Type b = upcast ? s : t;
1303 final boolean HIGH = true;
1304 final boolean LOW = false;
1305 final boolean DONT_REWRITE_TYPEVARS = false;
1306 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1307 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1308 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1309 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1310 Type lowSub = asSub(bLow, aLow.tsym);
1311 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1312 if (highSub == null) {
1313 final boolean REWRITE_TYPEVARS = true;
1314 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1315 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1316 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1317 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1318 lowSub = asSub(bLow, aLow.tsym);
1319 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1320 }
1321 if (highSub != null) {
1322 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1323 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1324 }
1325 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1326 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1327 && !disjointTypes(aLow.allparams(), highSub.allparams())
1328 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1329 if (upcast ? giveWarning(a, b) :
1330 giveWarning(b, a))
1331 warnStack.head.warn(LintCategory.UNCHECKED);
1332 return true;
1333 }
1334 }
1335 if (isReifiable(s))
1336 return isSubtypeUnchecked(a, b);
1337 else
1338 return isSubtypeUnchecked(a, b, warnStack.head);
1339 }
1341 // Sidecast
1342 if (s.tag == CLASS) {
1343 if ((s.tsym.flags() & INTERFACE) != 0) {
1344 return ((t.tsym.flags() & FINAL) == 0)
1345 ? sideCast(t, s, warnStack.head)
1346 : sideCastFinal(t, s, warnStack.head);
1347 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1348 return ((s.tsym.flags() & FINAL) == 0)
1349 ? sideCast(t, s, warnStack.head)
1350 : sideCastFinal(t, s, warnStack.head);
1351 } else {
1352 // unrelated class types
1353 return false;
1354 }
1355 }
1356 }
1357 return false;
1358 }
1360 @Override
1361 public Boolean visitArrayType(ArrayType t, Type s) {
1362 switch (s.tag) {
1363 case ERROR:
1364 case BOT:
1365 return true;
1366 case TYPEVAR:
1367 if (isCastable(s, t, Warner.noWarnings)) {
1368 warnStack.head.warn(LintCategory.UNCHECKED);
1369 return true;
1370 } else {
1371 return false;
1372 }
1373 case CLASS:
1374 return isSubtype(t, s);
1375 case ARRAY:
1376 if (elemtype(t).tag <= lastBaseTag ||
1377 elemtype(s).tag <= lastBaseTag) {
1378 return elemtype(t).tag == elemtype(s).tag;
1379 } else {
1380 return visit(elemtype(t), elemtype(s));
1381 }
1382 default:
1383 return false;
1384 }
1385 }
1387 @Override
1388 public Boolean visitTypeVar(TypeVar t, Type s) {
1389 switch (s.tag) {
1390 case ERROR:
1391 case BOT:
1392 return true;
1393 case TYPEVAR:
1394 if (isSubtype(t, s)) {
1395 return true;
1396 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1397 warnStack.head.warn(LintCategory.UNCHECKED);
1398 return true;
1399 } else {
1400 return false;
1401 }
1402 default:
1403 return isCastable(t.bound, s, warnStack.head);
1404 }
1405 }
1407 @Override
1408 public Boolean visitErrorType(ErrorType t, Type s) {
1409 return true;
1410 }
1411 };
1412 // </editor-fold>
1414 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1415 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1416 while (ts.tail != null && ss.tail != null) {
1417 if (disjointType(ts.head, ss.head)) return true;
1418 ts = ts.tail;
1419 ss = ss.tail;
1420 }
1421 return false;
1422 }
1424 /**
1425 * Two types or wildcards are considered disjoint if it can be
1426 * proven that no type can be contained in both. It is
1427 * conservative in that it is allowed to say that two types are
1428 * not disjoint, even though they actually are.
1429 *
1430 * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1431 * {@code X} and {@code Y} are not disjoint.
1432 */
1433 public boolean disjointType(Type t, Type s) {
1434 return disjointType.visit(t, s);
1435 }
1436 // where
1437 private TypeRelation disjointType = new TypeRelation() {
1439 private Set<TypePair> cache = new HashSet<TypePair>();
1441 public Boolean visitType(Type t, Type s) {
1442 if (s.tag == WILDCARD)
1443 return visit(s, t);
1444 else
1445 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1446 }
1448 private boolean isCastableRecursive(Type t, Type s) {
1449 TypePair pair = new TypePair(t, s);
1450 if (cache.add(pair)) {
1451 try {
1452 return Types.this.isCastable(t, s);
1453 } finally {
1454 cache.remove(pair);
1455 }
1456 } else {
1457 return true;
1458 }
1459 }
1461 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1462 TypePair pair = new TypePair(t, s);
1463 if (cache.add(pair)) {
1464 try {
1465 return Types.this.notSoftSubtype(t, s);
1466 } finally {
1467 cache.remove(pair);
1468 }
1469 } else {
1470 return false;
1471 }
1472 }
1474 @Override
1475 public Boolean visitWildcardType(WildcardType t, Type s) {
1476 if (t.isUnbound())
1477 return false;
1479 if (s.tag != WILDCARD) {
1480 if (t.isExtendsBound())
1481 return notSoftSubtypeRecursive(s, t.type);
1482 else // isSuperBound()
1483 return notSoftSubtypeRecursive(t.type, s);
1484 }
1486 if (s.isUnbound())
1487 return false;
1489 if (t.isExtendsBound()) {
1490 if (s.isExtendsBound())
1491 return !isCastableRecursive(t.type, upperBound(s));
1492 else if (s.isSuperBound())
1493 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1494 } else if (t.isSuperBound()) {
1495 if (s.isExtendsBound())
1496 return notSoftSubtypeRecursive(t.type, upperBound(s));
1497 }
1498 return false;
1499 }
1500 };
1501 // </editor-fold>
1503 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1504 /**
1505 * Returns the lower bounds of the formals of a method.
1506 */
1507 public List<Type> lowerBoundArgtypes(Type t) {
1508 return lowerBounds(t.getParameterTypes());
1509 }
1510 public List<Type> lowerBounds(List<Type> ts) {
1511 return map(ts, lowerBoundMapping);
1512 }
1513 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1514 public Type apply(Type t) {
1515 return lowerBound(t);
1516 }
1517 };
1518 // </editor-fold>
1520 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1521 /**
1522 * This relation answers the question: is impossible that
1523 * something of type `t' can be a subtype of `s'? This is
1524 * different from the question "is `t' not a subtype of `s'?"
1525 * when type variables are involved: Integer is not a subtype of T
1526 * where {@code <T extends Number>} but it is not true that Integer cannot
1527 * possibly be a subtype of T.
1528 */
1529 public boolean notSoftSubtype(Type t, Type s) {
1530 if (t == s) return false;
1531 if (t.tag == TYPEVAR) {
1532 TypeVar tv = (TypeVar) t;
1533 return !isCastable(tv.bound,
1534 relaxBound(s),
1535 Warner.noWarnings);
1536 }
1537 if (s.tag != WILDCARD)
1538 s = upperBound(s);
1540 return !isSubtype(t, relaxBound(s));
1541 }
1543 private Type relaxBound(Type t) {
1544 if (t.tag == TYPEVAR) {
1545 while (t.tag == TYPEVAR)
1546 t = t.getUpperBound();
1547 t = rewriteQuantifiers(t, true, true);
1548 }
1549 return t;
1550 }
1551 // </editor-fold>
1553 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1554 public boolean isReifiable(Type t) {
1555 return isReifiable.visit(t);
1556 }
1557 // where
1558 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1560 public Boolean visitType(Type t, Void ignored) {
1561 return true;
1562 }
1564 @Override
1565 public Boolean visitClassType(ClassType t, Void ignored) {
1566 if (t.isCompound())
1567 return false;
1568 else {
1569 if (!t.isParameterized())
1570 return true;
1572 for (Type param : t.allparams()) {
1573 if (!param.isUnbound())
1574 return false;
1575 }
1576 return true;
1577 }
1578 }
1580 @Override
1581 public Boolean visitArrayType(ArrayType t, Void ignored) {
1582 return visit(t.elemtype);
1583 }
1585 @Override
1586 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1587 return false;
1588 }
1589 };
1590 // </editor-fold>
1592 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1593 public boolean isArray(Type t) {
1594 while (t.tag == WILDCARD)
1595 t = upperBound(t);
1596 return t.tag == ARRAY;
1597 }
1599 /**
1600 * The element type of an array.
1601 */
1602 public Type elemtype(Type t) {
1603 switch (t.tag) {
1604 case WILDCARD:
1605 return elemtype(upperBound(t));
1606 case ARRAY:
1607 return ((ArrayType)t).elemtype;
1608 case FORALL:
1609 return elemtype(((ForAll)t).qtype);
1610 case ERROR:
1611 return t;
1612 default:
1613 return null;
1614 }
1615 }
1617 public Type elemtypeOrType(Type t) {
1618 Type elemtype = elemtype(t);
1619 return elemtype != null ?
1620 elemtype :
1621 t;
1622 }
1624 /**
1625 * Mapping to take element type of an arraytype
1626 */
1627 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1628 public Type apply(Type t) { return elemtype(t); }
1629 };
1631 /**
1632 * The number of dimensions of an array type.
1633 */
1634 public int dimensions(Type t) {
1635 int result = 0;
1636 while (t.tag == ARRAY) {
1637 result++;
1638 t = elemtype(t);
1639 }
1640 return result;
1641 }
1643 /**
1644 * Returns an ArrayType with the component type t
1645 *
1646 * @param t The component type of the ArrayType
1647 * @return the ArrayType for the given component
1648 */
1649 public ArrayType makeArrayType(Type t) {
1650 if (t.tag == VOID ||
1651 t.tag >= PACKAGE) {
1652 Assert.error("Type t must not be a a VOID or PACKAGE type, " + t.toString());
1653 }
1654 return new ArrayType(t, syms.arrayClass);
1655 }
1656 // </editor-fold>
1658 // <editor-fold defaultstate="collapsed" desc="asSuper">
1659 /**
1660 * Return the (most specific) base type of t that starts with the
1661 * given symbol. If none exists, return null.
1662 *
1663 * @param t a type
1664 * @param sym a symbol
1665 */
1666 public Type asSuper(Type t, Symbol sym) {
1667 return asSuper.visit(t, sym);
1668 }
1669 // where
1670 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1672 public Type visitType(Type t, Symbol sym) {
1673 return null;
1674 }
1676 @Override
1677 public Type visitClassType(ClassType t, Symbol sym) {
1678 if (t.tsym == sym)
1679 return t;
1681 Type st = supertype(t);
1682 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1683 Type x = asSuper(st, sym);
1684 if (x != null)
1685 return x;
1686 }
1687 if ((sym.flags() & INTERFACE) != 0) {
1688 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1689 Type x = asSuper(l.head, sym);
1690 if (x != null)
1691 return x;
1692 }
1693 }
1694 return null;
1695 }
1697 @Override
1698 public Type visitArrayType(ArrayType t, Symbol sym) {
1699 return isSubtype(t, sym.type) ? sym.type : null;
1700 }
1702 @Override
1703 public Type visitTypeVar(TypeVar t, Symbol sym) {
1704 if (t.tsym == sym)
1705 return t;
1706 else
1707 return asSuper(t.bound, sym);
1708 }
1710 @Override
1711 public Type visitErrorType(ErrorType t, Symbol sym) {
1712 return t;
1713 }
1714 };
1716 /**
1717 * Return the base type of t or any of its outer types that starts
1718 * with the given symbol. If none exists, return null.
1719 *
1720 * @param t a type
1721 * @param sym a symbol
1722 */
1723 public Type asOuterSuper(Type t, Symbol sym) {
1724 switch (t.tag) {
1725 case CLASS:
1726 do {
1727 Type s = asSuper(t, sym);
1728 if (s != null) return s;
1729 t = t.getEnclosingType();
1730 } while (t.tag == CLASS);
1731 return null;
1732 case ARRAY:
1733 return isSubtype(t, sym.type) ? sym.type : null;
1734 case TYPEVAR:
1735 return asSuper(t, sym);
1736 case ERROR:
1737 return t;
1738 default:
1739 return null;
1740 }
1741 }
1743 /**
1744 * Return the base type of t or any of its enclosing types that
1745 * starts with the given symbol. If none exists, return null.
1746 *
1747 * @param t a type
1748 * @param sym a symbol
1749 */
1750 public Type asEnclosingSuper(Type t, Symbol sym) {
1751 switch (t.tag) {
1752 case CLASS:
1753 do {
1754 Type s = asSuper(t, sym);
1755 if (s != null) return s;
1756 Type outer = t.getEnclosingType();
1757 t = (outer.tag == CLASS) ? outer :
1758 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1759 Type.noType;
1760 } while (t.tag == CLASS);
1761 return null;
1762 case ARRAY:
1763 return isSubtype(t, sym.type) ? sym.type : null;
1764 case TYPEVAR:
1765 return asSuper(t, sym);
1766 case ERROR:
1767 return t;
1768 default:
1769 return null;
1770 }
1771 }
1772 // </editor-fold>
1774 // <editor-fold defaultstate="collapsed" desc="memberType">
1775 /**
1776 * The type of given symbol, seen as a member of t.
1777 *
1778 * @param t a type
1779 * @param sym a symbol
1780 */
1781 public Type memberType(Type t, Symbol sym) {
1782 return (sym.flags() & STATIC) != 0
1783 ? sym.type
1784 : memberType.visit(t, sym);
1785 }
1786 // where
1787 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1789 public Type visitType(Type t, Symbol sym) {
1790 return sym.type;
1791 }
1793 @Override
1794 public Type visitWildcardType(WildcardType t, Symbol sym) {
1795 return memberType(upperBound(t), sym);
1796 }
1798 @Override
1799 public Type visitClassType(ClassType t, Symbol sym) {
1800 Symbol owner = sym.owner;
1801 long flags = sym.flags();
1802 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1803 Type base = asOuterSuper(t, owner);
1804 //if t is an intersection type T = CT & I1 & I2 ... & In
1805 //its supertypes CT, I1, ... In might contain wildcards
1806 //so we need to go through capture conversion
1807 base = t.isCompound() ? capture(base) : base;
1808 if (base != null) {
1809 List<Type> ownerParams = owner.type.allparams();
1810 List<Type> baseParams = base.allparams();
1811 if (ownerParams.nonEmpty()) {
1812 if (baseParams.isEmpty()) {
1813 // then base is a raw type
1814 return erasure(sym.type);
1815 } else {
1816 return subst(sym.type, ownerParams, baseParams);
1817 }
1818 }
1819 }
1820 }
1821 return sym.type;
1822 }
1824 @Override
1825 public Type visitTypeVar(TypeVar t, Symbol sym) {
1826 return memberType(t.bound, sym);
1827 }
1829 @Override
1830 public Type visitErrorType(ErrorType t, Symbol sym) {
1831 return t;
1832 }
1833 };
1834 // </editor-fold>
1836 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1837 public boolean isAssignable(Type t, Type s) {
1838 return isAssignable(t, s, Warner.noWarnings);
1839 }
1841 /**
1842 * Is t assignable to s?<br>
1843 * Equivalent to subtype except for constant values and raw
1844 * types.<br>
1845 * (not defined for Method and ForAll types)
1846 */
1847 public boolean isAssignable(Type t, Type s, Warner warn) {
1848 if (t.tag == ERROR)
1849 return true;
1850 if (t.tag <= INT && t.constValue() != null) {
1851 int value = ((Number)t.constValue()).intValue();
1852 switch (s.tag) {
1853 case BYTE:
1854 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1855 return true;
1856 break;
1857 case CHAR:
1858 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1859 return true;
1860 break;
1861 case SHORT:
1862 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1863 return true;
1864 break;
1865 case INT:
1866 return true;
1867 case CLASS:
1868 switch (unboxedType(s).tag) {
1869 case BYTE:
1870 case CHAR:
1871 case SHORT:
1872 return isAssignable(t, unboxedType(s), warn);
1873 }
1874 break;
1875 }
1876 }
1877 return isConvertible(t, s, warn);
1878 }
1879 // </editor-fold>
1881 // <editor-fold defaultstate="collapsed" desc="erasure">
1882 /**
1883 * The erasure of t {@code |t|} -- the type that results when all
1884 * type parameters in t are deleted.
1885 */
1886 public Type erasure(Type t) {
1887 return eraseNotNeeded(t)? t : erasure(t, false);
1888 }
1889 //where
1890 private boolean eraseNotNeeded(Type t) {
1891 // We don't want to erase primitive types and String type as that
1892 // operation is idempotent. Also, erasing these could result in loss
1893 // of information such as constant values attached to such types.
1894 return (t.tag <= lastBaseTag) || (syms.stringType.tsym == t.tsym);
1895 }
1897 private Type erasure(Type t, boolean recurse) {
1898 if (t.tag <= lastBaseTag)
1899 return t; /* fast special case */
1900 else
1901 return erasure.visit(t, recurse);
1902 }
1903 // where
1904 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1905 public Type visitType(Type t, Boolean recurse) {
1906 if (t.tag <= lastBaseTag)
1907 return t; /*fast special case*/
1908 else
1909 return t.map(recurse ? erasureRecFun : erasureFun);
1910 }
1912 @Override
1913 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1914 return erasure(upperBound(t), recurse);
1915 }
1917 @Override
1918 public Type visitClassType(ClassType t, Boolean recurse) {
1919 Type erased = t.tsym.erasure(Types.this);
1920 if (recurse) {
1921 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1922 }
1923 return erased;
1924 }
1926 @Override
1927 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1928 return erasure(t.bound, recurse);
1929 }
1931 @Override
1932 public Type visitErrorType(ErrorType t, Boolean recurse) {
1933 return t;
1934 }
1935 };
1937 private Mapping erasureFun = new Mapping ("erasure") {
1938 public Type apply(Type t) { return erasure(t); }
1939 };
1941 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1942 public Type apply(Type t) { return erasureRecursive(t); }
1943 };
1945 public List<Type> erasure(List<Type> ts) {
1946 return Type.map(ts, erasureFun);
1947 }
1949 public Type erasureRecursive(Type t) {
1950 return erasure(t, true);
1951 }
1953 public List<Type> erasureRecursive(List<Type> ts) {
1954 return Type.map(ts, erasureRecFun);
1955 }
1956 // </editor-fold>
1958 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1959 /**
1960 * Make a compound type from non-empty list of types
1961 *
1962 * @param bounds the types from which the compound type is formed
1963 * @param supertype is objectType if all bounds are interfaces,
1964 * null otherwise.
1965 */
1966 public Type makeCompoundType(List<Type> bounds,
1967 Type supertype) {
1968 ClassSymbol bc =
1969 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1970 Type.moreInfo
1971 ? names.fromString(bounds.toString())
1972 : names.empty,
1973 syms.noSymbol);
1974 if (bounds.head.tag == TYPEVAR)
1975 // error condition, recover
1976 bc.erasure_field = syms.objectType;
1977 else
1978 bc.erasure_field = erasure(bounds.head);
1979 bc.members_field = new Scope(bc);
1980 ClassType bt = (ClassType)bc.type;
1981 bt.allparams_field = List.nil();
1982 if (supertype != null) {
1983 bt.supertype_field = supertype;
1984 bt.interfaces_field = bounds;
1985 } else {
1986 bt.supertype_field = bounds.head;
1987 bt.interfaces_field = bounds.tail;
1988 }
1989 Assert.check(bt.supertype_field.tsym.completer != null
1990 || !bt.supertype_field.isInterface(),
1991 bt.supertype_field);
1992 return bt;
1993 }
1995 /**
1996 * Same as {@link #makeCompoundType(List,Type)}, except that the
1997 * second parameter is computed directly. Note that this might
1998 * cause a symbol completion. Hence, this version of
1999 * makeCompoundType may not be called during a classfile read.
2000 */
2001 public Type makeCompoundType(List<Type> bounds) {
2002 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
2003 supertype(bounds.head) : null;
2004 return makeCompoundType(bounds, supertype);
2005 }
2007 /**
2008 * A convenience wrapper for {@link #makeCompoundType(List)}; the
2009 * arguments are converted to a list and passed to the other
2010 * method. Note that this might cause a symbol completion.
2011 * Hence, this version of makeCompoundType may not be called
2012 * during a classfile read.
2013 */
2014 public Type makeCompoundType(Type bound1, Type bound2) {
2015 return makeCompoundType(List.of(bound1, bound2));
2016 }
2017 // </editor-fold>
2019 // <editor-fold defaultstate="collapsed" desc="supertype">
2020 public Type supertype(Type t) {
2021 return supertype.visit(t);
2022 }
2023 // where
2024 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2026 public Type visitType(Type t, Void ignored) {
2027 // A note on wildcards: there is no good way to
2028 // determine a supertype for a super bounded wildcard.
2029 return null;
2030 }
2032 @Override
2033 public Type visitClassType(ClassType t, Void ignored) {
2034 if (t.supertype_field == null) {
2035 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2036 // An interface has no superclass; its supertype is Object.
2037 if (t.isInterface())
2038 supertype = ((ClassType)t.tsym.type).supertype_field;
2039 if (t.supertype_field == null) {
2040 List<Type> actuals = classBound(t).allparams();
2041 List<Type> formals = t.tsym.type.allparams();
2042 if (t.hasErasedSupertypes()) {
2043 t.supertype_field = erasureRecursive(supertype);
2044 } else if (formals.nonEmpty()) {
2045 t.supertype_field = subst(supertype, formals, actuals);
2046 }
2047 else {
2048 t.supertype_field = supertype;
2049 }
2050 }
2051 }
2052 return t.supertype_field;
2053 }
2055 /**
2056 * The supertype is always a class type. If the type
2057 * variable's bounds start with a class type, this is also
2058 * the supertype. Otherwise, the supertype is
2059 * java.lang.Object.
2060 */
2061 @Override
2062 public Type visitTypeVar(TypeVar t, Void ignored) {
2063 if (t.bound.tag == TYPEVAR ||
2064 (!t.bound.isCompound() && !t.bound.isInterface())) {
2065 return t.bound;
2066 } else {
2067 return supertype(t.bound);
2068 }
2069 }
2071 @Override
2072 public Type visitArrayType(ArrayType t, Void ignored) {
2073 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2074 return arraySuperType();
2075 else
2076 return new ArrayType(supertype(t.elemtype), t.tsym);
2077 }
2079 @Override
2080 public Type visitErrorType(ErrorType t, Void ignored) {
2081 return t;
2082 }
2083 };
2084 // </editor-fold>
2086 // <editor-fold defaultstate="collapsed" desc="interfaces">
2087 /**
2088 * Return the interfaces implemented by this class.
2089 */
2090 public List<Type> interfaces(Type t) {
2091 return interfaces.visit(t);
2092 }
2093 // where
2094 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2096 public List<Type> visitType(Type t, Void ignored) {
2097 return List.nil();
2098 }
2100 @Override
2101 public List<Type> visitClassType(ClassType t, Void ignored) {
2102 if (t.interfaces_field == null) {
2103 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2104 if (t.interfaces_field == null) {
2105 // If t.interfaces_field is null, then t must
2106 // be a parameterized type (not to be confused
2107 // with a generic type declaration).
2108 // Terminology:
2109 // Parameterized type: List<String>
2110 // Generic type declaration: class List<E> { ... }
2111 // So t corresponds to List<String> and
2112 // t.tsym.type corresponds to List<E>.
2113 // The reason t must be parameterized type is
2114 // that completion will happen as a side
2115 // effect of calling
2116 // ClassSymbol.getInterfaces. Since
2117 // t.interfaces_field is null after
2118 // completion, we can assume that t is not the
2119 // type of a class/interface declaration.
2120 Assert.check(t != t.tsym.type, t);
2121 List<Type> actuals = t.allparams();
2122 List<Type> formals = t.tsym.type.allparams();
2123 if (t.hasErasedSupertypes()) {
2124 t.interfaces_field = erasureRecursive(interfaces);
2125 } else if (formals.nonEmpty()) {
2126 t.interfaces_field =
2127 upperBounds(subst(interfaces, formals, actuals));
2128 }
2129 else {
2130 t.interfaces_field = interfaces;
2131 }
2132 }
2133 }
2134 return t.interfaces_field;
2135 }
2137 @Override
2138 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2139 if (t.bound.isCompound())
2140 return interfaces(t.bound);
2142 if (t.bound.isInterface())
2143 return List.of(t.bound);
2145 return List.nil();
2146 }
2147 };
2148 // </editor-fold>
2150 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2151 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
2153 public boolean isDerivedRaw(Type t) {
2154 Boolean result = isDerivedRawCache.get(t);
2155 if (result == null) {
2156 result = isDerivedRawInternal(t);
2157 isDerivedRawCache.put(t, result);
2158 }
2159 return result;
2160 }
2162 public boolean isDerivedRawInternal(Type t) {
2163 if (t.isErroneous())
2164 return false;
2165 return
2166 t.isRaw() ||
2167 supertype(t) != null && isDerivedRaw(supertype(t)) ||
2168 isDerivedRaw(interfaces(t));
2169 }
2171 public boolean isDerivedRaw(List<Type> ts) {
2172 List<Type> l = ts;
2173 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2174 return l.nonEmpty();
2175 }
2176 // </editor-fold>
2178 // <editor-fold defaultstate="collapsed" desc="setBounds">
2179 /**
2180 * Set the bounds field of the given type variable to reflect a
2181 * (possibly multiple) list of bounds.
2182 * @param t a type variable
2183 * @param bounds the bounds, must be nonempty
2184 * @param supertype is objectType if all bounds are interfaces,
2185 * null otherwise.
2186 */
2187 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
2188 if (bounds.tail.isEmpty())
2189 t.bound = bounds.head;
2190 else
2191 t.bound = makeCompoundType(bounds, supertype);
2192 t.rank_field = -1;
2193 }
2195 /**
2196 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
2197 * third parameter is computed directly, as follows: if all
2198 * all bounds are interface types, the computed supertype is Object,
2199 * otherwise the supertype is simply left null (in this case, the supertype
2200 * is assumed to be the head of the bound list passed as second argument).
2201 * Note that this check might cause a symbol completion. Hence, this version of
2202 * setBounds may not be called during a classfile read.
2203 */
2204 public void setBounds(TypeVar t, List<Type> bounds) {
2205 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
2206 syms.objectType : null;
2207 setBounds(t, bounds, supertype);
2208 t.rank_field = -1;
2209 }
2210 // </editor-fold>
2212 // <editor-fold defaultstate="collapsed" desc="getBounds">
2213 /**
2214 * Return list of bounds of the given type variable.
2215 */
2216 public List<Type> getBounds(TypeVar t) {
2217 if (t.bound.isErroneous() || !t.bound.isCompound())
2218 return List.of(t.bound);
2219 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2220 return interfaces(t).prepend(supertype(t));
2221 else
2222 // No superclass was given in bounds.
2223 // In this case, supertype is Object, erasure is first interface.
2224 return interfaces(t);
2225 }
2226 // </editor-fold>
2228 // <editor-fold defaultstate="collapsed" desc="classBound">
2229 /**
2230 * If the given type is a (possibly selected) type variable,
2231 * return the bounding class of this type, otherwise return the
2232 * type itself.
2233 */
2234 public Type classBound(Type t) {
2235 return classBound.visit(t);
2236 }
2237 // where
2238 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2240 public Type visitType(Type t, Void ignored) {
2241 return t;
2242 }
2244 @Override
2245 public Type visitClassType(ClassType t, Void ignored) {
2246 Type outer1 = classBound(t.getEnclosingType());
2247 if (outer1 != t.getEnclosingType())
2248 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
2249 else
2250 return t;
2251 }
2253 @Override
2254 public Type visitTypeVar(TypeVar t, Void ignored) {
2255 return classBound(supertype(t));
2256 }
2258 @Override
2259 public Type visitErrorType(ErrorType t, Void ignored) {
2260 return t;
2261 }
2262 };
2263 // </editor-fold>
2265 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
2266 /**
2267 * Returns true iff the first signature is a <em>sub
2268 * signature</em> of the other. This is <b>not</b> an equivalence
2269 * relation.
2270 *
2271 * @jls section 8.4.2.
2272 * @see #overrideEquivalent(Type t, Type s)
2273 * @param t first signature (possibly raw).
2274 * @param s second signature (could be subjected to erasure).
2275 * @return true if t is a sub signature of s.
2276 */
2277 public boolean isSubSignature(Type t, Type s) {
2278 return isSubSignature(t, s, true);
2279 }
2281 public boolean isSubSignature(Type t, Type s, boolean strict) {
2282 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2283 }
2285 /**
2286 * Returns true iff these signatures are related by <em>override
2287 * equivalence</em>. This is the natural extension of
2288 * isSubSignature to an equivalence relation.
2289 *
2290 * @jls section 8.4.2.
2291 * @see #isSubSignature(Type t, Type s)
2292 * @param t a signature (possible raw, could be subjected to
2293 * erasure).
2294 * @param s a signature (possible raw, could be subjected to
2295 * erasure).
2296 * @return true if either argument is a sub signature of the other.
2297 */
2298 public boolean overrideEquivalent(Type t, Type s) {
2299 return hasSameArgs(t, s) ||
2300 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2301 }
2303 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2304 for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
2305 if (msym.overrides(e.sym, origin, Types.this, true)) {
2306 return true;
2307 }
2308 }
2309 return false;
2310 }
2312 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2313 class ImplementationCache {
2315 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2316 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2318 class Entry {
2319 final MethodSymbol cachedImpl;
2320 final Filter<Symbol> implFilter;
2321 final boolean checkResult;
2322 final int prevMark;
2324 public Entry(MethodSymbol cachedImpl,
2325 Filter<Symbol> scopeFilter,
2326 boolean checkResult,
2327 int prevMark) {
2328 this.cachedImpl = cachedImpl;
2329 this.implFilter = scopeFilter;
2330 this.checkResult = checkResult;
2331 this.prevMark = prevMark;
2332 }
2334 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2335 return this.implFilter == scopeFilter &&
2336 this.checkResult == checkResult &&
2337 this.prevMark == mark;
2338 }
2339 }
2341 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2342 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2343 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2344 if (cache == null) {
2345 cache = new HashMap<TypeSymbol, Entry>();
2346 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2347 }
2348 Entry e = cache.get(origin);
2349 CompoundScope members = membersClosure(origin.type, true);
2350 if (e == null ||
2351 !e.matches(implFilter, checkResult, members.getMark())) {
2352 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2353 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2354 return impl;
2355 }
2356 else {
2357 return e.cachedImpl;
2358 }
2359 }
2361 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2362 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2363 while (t.tag == TYPEVAR)
2364 t = t.getUpperBound();
2365 TypeSymbol c = t.tsym;
2366 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2367 e.scope != null;
2368 e = e.next(implFilter)) {
2369 if (e.sym != null &&
2370 e.sym.overrides(ms, origin, Types.this, checkResult))
2371 return (MethodSymbol)e.sym;
2372 }
2373 }
2374 return null;
2375 }
2376 }
2378 private ImplementationCache implCache = new ImplementationCache();
2380 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2381 return implCache.get(ms, origin, checkResult, implFilter);
2382 }
2383 // </editor-fold>
2385 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2386 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2388 private WeakHashMap<TypeSymbol, Entry> _map =
2389 new WeakHashMap<TypeSymbol, Entry>();
2391 class Entry {
2392 final boolean skipInterfaces;
2393 final CompoundScope compoundScope;
2395 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2396 this.skipInterfaces = skipInterfaces;
2397 this.compoundScope = compoundScope;
2398 }
2400 boolean matches(boolean skipInterfaces) {
2401 return this.skipInterfaces == skipInterfaces;
2402 }
2403 }
2405 List<TypeSymbol> seenTypes = List.nil();
2407 /** members closure visitor methods **/
2409 public CompoundScope visitType(Type t, Boolean skipInterface) {
2410 return null;
2411 }
2413 @Override
2414 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2415 if (seenTypes.contains(t.tsym)) {
2416 //this is possible when an interface is implemented in multiple
2417 //superclasses, or when a classs hierarchy is circular - in such
2418 //cases we don't need to recurse (empty scope is returned)
2419 return new CompoundScope(t.tsym);
2420 }
2421 try {
2422 seenTypes = seenTypes.prepend(t.tsym);
2423 ClassSymbol csym = (ClassSymbol)t.tsym;
2424 Entry e = _map.get(csym);
2425 if (e == null || !e.matches(skipInterface)) {
2426 CompoundScope membersClosure = new CompoundScope(csym);
2427 if (!skipInterface) {
2428 for (Type i : interfaces(t)) {
2429 membersClosure.addSubScope(visit(i, skipInterface));
2430 }
2431 }
2432 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2433 membersClosure.addSubScope(csym.members());
2434 e = new Entry(skipInterface, membersClosure);
2435 _map.put(csym, e);
2436 }
2437 return e.compoundScope;
2438 }
2439 finally {
2440 seenTypes = seenTypes.tail;
2441 }
2442 }
2444 @Override
2445 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2446 return visit(t.getUpperBound(), skipInterface);
2447 }
2448 }
2450 private MembersClosureCache membersCache = new MembersClosureCache();
2452 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2453 return membersCache.visit(site, skipInterface);
2454 }
2455 // </editor-fold>
2457 /**
2458 * Does t have the same arguments as s? It is assumed that both
2459 * types are (possibly polymorphic) method types. Monomorphic
2460 * method types "have the same arguments", if their argument lists
2461 * are equal. Polymorphic method types "have the same arguments",
2462 * if they have the same arguments after renaming all type
2463 * variables of one to corresponding type variables in the other,
2464 * where correspondence is by position in the type parameter list.
2465 */
2466 public boolean hasSameArgs(Type t, Type s) {
2467 return hasSameArgs(t, s, true);
2468 }
2470 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2471 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2472 }
2474 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2475 return hasSameArgs.visit(t, s);
2476 }
2477 // where
2478 private class HasSameArgs extends TypeRelation {
2480 boolean strict;
2482 public HasSameArgs(boolean strict) {
2483 this.strict = strict;
2484 }
2486 public Boolean visitType(Type t, Type s) {
2487 throw new AssertionError();
2488 }
2490 @Override
2491 public Boolean visitMethodType(MethodType t, Type s) {
2492 return s.tag == METHOD
2493 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2494 }
2496 @Override
2497 public Boolean visitForAll(ForAll t, Type s) {
2498 if (s.tag != FORALL)
2499 return strict ? false : visitMethodType(t.asMethodType(), s);
2501 ForAll forAll = (ForAll)s;
2502 return hasSameBounds(t, forAll)
2503 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2504 }
2506 @Override
2507 public Boolean visitErrorType(ErrorType t, Type s) {
2508 return false;
2509 }
2510 };
2512 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2513 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2515 // </editor-fold>
2517 // <editor-fold defaultstate="collapsed" desc="subst">
2518 public List<Type> subst(List<Type> ts,
2519 List<Type> from,
2520 List<Type> to) {
2521 return new Subst(from, to).subst(ts);
2522 }
2524 /**
2525 * Substitute all occurrences of a type in `from' with the
2526 * corresponding type in `to' in 't'. Match lists `from' and `to'
2527 * from the right: If lists have different length, discard leading
2528 * elements of the longer list.
2529 */
2530 public Type subst(Type t, List<Type> from, List<Type> to) {
2531 return new Subst(from, to).subst(t);
2532 }
2534 private class Subst extends UnaryVisitor<Type> {
2535 List<Type> from;
2536 List<Type> to;
2538 public Subst(List<Type> from, List<Type> to) {
2539 int fromLength = from.length();
2540 int toLength = to.length();
2541 while (fromLength > toLength) {
2542 fromLength--;
2543 from = from.tail;
2544 }
2545 while (fromLength < toLength) {
2546 toLength--;
2547 to = to.tail;
2548 }
2549 this.from = from;
2550 this.to = to;
2551 }
2553 Type subst(Type t) {
2554 if (from.tail == null)
2555 return t;
2556 else
2557 return visit(t);
2558 }
2560 List<Type> subst(List<Type> ts) {
2561 if (from.tail == null)
2562 return ts;
2563 boolean wild = false;
2564 if (ts.nonEmpty() && from.nonEmpty()) {
2565 Type head1 = subst(ts.head);
2566 List<Type> tail1 = subst(ts.tail);
2567 if (head1 != ts.head || tail1 != ts.tail)
2568 return tail1.prepend(head1);
2569 }
2570 return ts;
2571 }
2573 public Type visitType(Type t, Void ignored) {
2574 return t;
2575 }
2577 @Override
2578 public Type visitMethodType(MethodType t, Void ignored) {
2579 List<Type> argtypes = subst(t.argtypes);
2580 Type restype = subst(t.restype);
2581 List<Type> thrown = subst(t.thrown);
2582 if (argtypes == t.argtypes &&
2583 restype == t.restype &&
2584 thrown == t.thrown)
2585 return t;
2586 else
2587 return new MethodType(argtypes, restype, thrown, t.tsym);
2588 }
2590 @Override
2591 public Type visitTypeVar(TypeVar t, Void ignored) {
2592 for (List<Type> from = this.from, to = this.to;
2593 from.nonEmpty();
2594 from = from.tail, to = to.tail) {
2595 if (t == from.head) {
2596 return to.head.withTypeVar(t);
2597 }
2598 }
2599 return t;
2600 }
2602 @Override
2603 public Type visitClassType(ClassType t, Void ignored) {
2604 if (!t.isCompound()) {
2605 List<Type> typarams = t.getTypeArguments();
2606 List<Type> typarams1 = subst(typarams);
2607 Type outer = t.getEnclosingType();
2608 Type outer1 = subst(outer);
2609 if (typarams1 == typarams && outer1 == outer)
2610 return t;
2611 else
2612 return new ClassType(outer1, typarams1, t.tsym);
2613 } else {
2614 Type st = subst(supertype(t));
2615 List<Type> is = upperBounds(subst(interfaces(t)));
2616 if (st == supertype(t) && is == interfaces(t))
2617 return t;
2618 else
2619 return makeCompoundType(is.prepend(st));
2620 }
2621 }
2623 @Override
2624 public Type visitWildcardType(WildcardType t, Void ignored) {
2625 Type bound = t.type;
2626 if (t.kind != BoundKind.UNBOUND)
2627 bound = subst(bound);
2628 if (bound == t.type) {
2629 return t;
2630 } else {
2631 if (t.isExtendsBound() && bound.isExtendsBound())
2632 bound = upperBound(bound);
2633 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2634 }
2635 }
2637 @Override
2638 public Type visitArrayType(ArrayType t, Void ignored) {
2639 Type elemtype = subst(t.elemtype);
2640 if (elemtype == t.elemtype)
2641 return t;
2642 else
2643 return new ArrayType(upperBound(elemtype), t.tsym);
2644 }
2646 @Override
2647 public Type visitForAll(ForAll t, Void ignored) {
2648 if (Type.containsAny(to, t.tvars)) {
2649 //perform alpha-renaming of free-variables in 't'
2650 //if 'to' types contain variables that are free in 't'
2651 List<Type> freevars = newInstances(t.tvars);
2652 t = new ForAll(freevars,
2653 Types.this.subst(t.qtype, t.tvars, freevars));
2654 }
2655 List<Type> tvars1 = substBounds(t.tvars, from, to);
2656 Type qtype1 = subst(t.qtype);
2657 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2658 return t;
2659 } else if (tvars1 == t.tvars) {
2660 return new ForAll(tvars1, qtype1);
2661 } else {
2662 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2663 }
2664 }
2666 @Override
2667 public Type visitErrorType(ErrorType t, Void ignored) {
2668 return t;
2669 }
2670 }
2672 public List<Type> substBounds(List<Type> tvars,
2673 List<Type> from,
2674 List<Type> to) {
2675 if (tvars.isEmpty())
2676 return tvars;
2677 ListBuffer<Type> newBoundsBuf = lb();
2678 boolean changed = false;
2679 // calculate new bounds
2680 for (Type t : tvars) {
2681 TypeVar tv = (TypeVar) t;
2682 Type bound = subst(tv.bound, from, to);
2683 if (bound != tv.bound)
2684 changed = true;
2685 newBoundsBuf.append(bound);
2686 }
2687 if (!changed)
2688 return tvars;
2689 ListBuffer<Type> newTvars = lb();
2690 // create new type variables without bounds
2691 for (Type t : tvars) {
2692 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2693 }
2694 // the new bounds should use the new type variables in place
2695 // of the old
2696 List<Type> newBounds = newBoundsBuf.toList();
2697 from = tvars;
2698 to = newTvars.toList();
2699 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2700 newBounds.head = subst(newBounds.head, from, to);
2701 }
2702 newBounds = newBoundsBuf.toList();
2703 // set the bounds of new type variables to the new bounds
2704 for (Type t : newTvars.toList()) {
2705 TypeVar tv = (TypeVar) t;
2706 tv.bound = newBounds.head;
2707 newBounds = newBounds.tail;
2708 }
2709 return newTvars.toList();
2710 }
2712 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2713 Type bound1 = subst(t.bound, from, to);
2714 if (bound1 == t.bound)
2715 return t;
2716 else {
2717 // create new type variable without bounds
2718 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2719 // the new bound should use the new type variable in place
2720 // of the old
2721 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2722 return tv;
2723 }
2724 }
2725 // </editor-fold>
2727 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2728 /**
2729 * Does t have the same bounds for quantified variables as s?
2730 */
2731 boolean hasSameBounds(ForAll t, ForAll s) {
2732 List<Type> l1 = t.tvars;
2733 List<Type> l2 = s.tvars;
2734 while (l1.nonEmpty() && l2.nonEmpty() &&
2735 isSameType(l1.head.getUpperBound(),
2736 subst(l2.head.getUpperBound(),
2737 s.tvars,
2738 t.tvars))) {
2739 l1 = l1.tail;
2740 l2 = l2.tail;
2741 }
2742 return l1.isEmpty() && l2.isEmpty();
2743 }
2744 // </editor-fold>
2746 // <editor-fold defaultstate="collapsed" desc="newInstances">
2747 /** Create new vector of type variables from list of variables
2748 * changing all recursive bounds from old to new list.
2749 */
2750 public List<Type> newInstances(List<Type> tvars) {
2751 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2752 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2753 TypeVar tv = (TypeVar) l.head;
2754 tv.bound = subst(tv.bound, tvars, tvars1);
2755 }
2756 return tvars1;
2757 }
2758 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2759 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2760 };
2761 // </editor-fold>
2763 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2764 return original.accept(methodWithParameters, newParams);
2765 }
2766 // where
2767 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2768 public Type visitType(Type t, List<Type> newParams) {
2769 throw new IllegalArgumentException("Not a method type: " + t);
2770 }
2771 public Type visitMethodType(MethodType t, List<Type> newParams) {
2772 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2773 }
2774 public Type visitForAll(ForAll t, List<Type> newParams) {
2775 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2776 }
2777 };
2779 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2780 return original.accept(methodWithThrown, newThrown);
2781 }
2782 // where
2783 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2784 public Type visitType(Type t, List<Type> newThrown) {
2785 throw new IllegalArgumentException("Not a method type: " + t);
2786 }
2787 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2788 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2789 }
2790 public Type visitForAll(ForAll t, List<Type> newThrown) {
2791 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2792 }
2793 };
2795 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2796 return original.accept(methodWithReturn, newReturn);
2797 }
2798 // where
2799 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2800 public Type visitType(Type t, Type newReturn) {
2801 throw new IllegalArgumentException("Not a method type: " + t);
2802 }
2803 public Type visitMethodType(MethodType t, Type newReturn) {
2804 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2805 }
2806 public Type visitForAll(ForAll t, Type newReturn) {
2807 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2808 }
2809 };
2811 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2812 public Type createErrorType(Type originalType) {
2813 return new ErrorType(originalType, syms.errSymbol);
2814 }
2816 public Type createErrorType(ClassSymbol c, Type originalType) {
2817 return new ErrorType(c, originalType);
2818 }
2820 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2821 return new ErrorType(name, container, originalType);
2822 }
2823 // </editor-fold>
2825 // <editor-fold defaultstate="collapsed" desc="rank">
2826 /**
2827 * The rank of a class is the length of the longest path between
2828 * the class and java.lang.Object in the class inheritance
2829 * graph. Undefined for all but reference types.
2830 */
2831 public int rank(Type t) {
2832 switch(t.tag) {
2833 case CLASS: {
2834 ClassType cls = (ClassType)t;
2835 if (cls.rank_field < 0) {
2836 Name fullname = cls.tsym.getQualifiedName();
2837 if (fullname == names.java_lang_Object)
2838 cls.rank_field = 0;
2839 else {
2840 int r = rank(supertype(cls));
2841 for (List<Type> l = interfaces(cls);
2842 l.nonEmpty();
2843 l = l.tail) {
2844 if (rank(l.head) > r)
2845 r = rank(l.head);
2846 }
2847 cls.rank_field = r + 1;
2848 }
2849 }
2850 return cls.rank_field;
2851 }
2852 case TYPEVAR: {
2853 TypeVar tvar = (TypeVar)t;
2854 if (tvar.rank_field < 0) {
2855 int r = rank(supertype(tvar));
2856 for (List<Type> l = interfaces(tvar);
2857 l.nonEmpty();
2858 l = l.tail) {
2859 if (rank(l.head) > r) r = rank(l.head);
2860 }
2861 tvar.rank_field = r + 1;
2862 }
2863 return tvar.rank_field;
2864 }
2865 case ERROR:
2866 return 0;
2867 default:
2868 throw new AssertionError();
2869 }
2870 }
2871 // </editor-fold>
2873 /**
2874 * Helper method for generating a string representation of a given type
2875 * accordingly to a given locale
2876 */
2877 public String toString(Type t, Locale locale) {
2878 return Printer.createStandardPrinter(messages).visit(t, locale);
2879 }
2881 /**
2882 * Helper method for generating a string representation of a given type
2883 * accordingly to a given locale
2884 */
2885 public String toString(Symbol t, Locale locale) {
2886 return Printer.createStandardPrinter(messages).visit(t, locale);
2887 }
2889 // <editor-fold defaultstate="collapsed" desc="toString">
2890 /**
2891 * This toString is slightly more descriptive than the one on Type.
2892 *
2893 * @deprecated Types.toString(Type t, Locale l) provides better support
2894 * for localization
2895 */
2896 @Deprecated
2897 public String toString(Type t) {
2898 if (t.tag == FORALL) {
2899 ForAll forAll = (ForAll)t;
2900 return typaramsString(forAll.tvars) + forAll.qtype;
2901 }
2902 return "" + t;
2903 }
2904 // where
2905 private String typaramsString(List<Type> tvars) {
2906 StringBuilder s = new StringBuilder();
2907 s.append('<');
2908 boolean first = true;
2909 for (Type t : tvars) {
2910 if (!first) s.append(", ");
2911 first = false;
2912 appendTyparamString(((TypeVar)t), s);
2913 }
2914 s.append('>');
2915 return s.toString();
2916 }
2917 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2918 buf.append(t);
2919 if (t.bound == null ||
2920 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2921 return;
2922 buf.append(" extends "); // Java syntax; no need for i18n
2923 Type bound = t.bound;
2924 if (!bound.isCompound()) {
2925 buf.append(bound);
2926 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2927 buf.append(supertype(t));
2928 for (Type intf : interfaces(t)) {
2929 buf.append('&');
2930 buf.append(intf);
2931 }
2932 } else {
2933 // No superclass was given in bounds.
2934 // In this case, supertype is Object, erasure is first interface.
2935 boolean first = true;
2936 for (Type intf : interfaces(t)) {
2937 if (!first) buf.append('&');
2938 first = false;
2939 buf.append(intf);
2940 }
2941 }
2942 }
2943 // </editor-fold>
2945 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2946 /**
2947 * A cache for closures.
2948 *
2949 * <p>A closure is a list of all the supertypes and interfaces of
2950 * a class or interface type, ordered by ClassSymbol.precedes
2951 * (that is, subclasses come first, arbitrary but fixed
2952 * otherwise).
2953 */
2954 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2956 /**
2957 * Returns the closure of a class or interface type.
2958 */
2959 public List<Type> closure(Type t) {
2960 List<Type> cl = closureCache.get(t);
2961 if (cl == null) {
2962 Type st = supertype(t);
2963 if (!t.isCompound()) {
2964 if (st.tag == CLASS) {
2965 cl = insert(closure(st), t);
2966 } else if (st.tag == TYPEVAR) {
2967 cl = closure(st).prepend(t);
2968 } else {
2969 cl = List.of(t);
2970 }
2971 } else {
2972 cl = closure(supertype(t));
2973 }
2974 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2975 cl = union(cl, closure(l.head));
2976 closureCache.put(t, cl);
2977 }
2978 return cl;
2979 }
2981 /**
2982 * Insert a type in a closure
2983 */
2984 public List<Type> insert(List<Type> cl, Type t) {
2985 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2986 return cl.prepend(t);
2987 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2988 return insert(cl.tail, t).prepend(cl.head);
2989 } else {
2990 return cl;
2991 }
2992 }
2994 /**
2995 * Form the union of two closures
2996 */
2997 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2998 if (cl1.isEmpty()) {
2999 return cl2;
3000 } else if (cl2.isEmpty()) {
3001 return cl1;
3002 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3003 return union(cl1.tail, cl2).prepend(cl1.head);
3004 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3005 return union(cl1, cl2.tail).prepend(cl2.head);
3006 } else {
3007 return union(cl1.tail, cl2.tail).prepend(cl1.head);
3008 }
3009 }
3011 /**
3012 * Intersect two closures
3013 */
3014 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3015 if (cl1 == cl2)
3016 return cl1;
3017 if (cl1.isEmpty() || cl2.isEmpty())
3018 return List.nil();
3019 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3020 return intersect(cl1.tail, cl2);
3021 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3022 return intersect(cl1, cl2.tail);
3023 if (isSameType(cl1.head, cl2.head))
3024 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3025 if (cl1.head.tsym == cl2.head.tsym &&
3026 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
3027 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3028 Type merge = merge(cl1.head,cl2.head);
3029 return intersect(cl1.tail, cl2.tail).prepend(merge);
3030 }
3031 if (cl1.head.isRaw() || cl2.head.isRaw())
3032 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3033 }
3034 return intersect(cl1.tail, cl2.tail);
3035 }
3036 // where
3037 class TypePair {
3038 final Type t1;
3039 final Type t2;
3040 TypePair(Type t1, Type t2) {
3041 this.t1 = t1;
3042 this.t2 = t2;
3043 }
3044 @Override
3045 public int hashCode() {
3046 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
3047 }
3048 @Override
3049 public boolean equals(Object obj) {
3050 if (!(obj instanceof TypePair))
3051 return false;
3052 TypePair typePair = (TypePair)obj;
3053 return isSameType(t1, typePair.t1)
3054 && isSameType(t2, typePair.t2);
3055 }
3056 }
3057 Set<TypePair> mergeCache = new HashSet<TypePair>();
3058 private Type merge(Type c1, Type c2) {
3059 ClassType class1 = (ClassType) c1;
3060 List<Type> act1 = class1.getTypeArguments();
3061 ClassType class2 = (ClassType) c2;
3062 List<Type> act2 = class2.getTypeArguments();
3063 ListBuffer<Type> merged = new ListBuffer<Type>();
3064 List<Type> typarams = class1.tsym.type.getTypeArguments();
3066 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3067 if (containsType(act1.head, act2.head)) {
3068 merged.append(act1.head);
3069 } else if (containsType(act2.head, act1.head)) {
3070 merged.append(act2.head);
3071 } else {
3072 TypePair pair = new TypePair(c1, c2);
3073 Type m;
3074 if (mergeCache.add(pair)) {
3075 m = new WildcardType(lub(upperBound(act1.head),
3076 upperBound(act2.head)),
3077 BoundKind.EXTENDS,
3078 syms.boundClass);
3079 mergeCache.remove(pair);
3080 } else {
3081 m = new WildcardType(syms.objectType,
3082 BoundKind.UNBOUND,
3083 syms.boundClass);
3084 }
3085 merged.append(m.withTypeVar(typarams.head));
3086 }
3087 act1 = act1.tail;
3088 act2 = act2.tail;
3089 typarams = typarams.tail;
3090 }
3091 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3092 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
3093 }
3095 /**
3096 * Return the minimum type of a closure, a compound type if no
3097 * unique minimum exists.
3098 */
3099 private Type compoundMin(List<Type> cl) {
3100 if (cl.isEmpty()) return syms.objectType;
3101 List<Type> compound = closureMin(cl);
3102 if (compound.isEmpty())
3103 return null;
3104 else if (compound.tail.isEmpty())
3105 return compound.head;
3106 else
3107 return makeCompoundType(compound);
3108 }
3110 /**
3111 * Return the minimum types of a closure, suitable for computing
3112 * compoundMin or glb.
3113 */
3114 private List<Type> closureMin(List<Type> cl) {
3115 ListBuffer<Type> classes = lb();
3116 ListBuffer<Type> interfaces = lb();
3117 while (!cl.isEmpty()) {
3118 Type current = cl.head;
3119 if (current.isInterface())
3120 interfaces.append(current);
3121 else
3122 classes.append(current);
3123 ListBuffer<Type> candidates = lb();
3124 for (Type t : cl.tail) {
3125 if (!isSubtypeNoCapture(current, t))
3126 candidates.append(t);
3127 }
3128 cl = candidates.toList();
3129 }
3130 return classes.appendList(interfaces).toList();
3131 }
3133 /**
3134 * Return the least upper bound of pair of types. if the lub does
3135 * not exist return null.
3136 */
3137 public Type lub(Type t1, Type t2) {
3138 return lub(List.of(t1, t2));
3139 }
3141 /**
3142 * Return the least upper bound (lub) of set of types. If the lub
3143 * does not exist return the type of null (bottom).
3144 */
3145 public Type lub(List<Type> ts) {
3146 final int ARRAY_BOUND = 1;
3147 final int CLASS_BOUND = 2;
3148 int boundkind = 0;
3149 for (Type t : ts) {
3150 switch (t.tag) {
3151 case CLASS:
3152 boundkind |= CLASS_BOUND;
3153 break;
3154 case ARRAY:
3155 boundkind |= ARRAY_BOUND;
3156 break;
3157 case TYPEVAR:
3158 do {
3159 t = t.getUpperBound();
3160 } while (t.tag == TYPEVAR);
3161 if (t.tag == ARRAY) {
3162 boundkind |= ARRAY_BOUND;
3163 } else {
3164 boundkind |= CLASS_BOUND;
3165 }
3166 break;
3167 default:
3168 if (t.isPrimitive())
3169 return syms.errType;
3170 }
3171 }
3172 switch (boundkind) {
3173 case 0:
3174 return syms.botType;
3176 case ARRAY_BOUND:
3177 // calculate lub(A[], B[])
3178 List<Type> elements = Type.map(ts, elemTypeFun);
3179 for (Type t : elements) {
3180 if (t.isPrimitive()) {
3181 // if a primitive type is found, then return
3182 // arraySuperType unless all the types are the
3183 // same
3184 Type first = ts.head;
3185 for (Type s : ts.tail) {
3186 if (!isSameType(first, s)) {
3187 // lub(int[], B[]) is Cloneable & Serializable
3188 return arraySuperType();
3189 }
3190 }
3191 // all the array types are the same, return one
3192 // lub(int[], int[]) is int[]
3193 return first;
3194 }
3195 }
3196 // lub(A[], B[]) is lub(A, B)[]
3197 return new ArrayType(lub(elements), syms.arrayClass);
3199 case CLASS_BOUND:
3200 // calculate lub(A, B)
3201 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
3202 ts = ts.tail;
3203 Assert.check(!ts.isEmpty());
3204 //step 1 - compute erased candidate set (EC)
3205 List<Type> cl = erasedSupertypes(ts.head);
3206 for (Type t : ts.tail) {
3207 if (t.tag == CLASS || t.tag == TYPEVAR)
3208 cl = intersect(cl, erasedSupertypes(t));
3209 }
3210 //step 2 - compute minimal erased candidate set (MEC)
3211 List<Type> mec = closureMin(cl);
3212 //step 3 - for each element G in MEC, compute lci(Inv(G))
3213 List<Type> candidates = List.nil();
3214 for (Type erasedSupertype : mec) {
3215 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
3216 for (Type t : ts) {
3217 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
3218 }
3219 candidates = candidates.appendList(lci);
3220 }
3221 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3222 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3223 return compoundMin(candidates);
3225 default:
3226 // calculate lub(A, B[])
3227 List<Type> classes = List.of(arraySuperType());
3228 for (Type t : ts) {
3229 if (t.tag != ARRAY) // Filter out any arrays
3230 classes = classes.prepend(t);
3231 }
3232 // lub(A, B[]) is lub(A, arraySuperType)
3233 return lub(classes);
3234 }
3235 }
3236 // where
3237 List<Type> erasedSupertypes(Type t) {
3238 ListBuffer<Type> buf = lb();
3239 for (Type sup : closure(t)) {
3240 if (sup.tag == TYPEVAR) {
3241 buf.append(sup);
3242 } else {
3243 buf.append(erasure(sup));
3244 }
3245 }
3246 return buf.toList();
3247 }
3249 private Type arraySuperType = null;
3250 private Type arraySuperType() {
3251 // initialized lazily to avoid problems during compiler startup
3252 if (arraySuperType == null) {
3253 synchronized (this) {
3254 if (arraySuperType == null) {
3255 // JLS 10.8: all arrays implement Cloneable and Serializable.
3256 arraySuperType = makeCompoundType(List.of(syms.serializableType,
3257 syms.cloneableType),
3258 syms.objectType);
3259 }
3260 }
3261 }
3262 return arraySuperType;
3263 }
3264 // </editor-fold>
3266 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3267 public Type glb(List<Type> ts) {
3268 Type t1 = ts.head;
3269 for (Type t2 : ts.tail) {
3270 if (t1.isErroneous())
3271 return t1;
3272 t1 = glb(t1, t2);
3273 }
3274 return t1;
3275 }
3276 //where
3277 public Type glb(Type t, Type s) {
3278 if (s == null)
3279 return t;
3280 else if (t.isPrimitive() || s.isPrimitive())
3281 return syms.errType;
3282 else if (isSubtypeNoCapture(t, s))
3283 return t;
3284 else if (isSubtypeNoCapture(s, t))
3285 return s;
3287 List<Type> closure = union(closure(t), closure(s));
3288 List<Type> bounds = closureMin(closure);
3290 if (bounds.isEmpty()) { // length == 0
3291 return syms.objectType;
3292 } else if (bounds.tail.isEmpty()) { // length == 1
3293 return bounds.head;
3294 } else { // length > 1
3295 int classCount = 0;
3296 for (Type bound : bounds)
3297 if (!bound.isInterface())
3298 classCount++;
3299 if (classCount > 1)
3300 return createErrorType(t);
3301 }
3302 return makeCompoundType(bounds);
3303 }
3304 // </editor-fold>
3306 // <editor-fold defaultstate="collapsed" desc="hashCode">
3307 /**
3308 * Compute a hash code on a type.
3309 */
3310 public static int hashCode(Type t) {
3311 return hashCode.visit(t);
3312 }
3313 // where
3314 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3316 public Integer visitType(Type t, Void ignored) {
3317 return t.tag;
3318 }
3320 @Override
3321 public Integer visitClassType(ClassType t, Void ignored) {
3322 int result = visit(t.getEnclosingType());
3323 result *= 127;
3324 result += t.tsym.flatName().hashCode();
3325 for (Type s : t.getTypeArguments()) {
3326 result *= 127;
3327 result += visit(s);
3328 }
3329 return result;
3330 }
3332 @Override
3333 public Integer visitWildcardType(WildcardType t, Void ignored) {
3334 int result = t.kind.hashCode();
3335 if (t.type != null) {
3336 result *= 127;
3337 result += visit(t.type);
3338 }
3339 return result;
3340 }
3342 @Override
3343 public Integer visitArrayType(ArrayType t, Void ignored) {
3344 return visit(t.elemtype) + 12;
3345 }
3347 @Override
3348 public Integer visitTypeVar(TypeVar t, Void ignored) {
3349 return System.identityHashCode(t.tsym);
3350 }
3352 @Override
3353 public Integer visitUndetVar(UndetVar t, Void ignored) {
3354 return System.identityHashCode(t);
3355 }
3357 @Override
3358 public Integer visitErrorType(ErrorType t, Void ignored) {
3359 return 0;
3360 }
3361 };
3362 // </editor-fold>
3364 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3365 /**
3366 * Does t have a result that is a subtype of the result type of s,
3367 * suitable for covariant returns? It is assumed that both types
3368 * are (possibly polymorphic) method types. Monomorphic method
3369 * types are handled in the obvious way. Polymorphic method types
3370 * require renaming all type variables of one to corresponding
3371 * type variables in the other, where correspondence is by
3372 * position in the type parameter list. */
3373 public boolean resultSubtype(Type t, Type s, Warner warner) {
3374 List<Type> tvars = t.getTypeArguments();
3375 List<Type> svars = s.getTypeArguments();
3376 Type tres = t.getReturnType();
3377 Type sres = subst(s.getReturnType(), svars, tvars);
3378 return covariantReturnType(tres, sres, warner);
3379 }
3381 /**
3382 * Return-Type-Substitutable.
3383 * @jls section 8.4.5
3384 */
3385 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3386 if (hasSameArgs(r1, r2))
3387 return resultSubtype(r1, r2, Warner.noWarnings);
3388 else
3389 return covariantReturnType(r1.getReturnType(),
3390 erasure(r2.getReturnType()),
3391 Warner.noWarnings);
3392 }
3394 public boolean returnTypeSubstitutable(Type r1,
3395 Type r2, Type r2res,
3396 Warner warner) {
3397 if (isSameType(r1.getReturnType(), r2res))
3398 return true;
3399 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3400 return false;
3402 if (hasSameArgs(r1, r2))
3403 return covariantReturnType(r1.getReturnType(), r2res, warner);
3404 if (!allowCovariantReturns)
3405 return false;
3406 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3407 return true;
3408 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3409 return false;
3410 warner.warn(LintCategory.UNCHECKED);
3411 return true;
3412 }
3414 /**
3415 * Is t an appropriate return type in an overrider for a
3416 * method that returns s?
3417 */
3418 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3419 return
3420 isSameType(t, s) ||
3421 allowCovariantReturns &&
3422 !t.isPrimitive() &&
3423 !s.isPrimitive() &&
3424 isAssignable(t, s, warner);
3425 }
3426 // </editor-fold>
3428 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3429 /**
3430 * Return the class that boxes the given primitive.
3431 */
3432 public ClassSymbol boxedClass(Type t) {
3433 return reader.enterClass(syms.boxedName[t.tag]);
3434 }
3436 /**
3437 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3438 */
3439 public Type boxedTypeOrType(Type t) {
3440 return t.isPrimitive() ?
3441 boxedClass(t).type :
3442 t;
3443 }
3445 /**
3446 * Return the primitive type corresponding to a boxed type.
3447 */
3448 public Type unboxedType(Type t) {
3449 if (allowBoxing) {
3450 for (int i=0; i<syms.boxedName.length; i++) {
3451 Name box = syms.boxedName[i];
3452 if (box != null &&
3453 asSuper(t, reader.enterClass(box)) != null)
3454 return syms.typeOfTag[i];
3455 }
3456 }
3457 return Type.noType;
3458 }
3460 /**
3461 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3462 */
3463 public Type unboxedTypeOrType(Type t) {
3464 Type unboxedType = unboxedType(t);
3465 return unboxedType.tag == NONE ? t : unboxedType;
3466 }
3467 // </editor-fold>
3469 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3470 /*
3471 * JLS 5.1.10 Capture Conversion:
3472 *
3473 * Let G name a generic type declaration with n formal type
3474 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3475 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3476 * where, for 1 <= i <= n:
3477 *
3478 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3479 * Si is a fresh type variable whose upper bound is
3480 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3481 * type.
3482 *
3483 * + If Ti is a wildcard type argument of the form ? extends Bi,
3484 * then Si is a fresh type variable whose upper bound is
3485 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3486 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3487 * a compile-time error if for any two classes (not interfaces)
3488 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3489 *
3490 * + If Ti is a wildcard type argument of the form ? super Bi,
3491 * then Si is a fresh type variable whose upper bound is
3492 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3493 *
3494 * + Otherwise, Si = Ti.
3495 *
3496 * Capture conversion on any type other than a parameterized type
3497 * (4.5) acts as an identity conversion (5.1.1). Capture
3498 * conversions never require a special action at run time and
3499 * therefore never throw an exception at run time.
3500 *
3501 * Capture conversion is not applied recursively.
3502 */
3503 /**
3504 * Capture conversion as specified by the JLS.
3505 */
3507 public List<Type> capture(List<Type> ts) {
3508 List<Type> buf = List.nil();
3509 for (Type t : ts) {
3510 buf = buf.prepend(capture(t));
3511 }
3512 return buf.reverse();
3513 }
3514 public Type capture(Type t) {
3515 if (t.tag != CLASS)
3516 return t;
3517 if (t.getEnclosingType() != Type.noType) {
3518 Type capturedEncl = capture(t.getEnclosingType());
3519 if (capturedEncl != t.getEnclosingType()) {
3520 Type type1 = memberType(capturedEncl, t.tsym);
3521 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3522 }
3523 }
3524 ClassType cls = (ClassType)t;
3525 if (cls.isRaw() || !cls.isParameterized())
3526 return cls;
3528 ClassType G = (ClassType)cls.asElement().asType();
3529 List<Type> A = G.getTypeArguments();
3530 List<Type> T = cls.getTypeArguments();
3531 List<Type> S = freshTypeVariables(T);
3533 List<Type> currentA = A;
3534 List<Type> currentT = T;
3535 List<Type> currentS = S;
3536 boolean captured = false;
3537 while (!currentA.isEmpty() &&
3538 !currentT.isEmpty() &&
3539 !currentS.isEmpty()) {
3540 if (currentS.head != currentT.head) {
3541 captured = true;
3542 WildcardType Ti = (WildcardType)currentT.head;
3543 Type Ui = currentA.head.getUpperBound();
3544 CapturedType Si = (CapturedType)currentS.head;
3545 if (Ui == null)
3546 Ui = syms.objectType;
3547 switch (Ti.kind) {
3548 case UNBOUND:
3549 Si.bound = subst(Ui, A, S);
3550 Si.lower = syms.botType;
3551 break;
3552 case EXTENDS:
3553 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3554 Si.lower = syms.botType;
3555 break;
3556 case SUPER:
3557 Si.bound = subst(Ui, A, S);
3558 Si.lower = Ti.getSuperBound();
3559 break;
3560 }
3561 if (Si.bound == Si.lower)
3562 currentS.head = Si.bound;
3563 }
3564 currentA = currentA.tail;
3565 currentT = currentT.tail;
3566 currentS = currentS.tail;
3567 }
3568 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3569 return erasure(t); // some "rare" type involved
3571 if (captured)
3572 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3573 else
3574 return t;
3575 }
3576 // where
3577 public List<Type> freshTypeVariables(List<Type> types) {
3578 ListBuffer<Type> result = lb();
3579 for (Type t : types) {
3580 if (t.tag == WILDCARD) {
3581 Type bound = ((WildcardType)t).getExtendsBound();
3582 if (bound == null)
3583 bound = syms.objectType;
3584 result.append(new CapturedType(capturedName,
3585 syms.noSymbol,
3586 bound,
3587 syms.botType,
3588 (WildcardType)t));
3589 } else {
3590 result.append(t);
3591 }
3592 }
3593 return result.toList();
3594 }
3595 // </editor-fold>
3597 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3598 private List<Type> upperBounds(List<Type> ss) {
3599 if (ss.isEmpty()) return ss;
3600 Type head = upperBound(ss.head);
3601 List<Type> tail = upperBounds(ss.tail);
3602 if (head != ss.head || tail != ss.tail)
3603 return tail.prepend(head);
3604 else
3605 return ss;
3606 }
3608 private boolean sideCast(Type from, Type to, Warner warn) {
3609 // We are casting from type $from$ to type $to$, which are
3610 // non-final unrelated types. This method
3611 // tries to reject a cast by transferring type parameters
3612 // from $to$ to $from$ by common superinterfaces.
3613 boolean reverse = false;
3614 Type target = to;
3615 if ((to.tsym.flags() & INTERFACE) == 0) {
3616 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3617 reverse = true;
3618 to = from;
3619 from = target;
3620 }
3621 List<Type> commonSupers = superClosure(to, erasure(from));
3622 boolean giveWarning = commonSupers.isEmpty();
3623 // The arguments to the supers could be unified here to
3624 // get a more accurate analysis
3625 while (commonSupers.nonEmpty()) {
3626 Type t1 = asSuper(from, commonSupers.head.tsym);
3627 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3628 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3629 return false;
3630 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3631 commonSupers = commonSupers.tail;
3632 }
3633 if (giveWarning && !isReifiable(reverse ? from : to))
3634 warn.warn(LintCategory.UNCHECKED);
3635 if (!allowCovariantReturns)
3636 // reject if there is a common method signature with
3637 // incompatible return types.
3638 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3639 return true;
3640 }
3642 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3643 // We are casting from type $from$ to type $to$, which are
3644 // unrelated types one of which is final and the other of
3645 // which is an interface. This method
3646 // tries to reject a cast by transferring type parameters
3647 // from the final class to the interface.
3648 boolean reverse = false;
3649 Type target = to;
3650 if ((to.tsym.flags() & INTERFACE) == 0) {
3651 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3652 reverse = true;
3653 to = from;
3654 from = target;
3655 }
3656 Assert.check((from.tsym.flags() & FINAL) != 0);
3657 Type t1 = asSuper(from, to.tsym);
3658 if (t1 == null) return false;
3659 Type t2 = to;
3660 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3661 return false;
3662 if (!allowCovariantReturns)
3663 // reject if there is a common method signature with
3664 // incompatible return types.
3665 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3666 if (!isReifiable(target) &&
3667 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3668 warn.warn(LintCategory.UNCHECKED);
3669 return true;
3670 }
3672 private boolean giveWarning(Type from, Type to) {
3673 Type subFrom = asSub(from, to.tsym);
3674 return to.isParameterized() &&
3675 (!(isUnbounded(to) ||
3676 isSubtype(from, to) ||
3677 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3678 }
3680 private List<Type> superClosure(Type t, Type s) {
3681 List<Type> cl = List.nil();
3682 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3683 if (isSubtype(s, erasure(l.head))) {
3684 cl = insert(cl, l.head);
3685 } else {
3686 cl = union(cl, superClosure(l.head, s));
3687 }
3688 }
3689 return cl;
3690 }
3692 private boolean containsTypeEquivalent(Type t, Type s) {
3693 return
3694 isSameType(t, s) || // shortcut
3695 containsType(t, s) && containsType(s, t);
3696 }
3698 // <editor-fold defaultstate="collapsed" desc="adapt">
3699 /**
3700 * Adapt a type by computing a substitution which maps a source
3701 * type to a target type.
3702 *
3703 * @param source the source type
3704 * @param target the target type
3705 * @param from the type variables of the computed substitution
3706 * @param to the types of the computed substitution.
3707 */
3708 public void adapt(Type source,
3709 Type target,
3710 ListBuffer<Type> from,
3711 ListBuffer<Type> to) throws AdaptFailure {
3712 new Adapter(from, to).adapt(source, target);
3713 }
3715 class Adapter extends SimpleVisitor<Void, Type> {
3717 ListBuffer<Type> from;
3718 ListBuffer<Type> to;
3719 Map<Symbol,Type> mapping;
3721 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3722 this.from = from;
3723 this.to = to;
3724 mapping = new HashMap<Symbol,Type>();
3725 }
3727 public void adapt(Type source, Type target) throws AdaptFailure {
3728 visit(source, target);
3729 List<Type> fromList = from.toList();
3730 List<Type> toList = to.toList();
3731 while (!fromList.isEmpty()) {
3732 Type val = mapping.get(fromList.head.tsym);
3733 if (toList.head != val)
3734 toList.head = val;
3735 fromList = fromList.tail;
3736 toList = toList.tail;
3737 }
3738 }
3740 @Override
3741 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3742 if (target.tag == CLASS)
3743 adaptRecursive(source.allparams(), target.allparams());
3744 return null;
3745 }
3747 @Override
3748 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3749 if (target.tag == ARRAY)
3750 adaptRecursive(elemtype(source), elemtype(target));
3751 return null;
3752 }
3754 @Override
3755 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3756 if (source.isExtendsBound())
3757 adaptRecursive(upperBound(source), upperBound(target));
3758 else if (source.isSuperBound())
3759 adaptRecursive(lowerBound(source), lowerBound(target));
3760 return null;
3761 }
3763 @Override
3764 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3765 // Check to see if there is
3766 // already a mapping for $source$, in which case
3767 // the old mapping will be merged with the new
3768 Type val = mapping.get(source.tsym);
3769 if (val != null) {
3770 if (val.isSuperBound() && target.isSuperBound()) {
3771 val = isSubtype(lowerBound(val), lowerBound(target))
3772 ? target : val;
3773 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3774 val = isSubtype(upperBound(val), upperBound(target))
3775 ? val : target;
3776 } else if (!isSameType(val, target)) {
3777 throw new AdaptFailure();
3778 }
3779 } else {
3780 val = target;
3781 from.append(source);
3782 to.append(target);
3783 }
3784 mapping.put(source.tsym, val);
3785 return null;
3786 }
3788 @Override
3789 public Void visitType(Type source, Type target) {
3790 return null;
3791 }
3793 private Set<TypePair> cache = new HashSet<TypePair>();
3795 private void adaptRecursive(Type source, Type target) {
3796 TypePair pair = new TypePair(source, target);
3797 if (cache.add(pair)) {
3798 try {
3799 visit(source, target);
3800 } finally {
3801 cache.remove(pair);
3802 }
3803 }
3804 }
3806 private void adaptRecursive(List<Type> source, List<Type> target) {
3807 if (source.length() == target.length()) {
3808 while (source.nonEmpty()) {
3809 adaptRecursive(source.head, target.head);
3810 source = source.tail;
3811 target = target.tail;
3812 }
3813 }
3814 }
3815 }
3817 public static class AdaptFailure extends RuntimeException {
3818 static final long serialVersionUID = -7490231548272701566L;
3819 }
3821 private void adaptSelf(Type t,
3822 ListBuffer<Type> from,
3823 ListBuffer<Type> to) {
3824 try {
3825 //if (t.tsym.type != t)
3826 adapt(t.tsym.type, t, from, to);
3827 } catch (AdaptFailure ex) {
3828 // Adapt should never fail calculating a mapping from
3829 // t.tsym.type to t as there can be no merge problem.
3830 throw new AssertionError(ex);
3831 }
3832 }
3833 // </editor-fold>
3835 /**
3836 * Rewrite all type variables (universal quantifiers) in the given
3837 * type to wildcards (existential quantifiers). This is used to
3838 * determine if a cast is allowed. For example, if high is true
3839 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3840 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3841 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3842 * List<Integer>} with a warning.
3843 * @param t a type
3844 * @param high if true return an upper bound; otherwise a lower
3845 * bound
3846 * @param rewriteTypeVars only rewrite captured wildcards if false;
3847 * otherwise rewrite all type variables
3848 * @return the type rewritten with wildcards (existential
3849 * quantifiers) only
3850 */
3851 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3852 return new Rewriter(high, rewriteTypeVars).visit(t);
3853 }
3855 class Rewriter extends UnaryVisitor<Type> {
3857 boolean high;
3858 boolean rewriteTypeVars;
3860 Rewriter(boolean high, boolean rewriteTypeVars) {
3861 this.high = high;
3862 this.rewriteTypeVars = rewriteTypeVars;
3863 }
3865 @Override
3866 public Type visitClassType(ClassType t, Void s) {
3867 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3868 boolean changed = false;
3869 for (Type arg : t.allparams()) {
3870 Type bound = visit(arg);
3871 if (arg != bound) {
3872 changed = true;
3873 }
3874 rewritten.append(bound);
3875 }
3876 if (changed)
3877 return subst(t.tsym.type,
3878 t.tsym.type.allparams(),
3879 rewritten.toList());
3880 else
3881 return t;
3882 }
3884 public Type visitType(Type t, Void s) {
3885 return high ? upperBound(t) : lowerBound(t);
3886 }
3888 @Override
3889 public Type visitCapturedType(CapturedType t, Void s) {
3890 Type w_bound = t.wildcard.type;
3891 Type bound = w_bound.contains(t) ?
3892 erasure(w_bound) :
3893 visit(w_bound);
3894 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
3895 }
3897 @Override
3898 public Type visitTypeVar(TypeVar t, Void s) {
3899 if (rewriteTypeVars) {
3900 Type bound = t.bound.contains(t) ?
3901 erasure(t.bound) :
3902 visit(t.bound);
3903 return rewriteAsWildcardType(bound, t, EXTENDS);
3904 } else {
3905 return t;
3906 }
3907 }
3909 @Override
3910 public Type visitWildcardType(WildcardType t, Void s) {
3911 Type bound2 = visit(t.type);
3912 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
3913 }
3915 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
3916 switch (bk) {
3917 case EXTENDS: return high ?
3918 makeExtendsWildcard(B(bound), formal) :
3919 makeExtendsWildcard(syms.objectType, formal);
3920 case SUPER: return high ?
3921 makeSuperWildcard(syms.botType, formal) :
3922 makeSuperWildcard(B(bound), formal);
3923 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
3924 default:
3925 Assert.error("Invalid bound kind " + bk);
3926 return null;
3927 }
3928 }
3930 Type B(Type t) {
3931 while (t.tag == WILDCARD) {
3932 WildcardType w = (WildcardType)t;
3933 t = high ?
3934 w.getExtendsBound() :
3935 w.getSuperBound();
3936 if (t == null) {
3937 t = high ? syms.objectType : syms.botType;
3938 }
3939 }
3940 return t;
3941 }
3942 }
3945 /**
3946 * Create a wildcard with the given upper (extends) bound; create
3947 * an unbounded wildcard if bound is Object.
3948 *
3949 * @param bound the upper bound
3950 * @param formal the formal type parameter that will be
3951 * substituted by the wildcard
3952 */
3953 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3954 if (bound == syms.objectType) {
3955 return new WildcardType(syms.objectType,
3956 BoundKind.UNBOUND,
3957 syms.boundClass,
3958 formal);
3959 } else {
3960 return new WildcardType(bound,
3961 BoundKind.EXTENDS,
3962 syms.boundClass,
3963 formal);
3964 }
3965 }
3967 /**
3968 * Create a wildcard with the given lower (super) bound; create an
3969 * unbounded wildcard if bound is bottom (type of {@code null}).
3970 *
3971 * @param bound the lower bound
3972 * @param formal the formal type parameter that will be
3973 * substituted by the wildcard
3974 */
3975 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3976 if (bound.tag == BOT) {
3977 return new WildcardType(syms.objectType,
3978 BoundKind.UNBOUND,
3979 syms.boundClass,
3980 formal);
3981 } else {
3982 return new WildcardType(bound,
3983 BoundKind.SUPER,
3984 syms.boundClass,
3985 formal);
3986 }
3987 }
3989 /**
3990 * A wrapper for a type that allows use in sets.
3991 */
3992 class SingletonType {
3993 final Type t;
3994 SingletonType(Type t) {
3995 this.t = t;
3996 }
3997 public int hashCode() {
3998 return Types.hashCode(t);
3999 }
4000 public boolean equals(Object obj) {
4001 return (obj instanceof SingletonType) &&
4002 isSameType(t, ((SingletonType)obj).t);
4003 }
4004 public String toString() {
4005 return t.toString();
4006 }
4007 }
4008 // </editor-fold>
4010 // <editor-fold defaultstate="collapsed" desc="Visitors">
4011 /**
4012 * A default visitor for types. All visitor methods except
4013 * visitType are implemented by delegating to visitType. Concrete
4014 * subclasses must provide an implementation of visitType and can
4015 * override other methods as needed.
4016 *
4017 * @param <R> the return type of the operation implemented by this
4018 * visitor; use Void if no return type is needed.
4019 * @param <S> the type of the second argument (the first being the
4020 * type itself) of the operation implemented by this visitor; use
4021 * Void if a second argument is not needed.
4022 */
4023 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4024 final public R visit(Type t, S s) { return t.accept(this, s); }
4025 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
4026 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4027 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
4028 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
4029 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
4030 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
4031 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4032 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
4033 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
4034 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
4035 }
4037 /**
4038 * A default visitor for symbols. All visitor methods except
4039 * visitSymbol are implemented by delegating to visitSymbol. Concrete
4040 * subclasses must provide an implementation of visitSymbol and can
4041 * override other methods as needed.
4042 *
4043 * @param <R> the return type of the operation implemented by this
4044 * visitor; use Void if no return type is needed.
4045 * @param <S> the type of the second argument (the first being the
4046 * symbol itself) of the operation implemented by this visitor; use
4047 * Void if a second argument is not needed.
4048 */
4049 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4050 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
4051 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
4052 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
4053 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
4054 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
4055 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
4056 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
4057 }
4059 /**
4060 * A <em>simple</em> visitor for types. This visitor is simple as
4061 * captured wildcards, for-all types (generic methods), and
4062 * undetermined type variables (part of inference) are hidden.
4063 * Captured wildcards are hidden by treating them as type
4064 * variables and the rest are hidden by visiting their qtypes.
4065 *
4066 * @param <R> the return type of the operation implemented by this
4067 * visitor; use Void if no return type is needed.
4068 * @param <S> the type of the second argument (the first being the
4069 * type itself) of the operation implemented by this visitor; use
4070 * Void if a second argument is not needed.
4071 */
4072 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4073 @Override
4074 public R visitCapturedType(CapturedType t, S s) {
4075 return visitTypeVar(t, s);
4076 }
4077 @Override
4078 public R visitForAll(ForAll t, S s) {
4079 return visit(t.qtype, s);
4080 }
4081 @Override
4082 public R visitUndetVar(UndetVar t, S s) {
4083 return visit(t.qtype, s);
4084 }
4085 }
4087 /**
4088 * A plain relation on types. That is a 2-ary function on the
4089 * form Type × Type → Boolean.
4090 * <!-- In plain text: Type x Type -> Boolean -->
4091 */
4092 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4094 /**
4095 * A convenience visitor for implementing operations that only
4096 * require one argument (the type itself), that is, unary
4097 * operations.
4098 *
4099 * @param <R> the return type of the operation implemented by this
4100 * visitor; use Void if no return type is needed.
4101 */
4102 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4103 final public R visit(Type t) { return t.accept(this, null); }
4104 }
4106 /**
4107 * A visitor for implementing a mapping from types to types. The
4108 * default behavior of this class is to implement the identity
4109 * mapping (mapping a type to itself). This can be overridden in
4110 * subclasses.
4111 *
4112 * @param <S> the type of the second argument (the first being the
4113 * type itself) of this mapping; use Void if a second argument is
4114 * not needed.
4115 */
4116 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4117 final public Type visit(Type t) { return t.accept(this, null); }
4118 public Type visitType(Type t, S s) { return t; }
4119 }
4120 // </editor-fold>
4123 // <editor-fold defaultstate="collapsed" desc="Annotation support">
4125 public RetentionPolicy getRetention(Attribute.Compound a) {
4126 return getRetention(a.type.tsym);
4127 }
4129 public RetentionPolicy getRetention(Symbol sym) {
4130 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4131 Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4132 if (c != null) {
4133 Attribute value = c.member(names.value);
4134 if (value != null && value instanceof Attribute.Enum) {
4135 Name levelName = ((Attribute.Enum)value).value.name;
4136 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4137 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4138 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4139 else ;// /* fail soft */ throw new AssertionError(levelName);
4140 }
4141 }
4142 return vis;
4143 }
4144 // </editor-fold>
4145 }