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