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