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