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