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