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