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