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