Thu, 21 Feb 2013 17:49:56 -0800
Merge
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 if (capture(site) != site) {
576 Type formalInterface = site.tsym.type;
577 ListBuffer<Type> typeargs = ListBuffer.lb();
578 List<Type> actualTypeargs = site.getTypeArguments();
579 //simply replace the wildcards with its bound
580 for (Type t : formalInterface.getTypeArguments()) {
581 if (actualTypeargs.head.hasTag(WILDCARD)) {
582 WildcardType wt = (WildcardType)actualTypeargs.head;
583 Type bound;
584 switch (wt.kind) {
585 case UNBOUND:
586 //use declared bound if it doesn't depend on formal type-args
587 bound = wt.bound.bound.containsAny(formalInterface.getTypeArguments()) ?
588 syms.objectType : wt.bound.bound;
589 break;
590 default:
591 bound = wt.type;
592 }
593 typeargs.append(bound);
594 } else {
595 typeargs.append(actualTypeargs.head);
596 }
597 actualTypeargs = actualTypeargs.tail;
598 }
599 return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
600 } else {
601 return site;
602 }
603 }
604 // </editor-fold>
606 /**
607 * Scope filter used to skip methods that should be ignored (such as methods
608 * overridden by j.l.Object) during function interface conversion/marker interface checks
609 */
610 class DescriptorFilter implements Filter<Symbol> {
612 TypeSymbol origin;
614 DescriptorFilter(TypeSymbol origin) {
615 this.origin = origin;
616 }
618 @Override
619 public boolean accepts(Symbol sym) {
620 return sym.kind == Kinds.MTH &&
621 (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
622 !overridesObjectMethod(origin, sym) &&
623 (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
624 }
625 };
627 // <editor-fold defaultstate="collapsed" desc="isMarker">
629 /**
630 * A cache that keeps track of marker interfaces
631 */
632 class MarkerCache {
634 private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
636 class Entry {
637 final boolean isMarkerIntf;
638 final int prevMark;
640 public Entry(boolean isMarkerIntf,
641 int prevMark) {
642 this.isMarkerIntf = isMarkerIntf;
643 this.prevMark = prevMark;
644 }
646 boolean matches(int mark) {
647 return this.prevMark == mark;
648 }
649 }
651 boolean get(TypeSymbol origin) throws FunctionDescriptorLookupError {
652 Entry e = _map.get(origin);
653 CompoundScope members = membersClosure(origin.type, false);
654 if (e == null ||
655 !e.matches(members.getMark())) {
656 boolean isMarkerIntf = isMarkerInterfaceInternal(origin, members);
657 _map.put(origin, new Entry(isMarkerIntf, members.getMark()));
658 return isMarkerIntf;
659 }
660 else {
661 return e.isMarkerIntf;
662 }
663 }
665 /**
666 * Is given symbol a marker interface
667 */
668 public boolean isMarkerInterfaceInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
669 return !origin.isInterface() ?
670 false :
671 !membersCache.getElements(new DescriptorFilter(origin)).iterator().hasNext();
672 }
673 }
675 private MarkerCache markerCache = new MarkerCache();
677 /**
678 * Is given type a marker interface?
679 */
680 public boolean isMarkerInterface(Type site) {
681 return markerCache.get(site.tsym);
682 }
683 // </editor-fold>
685 // <editor-fold defaultstate="collapsed" desc="isSubtype">
686 /**
687 * Is t an unchecked subtype of s?
688 */
689 public boolean isSubtypeUnchecked(Type t, Type s) {
690 return isSubtypeUnchecked(t, s, noWarnings);
691 }
692 /**
693 * Is t an unchecked subtype of s?
694 */
695 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
696 boolean result = isSubtypeUncheckedInternal(t, s, warn);
697 if (result) {
698 checkUnsafeVarargsConversion(t, s, warn);
699 }
700 return result;
701 }
702 //where
703 private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
704 if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
705 t = t.unannotatedType();
706 s = s.unannotatedType();
707 if (((ArrayType)t).elemtype.isPrimitive()) {
708 return isSameType(elemtype(t), elemtype(s));
709 } else {
710 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
711 }
712 } else if (isSubtype(t, s)) {
713 return true;
714 }
715 else if (t.tag == TYPEVAR) {
716 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
717 }
718 else if (!s.isRaw()) {
719 Type t2 = asSuper(t, s.tsym);
720 if (t2 != null && t2.isRaw()) {
721 if (isReifiable(s))
722 warn.silentWarn(LintCategory.UNCHECKED);
723 else
724 warn.warn(LintCategory.UNCHECKED);
725 return true;
726 }
727 }
728 return false;
729 }
731 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
732 if (t.tag != ARRAY || isReifiable(t))
733 return;
734 t = t.unannotatedType();
735 s = s.unannotatedType();
736 ArrayType from = (ArrayType)t;
737 boolean shouldWarn = false;
738 switch (s.tag) {
739 case ARRAY:
740 ArrayType to = (ArrayType)s;
741 shouldWarn = from.isVarargs() &&
742 !to.isVarargs() &&
743 !isReifiable(from);
744 break;
745 case CLASS:
746 shouldWarn = from.isVarargs();
747 break;
748 }
749 if (shouldWarn) {
750 warn.warn(LintCategory.VARARGS);
751 }
752 }
754 /**
755 * Is t a subtype of s?<br>
756 * (not defined for Method and ForAll types)
757 */
758 final public boolean isSubtype(Type t, Type s) {
759 return isSubtype(t, s, true);
760 }
761 final public boolean isSubtypeNoCapture(Type t, Type s) {
762 return isSubtype(t, s, false);
763 }
764 public boolean isSubtype(Type t, Type s, boolean capture) {
765 if (t == s)
766 return true;
768 t = t.unannotatedType();
769 s = s.unannotatedType();
771 if (t == s)
772 return true;
774 if (s.isPartial())
775 return isSuperType(s, t);
777 if (s.isCompound()) {
778 for (Type s2 : interfaces(s).prepend(supertype(s))) {
779 if (!isSubtype(t, s2, capture))
780 return false;
781 }
782 return true;
783 }
785 Type lower = lowerBound(s);
786 if (s != lower)
787 return isSubtype(capture ? capture(t) : t, lower, false);
789 return isSubtype.visit(capture ? capture(t) : t, s);
790 }
791 // where
792 private TypeRelation isSubtype = new TypeRelation()
793 {
794 public Boolean visitType(Type t, Type s) {
795 switch (t.tag) {
796 case BYTE:
797 return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
798 case CHAR:
799 return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
800 case SHORT: case INT: case LONG:
801 case FLOAT: case DOUBLE:
802 return t.getTag().isSubRangeOf(s.getTag());
803 case BOOLEAN: case VOID:
804 return t.hasTag(s.getTag());
805 case TYPEVAR:
806 return isSubtypeNoCapture(t.getUpperBound(), s);
807 case BOT:
808 return
809 s.hasTag(BOT) || s.hasTag(CLASS) ||
810 s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
811 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
812 case NONE:
813 return false;
814 default:
815 throw new AssertionError("isSubtype " + t.tag);
816 }
817 }
819 private Set<TypePair> cache = new HashSet<TypePair>();
821 private boolean containsTypeRecursive(Type t, Type s) {
822 TypePair pair = new TypePair(t, s);
823 if (cache.add(pair)) {
824 try {
825 return containsType(t.getTypeArguments(),
826 s.getTypeArguments());
827 } finally {
828 cache.remove(pair);
829 }
830 } else {
831 return containsType(t.getTypeArguments(),
832 rewriteSupers(s).getTypeArguments());
833 }
834 }
836 private Type rewriteSupers(Type t) {
837 if (!t.isParameterized())
838 return t;
839 ListBuffer<Type> from = lb();
840 ListBuffer<Type> to = lb();
841 adaptSelf(t, from, to);
842 if (from.isEmpty())
843 return t;
844 ListBuffer<Type> rewrite = lb();
845 boolean changed = false;
846 for (Type orig : to.toList()) {
847 Type s = rewriteSupers(orig);
848 if (s.isSuperBound() && !s.isExtendsBound()) {
849 s = new WildcardType(syms.objectType,
850 BoundKind.UNBOUND,
851 syms.boundClass);
852 changed = true;
853 } else if (s != orig) {
854 s = new WildcardType(upperBound(s),
855 BoundKind.EXTENDS,
856 syms.boundClass);
857 changed = true;
858 }
859 rewrite.append(s);
860 }
861 if (changed)
862 return subst(t.tsym.type, from.toList(), rewrite.toList());
863 else
864 return t;
865 }
867 @Override
868 public Boolean visitClassType(ClassType t, Type s) {
869 Type sup = asSuper(t, s.tsym);
870 return sup != null
871 && sup.tsym == s.tsym
872 // You're not allowed to write
873 // Vector<Object> vec = new Vector<String>();
874 // But with wildcards you can write
875 // Vector<? extends Object> vec = new Vector<String>();
876 // which means that subtype checking must be done
877 // here instead of same-type checking (via containsType).
878 && (!s.isParameterized() || containsTypeRecursive(s, sup))
879 && isSubtypeNoCapture(sup.getEnclosingType(),
880 s.getEnclosingType());
881 }
883 @Override
884 public Boolean visitArrayType(ArrayType t, Type s) {
885 if (s.tag == ARRAY) {
886 if (t.elemtype.isPrimitive())
887 return isSameType(t.elemtype, elemtype(s));
888 else
889 return isSubtypeNoCapture(t.elemtype, elemtype(s));
890 }
892 if (s.tag == CLASS) {
893 Name sname = s.tsym.getQualifiedName();
894 return sname == names.java_lang_Object
895 || sname == names.java_lang_Cloneable
896 || sname == names.java_io_Serializable;
897 }
899 return false;
900 }
902 @Override
903 public Boolean visitUndetVar(UndetVar t, Type s) {
904 //todo: test against origin needed? or replace with substitution?
905 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
906 return true;
907 } else if (s.tag == BOT) {
908 //if 's' is 'null' there's no instantiated type U for which
909 //U <: s (but 'null' itself, which is not a valid type)
910 return false;
911 }
913 t.addBound(InferenceBound.UPPER, s, Types.this);
914 return true;
915 }
917 @Override
918 public Boolean visitErrorType(ErrorType t, Type s) {
919 return true;
920 }
921 };
923 /**
924 * Is t a subtype of every type in given list `ts'?<br>
925 * (not defined for Method and ForAll types)<br>
926 * Allows unchecked conversions.
927 */
928 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
929 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
930 if (!isSubtypeUnchecked(t, l.head, warn))
931 return false;
932 return true;
933 }
935 /**
936 * Are corresponding elements of ts subtypes of ss? If lists are
937 * of different length, return false.
938 */
939 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
940 while (ts.tail != null && ss.tail != null
941 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
942 isSubtype(ts.head, ss.head)) {
943 ts = ts.tail;
944 ss = ss.tail;
945 }
946 return ts.tail == null && ss.tail == null;
947 /*inlined: ts.isEmpty() && ss.isEmpty();*/
948 }
950 /**
951 * Are corresponding elements of ts subtypes of ss, allowing
952 * unchecked conversions? If lists are of different length,
953 * return false.
954 **/
955 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
956 while (ts.tail != null && ss.tail != null
957 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
958 isSubtypeUnchecked(ts.head, ss.head, warn)) {
959 ts = ts.tail;
960 ss = ss.tail;
961 }
962 return ts.tail == null && ss.tail == null;
963 /*inlined: ts.isEmpty() && ss.isEmpty();*/
964 }
965 // </editor-fold>
967 // <editor-fold defaultstate="collapsed" desc="isSuperType">
968 /**
969 * Is t a supertype of s?
970 */
971 public boolean isSuperType(Type t, Type s) {
972 switch (t.tag) {
973 case ERROR:
974 return true;
975 case UNDETVAR: {
976 UndetVar undet = (UndetVar)t;
977 if (t == s ||
978 undet.qtype == s ||
979 s.tag == ERROR ||
980 s.tag == BOT) return true;
981 undet.addBound(InferenceBound.LOWER, s, this);
982 return true;
983 }
984 default:
985 return isSubtype(s, t);
986 }
987 }
988 // </editor-fold>
990 // <editor-fold defaultstate="collapsed" desc="isSameType">
991 /**
992 * Are corresponding elements of the lists the same type? If
993 * lists are of different length, return false.
994 */
995 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
996 return isSameTypes(ts, ss, false);
997 }
998 public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
999 while (ts.tail != null && ss.tail != null
1000 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1001 isSameType(ts.head, ss.head, strict)) {
1002 ts = ts.tail;
1003 ss = ss.tail;
1004 }
1005 return ts.tail == null && ss.tail == null;
1006 /*inlined: ts.isEmpty() && ss.isEmpty();*/
1007 }
1009 /**
1010 * Is t the same type as s?
1011 */
1012 public boolean isSameType(Type t, Type s) {
1013 return isSameType(t, s, false);
1014 }
1015 public boolean isSameType(Type t, Type s, boolean strict) {
1016 return strict ?
1017 isSameTypeStrict.visit(t, s) :
1018 isSameTypeLoose.visit(t, s);
1019 }
1020 // where
1021 abstract class SameTypeVisitor extends TypeRelation {
1023 public Boolean visitType(Type t, Type s) {
1024 if (t == s)
1025 return true;
1027 if (s.isPartial())
1028 return visit(s, t);
1030 switch (t.tag) {
1031 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1032 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
1033 return t.tag == s.tag;
1034 case TYPEVAR: {
1035 if (s.tag == TYPEVAR) {
1036 //type-substitution does not preserve type-var types
1037 //check that type var symbols and bounds are indeed the same
1038 return sameTypeVars((TypeVar)t, (TypeVar)s);
1039 }
1040 else {
1041 //special case for s == ? super X, where upper(s) = u
1042 //check that u == t, where u has been set by Type.withTypeVar
1043 return s.isSuperBound() &&
1044 !s.isExtendsBound() &&
1045 visit(t, upperBound(s));
1046 }
1047 }
1048 default:
1049 throw new AssertionError("isSameType " + t.tag);
1050 }
1051 }
1053 abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
1055 @Override
1056 public Boolean visitWildcardType(WildcardType t, Type s) {
1057 if (s.isPartial())
1058 return visit(s, t);
1059 else
1060 return false;
1061 }
1063 @Override
1064 public Boolean visitClassType(ClassType t, Type s) {
1065 if (t == s)
1066 return true;
1068 if (s.isPartial())
1069 return visit(s, t);
1071 if (s.isSuperBound() && !s.isExtendsBound())
1072 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
1074 if (t.isCompound() && s.isCompound()) {
1075 if (!visit(supertype(t), supertype(s)))
1076 return false;
1078 HashSet<UniqueType> set = new HashSet<UniqueType>();
1079 for (Type x : interfaces(t))
1080 set.add(new UniqueType(x, Types.this));
1081 for (Type x : interfaces(s)) {
1082 if (!set.remove(new UniqueType(x, Types.this)))
1083 return false;
1084 }
1085 return (set.isEmpty());
1086 }
1087 return t.tsym == s.tsym
1088 && visit(t.getEnclosingType(), s.getEnclosingType())
1089 && containsTypes(t.getTypeArguments(), s.getTypeArguments());
1090 }
1092 abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
1094 @Override
1095 public Boolean visitArrayType(ArrayType t, Type s) {
1096 if (t == s)
1097 return true;
1099 if (s.isPartial())
1100 return visit(s, t);
1102 return s.hasTag(ARRAY)
1103 && containsTypeEquivalent(t.elemtype, elemtype(s));
1104 }
1106 @Override
1107 public Boolean visitMethodType(MethodType t, Type s) {
1108 // isSameType for methods does not take thrown
1109 // exceptions into account!
1110 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
1111 }
1113 @Override
1114 public Boolean visitPackageType(PackageType t, Type s) {
1115 return t == s;
1116 }
1118 @Override
1119 public Boolean visitForAll(ForAll t, Type s) {
1120 if (s.tag != FORALL)
1121 return false;
1123 ForAll forAll = (ForAll)s;
1124 return hasSameBounds(t, forAll)
1125 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1126 }
1128 @Override
1129 public Boolean visitUndetVar(UndetVar t, Type s) {
1130 if (s.tag == WILDCARD)
1131 // FIXME, this might be leftovers from before capture conversion
1132 return false;
1134 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
1135 return true;
1137 t.addBound(InferenceBound.EQ, s, Types.this);
1139 return true;
1140 }
1142 @Override
1143 public Boolean visitErrorType(ErrorType t, Type s) {
1144 return true;
1145 }
1146 }
1148 /**
1149 * Standard type-equality relation - type variables are considered
1150 * equals if they share the same type symbol.
1151 */
1152 TypeRelation isSameTypeLoose = new SameTypeVisitor() {
1153 @Override
1154 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
1155 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
1156 }
1157 @Override
1158 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
1159 return containsTypeEquivalent(ts1, ts2);
1160 }
1161 };
1163 /**
1164 * Strict type-equality relation - type variables are considered
1165 * equals if they share the same object identity.
1166 */
1167 TypeRelation isSameTypeStrict = new SameTypeVisitor() {
1168 @Override
1169 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
1170 return tv1 == tv2;
1171 }
1172 @Override
1173 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
1174 return isSameTypes(ts1, ts2, true);
1175 }
1176 };
1177 // </editor-fold>
1179 // <editor-fold defaultstate="collapsed" desc="Contains Type">
1180 public boolean containedBy(Type t, Type s) {
1181 switch (t.tag) {
1182 case UNDETVAR:
1183 if (s.tag == WILDCARD) {
1184 UndetVar undetvar = (UndetVar)t;
1185 WildcardType wt = (WildcardType)s;
1186 switch(wt.kind) {
1187 case UNBOUND: //similar to ? extends Object
1188 case EXTENDS: {
1189 Type bound = upperBound(s);
1190 undetvar.addBound(InferenceBound.UPPER, bound, this);
1191 break;
1192 }
1193 case SUPER: {
1194 Type bound = lowerBound(s);
1195 undetvar.addBound(InferenceBound.LOWER, bound, this);
1196 break;
1197 }
1198 }
1199 return true;
1200 } else {
1201 return isSameType(t, s);
1202 }
1203 case ERROR:
1204 return true;
1205 default:
1206 return containsType(s, t);
1207 }
1208 }
1210 boolean containsType(List<Type> ts, List<Type> ss) {
1211 while (ts.nonEmpty() && ss.nonEmpty()
1212 && containsType(ts.head, ss.head)) {
1213 ts = ts.tail;
1214 ss = ss.tail;
1215 }
1216 return ts.isEmpty() && ss.isEmpty();
1217 }
1219 /**
1220 * Check if t contains s.
1221 *
1222 * <p>T contains S if:
1223 *
1224 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1225 *
1226 * <p>This relation is only used by ClassType.isSubtype(), that
1227 * is,
1228 *
1229 * <p>{@code C<S> <: C<T> if T contains S.}
1230 *
1231 * <p>Because of F-bounds, this relation can lead to infinite
1232 * recursion. Thus we must somehow break that recursion. Notice
1233 * that containsType() is only called from ClassType.isSubtype().
1234 * Since the arguments have already been checked against their
1235 * bounds, we know:
1236 *
1237 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1238 *
1239 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1240 *
1241 * @param t a type
1242 * @param s a type
1243 */
1244 public boolean containsType(Type t, Type s) {
1245 return containsType.visit(t, s);
1246 }
1247 // where
1248 private TypeRelation containsType = new TypeRelation() {
1250 private Type U(Type t) {
1251 while (t.tag == WILDCARD) {
1252 WildcardType w = (WildcardType)t;
1253 if (w.isSuperBound())
1254 return w.bound == null ? syms.objectType : w.bound.bound;
1255 else
1256 t = w.type;
1257 }
1258 return t;
1259 }
1261 private Type L(Type t) {
1262 while (t.tag == WILDCARD) {
1263 WildcardType w = (WildcardType)t;
1264 if (w.isExtendsBound())
1265 return syms.botType;
1266 else
1267 t = w.type;
1268 }
1269 return t;
1270 }
1272 public Boolean visitType(Type t, Type s) {
1273 if (s.isPartial())
1274 return containedBy(s, t);
1275 else
1276 return isSameType(t, s);
1277 }
1279 // void debugContainsType(WildcardType t, Type s) {
1280 // System.err.println();
1281 // System.err.format(" does %s contain %s?%n", t, s);
1282 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1283 // upperBound(s), s, t, U(t),
1284 // t.isSuperBound()
1285 // || isSubtypeNoCapture(upperBound(s), U(t)));
1286 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1287 // L(t), t, s, lowerBound(s),
1288 // t.isExtendsBound()
1289 // || isSubtypeNoCapture(L(t), lowerBound(s)));
1290 // System.err.println();
1291 // }
1293 @Override
1294 public Boolean visitWildcardType(WildcardType t, Type s) {
1295 if (s.isPartial())
1296 return containedBy(s, t);
1297 else {
1298 // debugContainsType(t, s);
1299 return isSameWildcard(t, s)
1300 || isCaptureOf(s, t)
1301 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
1302 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
1303 }
1304 }
1306 @Override
1307 public Boolean visitUndetVar(UndetVar t, Type s) {
1308 if (s.tag != WILDCARD)
1309 return isSameType(t, s);
1310 else
1311 return false;
1312 }
1314 @Override
1315 public Boolean visitErrorType(ErrorType t, Type s) {
1316 return true;
1317 }
1318 };
1320 public boolean isCaptureOf(Type s, WildcardType t) {
1321 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
1322 return false;
1323 return isSameWildcard(t, ((CapturedType)s).wildcard);
1324 }
1326 public boolean isSameWildcard(WildcardType t, Type s) {
1327 if (s.tag != WILDCARD)
1328 return false;
1329 WildcardType w = (WildcardType)s;
1330 return w.kind == t.kind && w.type == t.type;
1331 }
1333 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1334 while (ts.nonEmpty() && ss.nonEmpty()
1335 && containsTypeEquivalent(ts.head, ss.head)) {
1336 ts = ts.tail;
1337 ss = ss.tail;
1338 }
1339 return ts.isEmpty() && ss.isEmpty();
1340 }
1341 // </editor-fold>
1343 // <editor-fold defaultstate="collapsed" desc="isCastable">
1344 public boolean isCastable(Type t, Type s) {
1345 return isCastable(t, s, noWarnings);
1346 }
1348 /**
1349 * Is t is castable to s?<br>
1350 * s is assumed to be an erased type.<br>
1351 * (not defined for Method and ForAll types).
1352 */
1353 public boolean isCastable(Type t, Type s, Warner warn) {
1354 if (t == s)
1355 return true;
1357 if (t.isPrimitive() != s.isPrimitive())
1358 return allowBoxing && (
1359 isConvertible(t, s, warn)
1360 || (allowObjectToPrimitiveCast &&
1361 s.isPrimitive() &&
1362 isSubtype(boxedClass(s).type, t)));
1363 if (warn != warnStack.head) {
1364 try {
1365 warnStack = warnStack.prepend(warn);
1366 checkUnsafeVarargsConversion(t, s, warn);
1367 return isCastable.visit(t,s);
1368 } finally {
1369 warnStack = warnStack.tail;
1370 }
1371 } else {
1372 return isCastable.visit(t,s);
1373 }
1374 }
1375 // where
1376 private TypeRelation isCastable = new TypeRelation() {
1378 public Boolean visitType(Type t, Type s) {
1379 if (s.tag == ERROR)
1380 return true;
1382 switch (t.tag) {
1383 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1384 case DOUBLE:
1385 return s.isNumeric();
1386 case BOOLEAN:
1387 return s.tag == BOOLEAN;
1388 case VOID:
1389 return false;
1390 case BOT:
1391 return isSubtype(t, s);
1392 default:
1393 throw new AssertionError();
1394 }
1395 }
1397 @Override
1398 public Boolean visitWildcardType(WildcardType t, Type s) {
1399 return isCastable(upperBound(t), s, warnStack.head);
1400 }
1402 @Override
1403 public Boolean visitClassType(ClassType t, Type s) {
1404 if (s.tag == ERROR || s.tag == BOT)
1405 return true;
1407 if (s.tag == TYPEVAR) {
1408 if (isCastable(t, s.getUpperBound(), noWarnings)) {
1409 warnStack.head.warn(LintCategory.UNCHECKED);
1410 return true;
1411 } else {
1412 return false;
1413 }
1414 }
1416 if (t.isCompound()) {
1417 Warner oldWarner = warnStack.head;
1418 warnStack.head = noWarnings;
1419 if (!visit(supertype(t), s))
1420 return false;
1421 for (Type intf : interfaces(t)) {
1422 if (!visit(intf, s))
1423 return false;
1424 }
1425 if (warnStack.head.hasLint(LintCategory.UNCHECKED))
1426 oldWarner.warn(LintCategory.UNCHECKED);
1427 return true;
1428 }
1430 if (s.isCompound()) {
1431 // call recursively to reuse the above code
1432 return visitClassType((ClassType)s, t);
1433 }
1435 if (s.tag == CLASS || s.tag == ARRAY) {
1436 boolean upcast;
1437 if ((upcast = isSubtype(erasure(t), erasure(s)))
1438 || isSubtype(erasure(s), erasure(t))) {
1439 if (!upcast && s.tag == ARRAY) {
1440 if (!isReifiable(s))
1441 warnStack.head.warn(LintCategory.UNCHECKED);
1442 return true;
1443 } else if (s.isRaw()) {
1444 return true;
1445 } else if (t.isRaw()) {
1446 if (!isUnbounded(s))
1447 warnStack.head.warn(LintCategory.UNCHECKED);
1448 return true;
1449 }
1450 // Assume |a| <: |b|
1451 final Type a = upcast ? t : s;
1452 final Type b = upcast ? s : t;
1453 final boolean HIGH = true;
1454 final boolean LOW = false;
1455 final boolean DONT_REWRITE_TYPEVARS = false;
1456 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1457 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1458 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1459 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1460 Type lowSub = asSub(bLow, aLow.tsym);
1461 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1462 if (highSub == null) {
1463 final boolean REWRITE_TYPEVARS = true;
1464 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1465 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1466 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1467 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1468 lowSub = asSub(bLow, aLow.tsym);
1469 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1470 }
1471 if (highSub != null) {
1472 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1473 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1474 }
1475 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1476 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1477 && !disjointTypes(aLow.allparams(), highSub.allparams())
1478 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1479 if (upcast ? giveWarning(a, b) :
1480 giveWarning(b, a))
1481 warnStack.head.warn(LintCategory.UNCHECKED);
1482 return true;
1483 }
1484 }
1485 if (isReifiable(s))
1486 return isSubtypeUnchecked(a, b);
1487 else
1488 return isSubtypeUnchecked(a, b, warnStack.head);
1489 }
1491 // Sidecast
1492 if (s.tag == CLASS) {
1493 if ((s.tsym.flags() & INTERFACE) != 0) {
1494 return ((t.tsym.flags() & FINAL) == 0)
1495 ? sideCast(t, s, warnStack.head)
1496 : sideCastFinal(t, s, warnStack.head);
1497 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1498 return ((s.tsym.flags() & FINAL) == 0)
1499 ? sideCast(t, s, warnStack.head)
1500 : sideCastFinal(t, s, warnStack.head);
1501 } else {
1502 // unrelated class types
1503 return false;
1504 }
1505 }
1506 }
1507 return false;
1508 }
1510 @Override
1511 public Boolean visitArrayType(ArrayType t, Type s) {
1512 switch (s.tag) {
1513 case ERROR:
1514 case BOT:
1515 return true;
1516 case TYPEVAR:
1517 if (isCastable(s, t, noWarnings)) {
1518 warnStack.head.warn(LintCategory.UNCHECKED);
1519 return true;
1520 } else {
1521 return false;
1522 }
1523 case CLASS:
1524 return isSubtype(t, s);
1525 case ARRAY:
1526 if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
1527 return elemtype(t).tag == elemtype(s).tag;
1528 } else {
1529 return visit(elemtype(t), elemtype(s));
1530 }
1531 default:
1532 return false;
1533 }
1534 }
1536 @Override
1537 public Boolean visitTypeVar(TypeVar t, Type s) {
1538 switch (s.tag) {
1539 case ERROR:
1540 case BOT:
1541 return true;
1542 case TYPEVAR:
1543 if (isSubtype(t, s)) {
1544 return true;
1545 } else if (isCastable(t.bound, s, noWarnings)) {
1546 warnStack.head.warn(LintCategory.UNCHECKED);
1547 return true;
1548 } else {
1549 return false;
1550 }
1551 default:
1552 return isCastable(t.bound, s, warnStack.head);
1553 }
1554 }
1556 @Override
1557 public Boolean visitErrorType(ErrorType t, Type s) {
1558 return true;
1559 }
1560 };
1561 // </editor-fold>
1563 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1564 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1565 while (ts.tail != null && ss.tail != null) {
1566 if (disjointType(ts.head, ss.head)) return true;
1567 ts = ts.tail;
1568 ss = ss.tail;
1569 }
1570 return false;
1571 }
1573 /**
1574 * Two types or wildcards are considered disjoint if it can be
1575 * proven that no type can be contained in both. It is
1576 * conservative in that it is allowed to say that two types are
1577 * not disjoint, even though they actually are.
1578 *
1579 * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1580 * {@code X} and {@code Y} are not disjoint.
1581 */
1582 public boolean disjointType(Type t, Type s) {
1583 return disjointType.visit(t, s);
1584 }
1585 // where
1586 private TypeRelation disjointType = new TypeRelation() {
1588 private Set<TypePair> cache = new HashSet<TypePair>();
1590 public Boolean visitType(Type t, Type s) {
1591 if (s.tag == WILDCARD)
1592 return visit(s, t);
1593 else
1594 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1595 }
1597 private boolean isCastableRecursive(Type t, Type s) {
1598 TypePair pair = new TypePair(t, s);
1599 if (cache.add(pair)) {
1600 try {
1601 return Types.this.isCastable(t, s);
1602 } finally {
1603 cache.remove(pair);
1604 }
1605 } else {
1606 return true;
1607 }
1608 }
1610 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1611 TypePair pair = new TypePair(t, s);
1612 if (cache.add(pair)) {
1613 try {
1614 return Types.this.notSoftSubtype(t, s);
1615 } finally {
1616 cache.remove(pair);
1617 }
1618 } else {
1619 return false;
1620 }
1621 }
1623 @Override
1624 public Boolean visitWildcardType(WildcardType t, Type s) {
1625 if (t.isUnbound())
1626 return false;
1628 if (s.tag != WILDCARD) {
1629 if (t.isExtendsBound())
1630 return notSoftSubtypeRecursive(s, t.type);
1631 else // isSuperBound()
1632 return notSoftSubtypeRecursive(t.type, s);
1633 }
1635 if (s.isUnbound())
1636 return false;
1638 if (t.isExtendsBound()) {
1639 if (s.isExtendsBound())
1640 return !isCastableRecursive(t.type, upperBound(s));
1641 else if (s.isSuperBound())
1642 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1643 } else if (t.isSuperBound()) {
1644 if (s.isExtendsBound())
1645 return notSoftSubtypeRecursive(t.type, upperBound(s));
1646 }
1647 return false;
1648 }
1649 };
1650 // </editor-fold>
1652 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1653 /**
1654 * Returns the lower bounds of the formals of a method.
1655 */
1656 public List<Type> lowerBoundArgtypes(Type t) {
1657 return lowerBounds(t.getParameterTypes());
1658 }
1659 public List<Type> lowerBounds(List<Type> ts) {
1660 return map(ts, lowerBoundMapping);
1661 }
1662 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1663 public Type apply(Type t) {
1664 return lowerBound(t);
1665 }
1666 };
1667 // </editor-fold>
1669 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1670 /**
1671 * This relation answers the question: is impossible that
1672 * something of type `t' can be a subtype of `s'? This is
1673 * different from the question "is `t' not a subtype of `s'?"
1674 * when type variables are involved: Integer is not a subtype of T
1675 * where {@code <T extends Number>} but it is not true that Integer cannot
1676 * possibly be a subtype of T.
1677 */
1678 public boolean notSoftSubtype(Type t, Type s) {
1679 if (t == s) return false;
1680 if (t.tag == TYPEVAR) {
1681 TypeVar tv = (TypeVar) t;
1682 return !isCastable(tv.bound,
1683 relaxBound(s),
1684 noWarnings);
1685 }
1686 if (s.tag != WILDCARD)
1687 s = upperBound(s);
1689 return !isSubtype(t, relaxBound(s));
1690 }
1692 private Type relaxBound(Type t) {
1693 if (t.tag == TYPEVAR) {
1694 while (t.tag == TYPEVAR)
1695 t = t.getUpperBound();
1696 t = rewriteQuantifiers(t, true, true);
1697 }
1698 return t;
1699 }
1700 // </editor-fold>
1702 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1703 public boolean isReifiable(Type t) {
1704 return isReifiable.visit(t);
1705 }
1706 // where
1707 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1709 public Boolean visitType(Type t, Void ignored) {
1710 return true;
1711 }
1713 @Override
1714 public Boolean visitClassType(ClassType t, Void ignored) {
1715 if (t.isCompound())
1716 return false;
1717 else {
1718 if (!t.isParameterized())
1719 return true;
1721 for (Type param : t.allparams()) {
1722 if (!param.isUnbound())
1723 return false;
1724 }
1725 return true;
1726 }
1727 }
1729 @Override
1730 public Boolean visitArrayType(ArrayType t, Void ignored) {
1731 return visit(t.elemtype);
1732 }
1734 @Override
1735 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1736 return false;
1737 }
1738 };
1739 // </editor-fold>
1741 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1742 public boolean isArray(Type t) {
1743 while (t.tag == WILDCARD)
1744 t = upperBound(t);
1745 return t.tag == ARRAY;
1746 }
1748 /**
1749 * The element type of an array.
1750 */
1751 public Type elemtype(Type t) {
1752 switch (t.tag) {
1753 case WILDCARD:
1754 return elemtype(upperBound(t));
1755 case ARRAY:
1756 t = t.unannotatedType();
1757 return ((ArrayType)t).elemtype;
1758 case FORALL:
1759 return elemtype(((ForAll)t).qtype);
1760 case ERROR:
1761 return t;
1762 default:
1763 return null;
1764 }
1765 }
1767 public Type elemtypeOrType(Type t) {
1768 Type elemtype = elemtype(t);
1769 return elemtype != null ?
1770 elemtype :
1771 t;
1772 }
1774 /**
1775 * Mapping to take element type of an arraytype
1776 */
1777 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1778 public Type apply(Type t) { return elemtype(t); }
1779 };
1781 /**
1782 * The number of dimensions of an array type.
1783 */
1784 public int dimensions(Type t) {
1785 int result = 0;
1786 while (t.tag == ARRAY) {
1787 result++;
1788 t = elemtype(t);
1789 }
1790 return result;
1791 }
1793 /**
1794 * Returns an ArrayType with the component type t
1795 *
1796 * @param t The component type of the ArrayType
1797 * @return the ArrayType for the given component
1798 */
1799 public ArrayType makeArrayType(Type t) {
1800 if (t.tag == VOID ||
1801 t.tag == PACKAGE) {
1802 Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
1803 }
1804 return new ArrayType(t, syms.arrayClass);
1805 }
1806 // </editor-fold>
1808 // <editor-fold defaultstate="collapsed" desc="asSuper">
1809 /**
1810 * Return the (most specific) base type of t that starts with the
1811 * given symbol. If none exists, return null.
1812 *
1813 * @param t a type
1814 * @param sym a symbol
1815 */
1816 public Type asSuper(Type t, Symbol sym) {
1817 return asSuper.visit(t, sym);
1818 }
1819 // where
1820 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1822 public Type visitType(Type t, Symbol sym) {
1823 return null;
1824 }
1826 @Override
1827 public Type visitClassType(ClassType t, Symbol sym) {
1828 if (t.tsym == sym)
1829 return t;
1831 Type st = supertype(t);
1832 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1833 Type x = asSuper(st, sym);
1834 if (x != null)
1835 return x;
1836 }
1837 if ((sym.flags() & INTERFACE) != 0) {
1838 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1839 Type x = asSuper(l.head, sym);
1840 if (x != null)
1841 return x;
1842 }
1843 }
1844 return null;
1845 }
1847 @Override
1848 public Type visitArrayType(ArrayType t, Symbol sym) {
1849 return isSubtype(t, sym.type) ? sym.type : null;
1850 }
1852 @Override
1853 public Type visitTypeVar(TypeVar t, Symbol sym) {
1854 if (t.tsym == sym)
1855 return t;
1856 else
1857 return asSuper(t.bound, sym);
1858 }
1860 @Override
1861 public Type visitErrorType(ErrorType t, Symbol sym) {
1862 return t;
1863 }
1864 };
1866 /**
1867 * Return the base type of t or any of its outer types that starts
1868 * with the given symbol. If none exists, return null.
1869 *
1870 * @param t a type
1871 * @param sym a symbol
1872 */
1873 public Type asOuterSuper(Type t, Symbol sym) {
1874 switch (t.tag) {
1875 case CLASS:
1876 do {
1877 Type s = asSuper(t, sym);
1878 if (s != null) return s;
1879 t = t.getEnclosingType();
1880 } while (t.tag == CLASS);
1881 return null;
1882 case ARRAY:
1883 return isSubtype(t, sym.type) ? sym.type : null;
1884 case TYPEVAR:
1885 return asSuper(t, sym);
1886 case ERROR:
1887 return t;
1888 default:
1889 return null;
1890 }
1891 }
1893 /**
1894 * Return the base type of t or any of its enclosing types that
1895 * starts with the given symbol. If none exists, return null.
1896 *
1897 * @param t a type
1898 * @param sym a symbol
1899 */
1900 public Type asEnclosingSuper(Type t, Symbol sym) {
1901 switch (t.tag) {
1902 case CLASS:
1903 do {
1904 Type s = asSuper(t, sym);
1905 if (s != null) return s;
1906 Type outer = t.getEnclosingType();
1907 t = (outer.tag == CLASS) ? outer :
1908 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1909 Type.noType;
1910 } while (t.tag == CLASS);
1911 return null;
1912 case ARRAY:
1913 return isSubtype(t, sym.type) ? sym.type : null;
1914 case TYPEVAR:
1915 return asSuper(t, sym);
1916 case ERROR:
1917 return t;
1918 default:
1919 return null;
1920 }
1921 }
1922 // </editor-fold>
1924 // <editor-fold defaultstate="collapsed" desc="memberType">
1925 /**
1926 * The type of given symbol, seen as a member of t.
1927 *
1928 * @param t a type
1929 * @param sym a symbol
1930 */
1931 public Type memberType(Type t, Symbol sym) {
1932 return (sym.flags() & STATIC) != 0
1933 ? sym.type
1934 : memberType.visit(t, sym);
1935 }
1936 // where
1937 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1939 public Type visitType(Type t, Symbol sym) {
1940 return sym.type;
1941 }
1943 @Override
1944 public Type visitWildcardType(WildcardType t, Symbol sym) {
1945 return memberType(upperBound(t), sym);
1946 }
1948 @Override
1949 public Type visitClassType(ClassType t, Symbol sym) {
1950 Symbol owner = sym.owner;
1951 long flags = sym.flags();
1952 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1953 Type base = asOuterSuper(t, owner);
1954 //if t is an intersection type T = CT & I1 & I2 ... & In
1955 //its supertypes CT, I1, ... In might contain wildcards
1956 //so we need to go through capture conversion
1957 base = t.isCompound() ? capture(base) : base;
1958 if (base != null) {
1959 List<Type> ownerParams = owner.type.allparams();
1960 List<Type> baseParams = base.allparams();
1961 if (ownerParams.nonEmpty()) {
1962 if (baseParams.isEmpty()) {
1963 // then base is a raw type
1964 return erasure(sym.type);
1965 } else {
1966 return subst(sym.type, ownerParams, baseParams);
1967 }
1968 }
1969 }
1970 }
1971 return sym.type;
1972 }
1974 @Override
1975 public Type visitTypeVar(TypeVar t, Symbol sym) {
1976 return memberType(t.bound, sym);
1977 }
1979 @Override
1980 public Type visitErrorType(ErrorType t, Symbol sym) {
1981 return t;
1982 }
1983 };
1984 // </editor-fold>
1986 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1987 public boolean isAssignable(Type t, Type s) {
1988 return isAssignable(t, s, noWarnings);
1989 }
1991 /**
1992 * Is t assignable to s?<br>
1993 * Equivalent to subtype except for constant values and raw
1994 * types.<br>
1995 * (not defined for Method and ForAll types)
1996 */
1997 public boolean isAssignable(Type t, Type s, Warner warn) {
1998 if (t.tag == ERROR)
1999 return true;
2000 if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
2001 int value = ((Number)t.constValue()).intValue();
2002 switch (s.tag) {
2003 case BYTE:
2004 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
2005 return true;
2006 break;
2007 case CHAR:
2008 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
2009 return true;
2010 break;
2011 case SHORT:
2012 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
2013 return true;
2014 break;
2015 case INT:
2016 return true;
2017 case CLASS:
2018 switch (unboxedType(s).tag) {
2019 case BYTE:
2020 case CHAR:
2021 case SHORT:
2022 return isAssignable(t, unboxedType(s), warn);
2023 }
2024 break;
2025 }
2026 }
2027 return isConvertible(t, s, warn);
2028 }
2029 // </editor-fold>
2031 // <editor-fold defaultstate="collapsed" desc="erasure">
2032 /**
2033 * The erasure of t {@code |t|} -- the type that results when all
2034 * type parameters in t are deleted.
2035 */
2036 public Type erasure(Type t) {
2037 return eraseNotNeeded(t)? t : erasure(t, false);
2038 }
2039 //where
2040 private boolean eraseNotNeeded(Type t) {
2041 // We don't want to erase primitive types and String type as that
2042 // operation is idempotent. Also, erasing these could result in loss
2043 // of information such as constant values attached to such types.
2044 return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
2045 }
2047 private Type erasure(Type t, boolean recurse) {
2048 if (t.isPrimitive())
2049 return t; /* fast special case */
2050 else
2051 return erasure.visit(t, recurse);
2052 }
2053 // where
2054 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
2055 public Type visitType(Type t, Boolean recurse) {
2056 if (t.isPrimitive())
2057 return t; /*fast special case*/
2058 else
2059 return t.map(recurse ? erasureRecFun : erasureFun);
2060 }
2062 @Override
2063 public Type visitWildcardType(WildcardType t, Boolean recurse) {
2064 return erasure(upperBound(t), recurse);
2065 }
2067 @Override
2068 public Type visitClassType(ClassType t, Boolean recurse) {
2069 Type erased = t.tsym.erasure(Types.this);
2070 if (recurse) {
2071 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
2072 }
2073 return erased;
2074 }
2076 @Override
2077 public Type visitTypeVar(TypeVar t, Boolean recurse) {
2078 return erasure(t.bound, recurse);
2079 }
2081 @Override
2082 public Type visitErrorType(ErrorType t, Boolean recurse) {
2083 return t;
2084 }
2086 @Override
2087 public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
2088 Type erased = erasure(t.underlyingType, recurse);
2089 if (erased.getKind() == TypeKind.ANNOTATED) {
2090 // This can only happen when the underlying type is a
2091 // type variable and the upper bound of it is annotated.
2092 // The annotation on the type variable overrides the one
2093 // on the bound.
2094 erased = ((AnnotatedType)erased).underlyingType;
2095 }
2096 return new AnnotatedType(t.typeAnnotations, erased);
2097 }
2098 };
2100 private Mapping erasureFun = new Mapping ("erasure") {
2101 public Type apply(Type t) { return erasure(t); }
2102 };
2104 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
2105 public Type apply(Type t) { return erasureRecursive(t); }
2106 };
2108 public List<Type> erasure(List<Type> ts) {
2109 return Type.map(ts, erasureFun);
2110 }
2112 public Type erasureRecursive(Type t) {
2113 return erasure(t, true);
2114 }
2116 public List<Type> erasureRecursive(List<Type> ts) {
2117 return Type.map(ts, erasureRecFun);
2118 }
2119 // </editor-fold>
2121 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
2122 /**
2123 * Make a compound type from non-empty list of types
2124 *
2125 * @param bounds the types from which the compound type is formed
2126 * @param supertype is objectType if all bounds are interfaces,
2127 * null otherwise.
2128 */
2129 public Type makeCompoundType(List<Type> bounds) {
2130 return makeCompoundType(bounds, bounds.head.tsym.isInterface());
2131 }
2132 public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
2133 Assert.check(bounds.nonEmpty());
2134 Type firstExplicitBound = bounds.head;
2135 if (allInterfaces) {
2136 bounds = bounds.prepend(syms.objectType);
2137 }
2138 ClassSymbol bc =
2139 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
2140 Type.moreInfo
2141 ? names.fromString(bounds.toString())
2142 : names.empty,
2143 null,
2144 syms.noSymbol);
2145 bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
2146 bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
2147 syms.objectType : // error condition, recover
2148 erasure(firstExplicitBound);
2149 bc.members_field = new Scope(bc);
2150 return bc.type;
2151 }
2153 /**
2154 * A convenience wrapper for {@link #makeCompoundType(List)}; the
2155 * arguments are converted to a list and passed to the other
2156 * method. Note that this might cause a symbol completion.
2157 * Hence, this version of makeCompoundType may not be called
2158 * during a classfile read.
2159 */
2160 public Type makeCompoundType(Type bound1, Type bound2) {
2161 return makeCompoundType(List.of(bound1, bound2));
2162 }
2163 // </editor-fold>
2165 // <editor-fold defaultstate="collapsed" desc="supertype">
2166 public Type supertype(Type t) {
2167 return supertype.visit(t);
2168 }
2169 // where
2170 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2172 public Type visitType(Type t, Void ignored) {
2173 // A note on wildcards: there is no good way to
2174 // determine a supertype for a super bounded wildcard.
2175 return null;
2176 }
2178 @Override
2179 public Type visitClassType(ClassType t, Void ignored) {
2180 if (t.supertype_field == null) {
2181 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2182 // An interface has no superclass; its supertype is Object.
2183 if (t.isInterface())
2184 supertype = ((ClassType)t.tsym.type).supertype_field;
2185 if (t.supertype_field == null) {
2186 List<Type> actuals = classBound(t).allparams();
2187 List<Type> formals = t.tsym.type.allparams();
2188 if (t.hasErasedSupertypes()) {
2189 t.supertype_field = erasureRecursive(supertype);
2190 } else if (formals.nonEmpty()) {
2191 t.supertype_field = subst(supertype, formals, actuals);
2192 }
2193 else {
2194 t.supertype_field = supertype;
2195 }
2196 }
2197 }
2198 return t.supertype_field;
2199 }
2201 /**
2202 * The supertype is always a class type. If the type
2203 * variable's bounds start with a class type, this is also
2204 * the supertype. Otherwise, the supertype is
2205 * java.lang.Object.
2206 */
2207 @Override
2208 public Type visitTypeVar(TypeVar t, Void ignored) {
2209 if (t.bound.tag == TYPEVAR ||
2210 (!t.bound.isCompound() && !t.bound.isInterface())) {
2211 return t.bound;
2212 } else {
2213 return supertype(t.bound);
2214 }
2215 }
2217 @Override
2218 public Type visitArrayType(ArrayType t, Void ignored) {
2219 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2220 return arraySuperType();
2221 else
2222 return new ArrayType(supertype(t.elemtype), t.tsym);
2223 }
2225 @Override
2226 public Type visitErrorType(ErrorType t, Void ignored) {
2227 return t;
2228 }
2229 };
2230 // </editor-fold>
2232 // <editor-fold defaultstate="collapsed" desc="interfaces">
2233 /**
2234 * Return the interfaces implemented by this class.
2235 */
2236 public List<Type> interfaces(Type t) {
2237 return interfaces.visit(t);
2238 }
2239 // where
2240 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2242 public List<Type> visitType(Type t, Void ignored) {
2243 return List.nil();
2244 }
2246 @Override
2247 public List<Type> visitClassType(ClassType t, Void ignored) {
2248 if (t.interfaces_field == null) {
2249 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2250 if (t.interfaces_field == null) {
2251 // If t.interfaces_field is null, then t must
2252 // be a parameterized type (not to be confused
2253 // with a generic type declaration).
2254 // Terminology:
2255 // Parameterized type: List<String>
2256 // Generic type declaration: class List<E> { ... }
2257 // So t corresponds to List<String> and
2258 // t.tsym.type corresponds to List<E>.
2259 // The reason t must be parameterized type is
2260 // that completion will happen as a side
2261 // effect of calling
2262 // ClassSymbol.getInterfaces. Since
2263 // t.interfaces_field is null after
2264 // completion, we can assume that t is not the
2265 // type of a class/interface declaration.
2266 Assert.check(t != t.tsym.type, t);
2267 List<Type> actuals = t.allparams();
2268 List<Type> formals = t.tsym.type.allparams();
2269 if (t.hasErasedSupertypes()) {
2270 t.interfaces_field = erasureRecursive(interfaces);
2271 } else if (formals.nonEmpty()) {
2272 t.interfaces_field =
2273 upperBounds(subst(interfaces, formals, actuals));
2274 }
2275 else {
2276 t.interfaces_field = interfaces;
2277 }
2278 }
2279 }
2280 return t.interfaces_field;
2281 }
2283 @Override
2284 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2285 if (t.bound.isCompound())
2286 return interfaces(t.bound);
2288 if (t.bound.isInterface())
2289 return List.of(t.bound);
2291 return List.nil();
2292 }
2293 };
2295 public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
2296 for (Type i2 : interfaces(origin.type)) {
2297 if (isym == i2.tsym) return true;
2298 }
2299 return false;
2300 }
2301 // </editor-fold>
2303 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2304 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
2306 public boolean isDerivedRaw(Type t) {
2307 Boolean result = isDerivedRawCache.get(t);
2308 if (result == null) {
2309 result = isDerivedRawInternal(t);
2310 isDerivedRawCache.put(t, result);
2311 }
2312 return result;
2313 }
2315 public boolean isDerivedRawInternal(Type t) {
2316 if (t.isErroneous())
2317 return false;
2318 return
2319 t.isRaw() ||
2320 supertype(t) != null && isDerivedRaw(supertype(t)) ||
2321 isDerivedRaw(interfaces(t));
2322 }
2324 public boolean isDerivedRaw(List<Type> ts) {
2325 List<Type> l = ts;
2326 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2327 return l.nonEmpty();
2328 }
2329 // </editor-fold>
2331 // <editor-fold defaultstate="collapsed" desc="setBounds">
2332 /**
2333 * Set the bounds field of the given type variable to reflect a
2334 * (possibly multiple) list of bounds.
2335 * @param t a type variable
2336 * @param bounds the bounds, must be nonempty
2337 * @param supertype is objectType if all bounds are interfaces,
2338 * null otherwise.
2339 */
2340 public void setBounds(TypeVar t, List<Type> bounds) {
2341 setBounds(t, bounds, bounds.head.tsym.isInterface());
2342 }
2344 /**
2345 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
2346 * third parameter is computed directly, as follows: if all
2347 * all bounds are interface types, the computed supertype is Object,
2348 * otherwise the supertype is simply left null (in this case, the supertype
2349 * is assumed to be the head of the bound list passed as second argument).
2350 * Note that this check might cause a symbol completion. Hence, this version of
2351 * setBounds may not be called during a classfile read.
2352 */
2353 public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
2354 t.bound = bounds.tail.isEmpty() ?
2355 bounds.head :
2356 makeCompoundType(bounds, allInterfaces);
2357 t.rank_field = -1;
2358 }
2359 // </editor-fold>
2361 // <editor-fold defaultstate="collapsed" desc="getBounds">
2362 /**
2363 * Return list of bounds of the given type variable.
2364 */
2365 public List<Type> getBounds(TypeVar t) {
2366 if (t.bound.hasTag(NONE))
2367 return List.nil();
2368 else if (t.bound.isErroneous() || !t.bound.isCompound())
2369 return List.of(t.bound);
2370 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2371 return interfaces(t).prepend(supertype(t));
2372 else
2373 // No superclass was given in bounds.
2374 // In this case, supertype is Object, erasure is first interface.
2375 return interfaces(t);
2376 }
2377 // </editor-fold>
2379 // <editor-fold defaultstate="collapsed" desc="classBound">
2380 /**
2381 * If the given type is a (possibly selected) type variable,
2382 * return the bounding class of this type, otherwise return the
2383 * type itself.
2384 */
2385 public Type classBound(Type t) {
2386 return classBound.visit(t);
2387 }
2388 // where
2389 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2391 public Type visitType(Type t, Void ignored) {
2392 return t;
2393 }
2395 @Override
2396 public Type visitClassType(ClassType t, Void ignored) {
2397 Type outer1 = classBound(t.getEnclosingType());
2398 if (outer1 != t.getEnclosingType())
2399 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
2400 else
2401 return t;
2402 }
2404 @Override
2405 public Type visitTypeVar(TypeVar t, Void ignored) {
2406 return classBound(supertype(t));
2407 }
2409 @Override
2410 public Type visitErrorType(ErrorType t, Void ignored) {
2411 return t;
2412 }
2413 };
2414 // </editor-fold>
2416 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
2417 /**
2418 * Returns true iff the first signature is a <em>sub
2419 * signature</em> of the other. This is <b>not</b> an equivalence
2420 * relation.
2421 *
2422 * @jls section 8.4.2.
2423 * @see #overrideEquivalent(Type t, Type s)
2424 * @param t first signature (possibly raw).
2425 * @param s second signature (could be subjected to erasure).
2426 * @return true if t is a sub signature of s.
2427 */
2428 public boolean isSubSignature(Type t, Type s) {
2429 return isSubSignature(t, s, true);
2430 }
2432 public boolean isSubSignature(Type t, Type s, boolean strict) {
2433 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2434 }
2436 /**
2437 * Returns true iff these signatures are related by <em>override
2438 * equivalence</em>. This is the natural extension of
2439 * isSubSignature to an equivalence relation.
2440 *
2441 * @jls section 8.4.2.
2442 * @see #isSubSignature(Type t, Type s)
2443 * @param t a signature (possible raw, could be subjected to
2444 * erasure).
2445 * @param s a signature (possible raw, could be subjected to
2446 * erasure).
2447 * @return true if either argument is a sub signature of the other.
2448 */
2449 public boolean overrideEquivalent(Type t, Type s) {
2450 return hasSameArgs(t, s) ||
2451 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2452 }
2454 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2455 for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
2456 if (msym.overrides(e.sym, origin, Types.this, true)) {
2457 return true;
2458 }
2459 }
2460 return false;
2461 }
2463 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2464 class ImplementationCache {
2466 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2467 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2469 class Entry {
2470 final MethodSymbol cachedImpl;
2471 final Filter<Symbol> implFilter;
2472 final boolean checkResult;
2473 final int prevMark;
2475 public Entry(MethodSymbol cachedImpl,
2476 Filter<Symbol> scopeFilter,
2477 boolean checkResult,
2478 int prevMark) {
2479 this.cachedImpl = cachedImpl;
2480 this.implFilter = scopeFilter;
2481 this.checkResult = checkResult;
2482 this.prevMark = prevMark;
2483 }
2485 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2486 return this.implFilter == scopeFilter &&
2487 this.checkResult == checkResult &&
2488 this.prevMark == mark;
2489 }
2490 }
2492 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2493 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2494 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2495 if (cache == null) {
2496 cache = new HashMap<TypeSymbol, Entry>();
2497 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2498 }
2499 Entry e = cache.get(origin);
2500 CompoundScope members = membersClosure(origin.type, true);
2501 if (e == null ||
2502 !e.matches(implFilter, checkResult, members.getMark())) {
2503 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2504 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2505 return impl;
2506 }
2507 else {
2508 return e.cachedImpl;
2509 }
2510 }
2512 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2513 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2514 while (t.tag == TYPEVAR)
2515 t = t.getUpperBound();
2516 TypeSymbol c = t.tsym;
2517 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2518 e.scope != null;
2519 e = e.next(implFilter)) {
2520 if (e.sym != null &&
2521 e.sym.overrides(ms, origin, Types.this, checkResult))
2522 return (MethodSymbol)e.sym;
2523 }
2524 }
2525 return null;
2526 }
2527 }
2529 private ImplementationCache implCache = new ImplementationCache();
2531 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2532 return implCache.get(ms, origin, checkResult, implFilter);
2533 }
2534 // </editor-fold>
2536 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2537 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2539 private WeakHashMap<TypeSymbol, Entry> _map =
2540 new WeakHashMap<TypeSymbol, Entry>();
2542 class Entry {
2543 final boolean skipInterfaces;
2544 final CompoundScope compoundScope;
2546 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2547 this.skipInterfaces = skipInterfaces;
2548 this.compoundScope = compoundScope;
2549 }
2551 boolean matches(boolean skipInterfaces) {
2552 return this.skipInterfaces == skipInterfaces;
2553 }
2554 }
2556 List<TypeSymbol> seenTypes = List.nil();
2558 /** members closure visitor methods **/
2560 public CompoundScope visitType(Type t, Boolean skipInterface) {
2561 return null;
2562 }
2564 @Override
2565 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2566 if (seenTypes.contains(t.tsym)) {
2567 //this is possible when an interface is implemented in multiple
2568 //superclasses, or when a classs hierarchy is circular - in such
2569 //cases we don't need to recurse (empty scope is returned)
2570 return new CompoundScope(t.tsym);
2571 }
2572 try {
2573 seenTypes = seenTypes.prepend(t.tsym);
2574 ClassSymbol csym = (ClassSymbol)t.tsym;
2575 Entry e = _map.get(csym);
2576 if (e == null || !e.matches(skipInterface)) {
2577 CompoundScope membersClosure = new CompoundScope(csym);
2578 if (!skipInterface) {
2579 for (Type i : interfaces(t)) {
2580 membersClosure.addSubScope(visit(i, skipInterface));
2581 }
2582 }
2583 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2584 membersClosure.addSubScope(csym.members());
2585 e = new Entry(skipInterface, membersClosure);
2586 _map.put(csym, e);
2587 }
2588 return e.compoundScope;
2589 }
2590 finally {
2591 seenTypes = seenTypes.tail;
2592 }
2593 }
2595 @Override
2596 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2597 return visit(t.getUpperBound(), skipInterface);
2598 }
2599 }
2601 private MembersClosureCache membersCache = new MembersClosureCache();
2603 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2604 return membersCache.visit(site, skipInterface);
2605 }
2606 // </editor-fold>
2609 //where
2610 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
2611 Filter<Symbol> filter = new MethodFilter(ms, site);
2612 List<MethodSymbol> candidates = List.nil();
2613 for (Symbol s : membersClosure(site, false).getElements(filter)) {
2614 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
2615 return List.of((MethodSymbol)s);
2616 } else if (!candidates.contains(s)) {
2617 candidates = candidates.prepend((MethodSymbol)s);
2618 }
2619 }
2620 return prune(candidates);
2621 }
2623 public List<MethodSymbol> prune(List<MethodSymbol> methods) {
2624 ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
2625 for (MethodSymbol m1 : methods) {
2626 boolean isMin_m1 = true;
2627 for (MethodSymbol m2 : methods) {
2628 if (m1 == m2) continue;
2629 if (m2.owner != m1.owner &&
2630 asSuper(m2.owner.type, m1.owner) != null) {
2631 isMin_m1 = false;
2632 break;
2633 }
2634 }
2635 if (isMin_m1)
2636 methodsMin.append(m1);
2637 }
2638 return methodsMin.toList();
2639 }
2640 // where
2641 private class MethodFilter implements Filter<Symbol> {
2643 Symbol msym;
2644 Type site;
2646 MethodFilter(Symbol msym, Type site) {
2647 this.msym = msym;
2648 this.site = site;
2649 }
2651 public boolean accepts(Symbol s) {
2652 return s.kind == Kinds.MTH &&
2653 s.name == msym.name &&
2654 s.isInheritedIn(site.tsym, Types.this) &&
2655 overrideEquivalent(memberType(site, s), memberType(site, msym));
2656 }
2657 };
2658 // </editor-fold>
2660 /**
2661 * Does t have the same arguments as s? It is assumed that both
2662 * types are (possibly polymorphic) method types. Monomorphic
2663 * method types "have the same arguments", if their argument lists
2664 * are equal. Polymorphic method types "have the same arguments",
2665 * if they have the same arguments after renaming all type
2666 * variables of one to corresponding type variables in the other,
2667 * where correspondence is by position in the type parameter list.
2668 */
2669 public boolean hasSameArgs(Type t, Type s) {
2670 return hasSameArgs(t, s, true);
2671 }
2673 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2674 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2675 }
2677 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2678 return hasSameArgs.visit(t, s);
2679 }
2680 // where
2681 private class HasSameArgs extends TypeRelation {
2683 boolean strict;
2685 public HasSameArgs(boolean strict) {
2686 this.strict = strict;
2687 }
2689 public Boolean visitType(Type t, Type s) {
2690 throw new AssertionError();
2691 }
2693 @Override
2694 public Boolean visitMethodType(MethodType t, Type s) {
2695 return s.tag == METHOD
2696 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2697 }
2699 @Override
2700 public Boolean visitForAll(ForAll t, Type s) {
2701 if (s.tag != FORALL)
2702 return strict ? false : visitMethodType(t.asMethodType(), s);
2704 ForAll forAll = (ForAll)s;
2705 return hasSameBounds(t, forAll)
2706 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2707 }
2709 @Override
2710 public Boolean visitErrorType(ErrorType t, Type s) {
2711 return false;
2712 }
2713 };
2715 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2716 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2718 // </editor-fold>
2720 // <editor-fold defaultstate="collapsed" desc="subst">
2721 public List<Type> subst(List<Type> ts,
2722 List<Type> from,
2723 List<Type> to) {
2724 return new Subst(from, to).subst(ts);
2725 }
2727 /**
2728 * Substitute all occurrences of a type in `from' with the
2729 * corresponding type in `to' in 't'. Match lists `from' and `to'
2730 * from the right: If lists have different length, discard leading
2731 * elements of the longer list.
2732 */
2733 public Type subst(Type t, List<Type> from, List<Type> to) {
2734 return new Subst(from, to).subst(t);
2735 }
2737 private class Subst extends UnaryVisitor<Type> {
2738 List<Type> from;
2739 List<Type> to;
2741 public Subst(List<Type> from, List<Type> to) {
2742 int fromLength = from.length();
2743 int toLength = to.length();
2744 while (fromLength > toLength) {
2745 fromLength--;
2746 from = from.tail;
2747 }
2748 while (fromLength < toLength) {
2749 toLength--;
2750 to = to.tail;
2751 }
2752 this.from = from;
2753 this.to = to;
2754 }
2756 Type subst(Type t) {
2757 if (from.tail == null)
2758 return t;
2759 else
2760 return visit(t);
2761 }
2763 List<Type> subst(List<Type> ts) {
2764 if (from.tail == null)
2765 return ts;
2766 boolean wild = false;
2767 if (ts.nonEmpty() && from.nonEmpty()) {
2768 Type head1 = subst(ts.head);
2769 List<Type> tail1 = subst(ts.tail);
2770 if (head1 != ts.head || tail1 != ts.tail)
2771 return tail1.prepend(head1);
2772 }
2773 return ts;
2774 }
2776 public Type visitType(Type t, Void ignored) {
2777 return t;
2778 }
2780 @Override
2781 public Type visitMethodType(MethodType t, Void ignored) {
2782 List<Type> argtypes = subst(t.argtypes);
2783 Type restype = subst(t.restype);
2784 List<Type> thrown = subst(t.thrown);
2785 if (argtypes == t.argtypes &&
2786 restype == t.restype &&
2787 thrown == t.thrown)
2788 return t;
2789 else
2790 return new MethodType(argtypes, restype, thrown, t.tsym);
2791 }
2793 @Override
2794 public Type visitTypeVar(TypeVar t, Void ignored) {
2795 for (List<Type> from = this.from, to = this.to;
2796 from.nonEmpty();
2797 from = from.tail, to = to.tail) {
2798 if (t == from.head) {
2799 return to.head.withTypeVar(t);
2800 }
2801 }
2802 return t;
2803 }
2805 @Override
2806 public Type visitClassType(ClassType t, Void ignored) {
2807 if (!t.isCompound()) {
2808 List<Type> typarams = t.getTypeArguments();
2809 List<Type> typarams1 = subst(typarams);
2810 Type outer = t.getEnclosingType();
2811 Type outer1 = subst(outer);
2812 if (typarams1 == typarams && outer1 == outer)
2813 return t;
2814 else
2815 return new ClassType(outer1, typarams1, t.tsym);
2816 } else {
2817 Type st = subst(supertype(t));
2818 List<Type> is = upperBounds(subst(interfaces(t)));
2819 if (st == supertype(t) && is == interfaces(t))
2820 return t;
2821 else
2822 return makeCompoundType(is.prepend(st));
2823 }
2824 }
2826 @Override
2827 public Type visitWildcardType(WildcardType t, Void ignored) {
2828 Type bound = t.type;
2829 if (t.kind != BoundKind.UNBOUND)
2830 bound = subst(bound);
2831 if (bound == t.type) {
2832 return t;
2833 } else {
2834 if (t.isExtendsBound() && bound.isExtendsBound())
2835 bound = upperBound(bound);
2836 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2837 }
2838 }
2840 @Override
2841 public Type visitArrayType(ArrayType t, Void ignored) {
2842 Type elemtype = subst(t.elemtype);
2843 if (elemtype == t.elemtype)
2844 return t;
2845 else
2846 return new ArrayType(upperBound(elemtype), t.tsym);
2847 }
2849 @Override
2850 public Type visitForAll(ForAll t, Void ignored) {
2851 if (Type.containsAny(to, t.tvars)) {
2852 //perform alpha-renaming of free-variables in 't'
2853 //if 'to' types contain variables that are free in 't'
2854 List<Type> freevars = newInstances(t.tvars);
2855 t = new ForAll(freevars,
2856 Types.this.subst(t.qtype, t.tvars, freevars));
2857 }
2858 List<Type> tvars1 = substBounds(t.tvars, from, to);
2859 Type qtype1 = subst(t.qtype);
2860 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2861 return t;
2862 } else if (tvars1 == t.tvars) {
2863 return new ForAll(tvars1, qtype1);
2864 } else {
2865 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2866 }
2867 }
2869 @Override
2870 public Type visitErrorType(ErrorType t, Void ignored) {
2871 return t;
2872 }
2873 }
2875 public List<Type> substBounds(List<Type> tvars,
2876 List<Type> from,
2877 List<Type> to) {
2878 if (tvars.isEmpty())
2879 return tvars;
2880 ListBuffer<Type> newBoundsBuf = lb();
2881 boolean changed = false;
2882 // calculate new bounds
2883 for (Type t : tvars) {
2884 TypeVar tv = (TypeVar) t;
2885 Type bound = subst(tv.bound, from, to);
2886 if (bound != tv.bound)
2887 changed = true;
2888 newBoundsBuf.append(bound);
2889 }
2890 if (!changed)
2891 return tvars;
2892 ListBuffer<Type> newTvars = lb();
2893 // create new type variables without bounds
2894 for (Type t : tvars) {
2895 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2896 }
2897 // the new bounds should use the new type variables in place
2898 // of the old
2899 List<Type> newBounds = newBoundsBuf.toList();
2900 from = tvars;
2901 to = newTvars.toList();
2902 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2903 newBounds.head = subst(newBounds.head, from, to);
2904 }
2905 newBounds = newBoundsBuf.toList();
2906 // set the bounds of new type variables to the new bounds
2907 for (Type t : newTvars.toList()) {
2908 TypeVar tv = (TypeVar) t;
2909 tv.bound = newBounds.head;
2910 newBounds = newBounds.tail;
2911 }
2912 return newTvars.toList();
2913 }
2915 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2916 Type bound1 = subst(t.bound, from, to);
2917 if (bound1 == t.bound)
2918 return t;
2919 else {
2920 // create new type variable without bounds
2921 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2922 // the new bound should use the new type variable in place
2923 // of the old
2924 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2925 return tv;
2926 }
2927 }
2928 // </editor-fold>
2930 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2931 /**
2932 * Does t have the same bounds for quantified variables as s?
2933 */
2934 boolean hasSameBounds(ForAll t, ForAll s) {
2935 List<Type> l1 = t.tvars;
2936 List<Type> l2 = s.tvars;
2937 while (l1.nonEmpty() && l2.nonEmpty() &&
2938 isSameType(l1.head.getUpperBound(),
2939 subst(l2.head.getUpperBound(),
2940 s.tvars,
2941 t.tvars))) {
2942 l1 = l1.tail;
2943 l2 = l2.tail;
2944 }
2945 return l1.isEmpty() && l2.isEmpty();
2946 }
2947 // </editor-fold>
2949 // <editor-fold defaultstate="collapsed" desc="newInstances">
2950 /** Create new vector of type variables from list of variables
2951 * changing all recursive bounds from old to new list.
2952 */
2953 public List<Type> newInstances(List<Type> tvars) {
2954 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2955 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2956 TypeVar tv = (TypeVar) l.head;
2957 tv.bound = subst(tv.bound, tvars, tvars1);
2958 }
2959 return tvars1;
2960 }
2961 private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
2962 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2963 };
2964 // </editor-fold>
2966 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2967 return original.accept(methodWithParameters, newParams);
2968 }
2969 // where
2970 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2971 public Type visitType(Type t, List<Type> newParams) {
2972 throw new IllegalArgumentException("Not a method type: " + t);
2973 }
2974 public Type visitMethodType(MethodType t, List<Type> newParams) {
2975 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2976 }
2977 public Type visitForAll(ForAll t, List<Type> newParams) {
2978 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2979 }
2980 };
2982 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2983 return original.accept(methodWithThrown, newThrown);
2984 }
2985 // where
2986 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2987 public Type visitType(Type t, List<Type> newThrown) {
2988 throw new IllegalArgumentException("Not a method type: " + t);
2989 }
2990 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2991 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2992 }
2993 public Type visitForAll(ForAll t, List<Type> newThrown) {
2994 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2995 }
2996 };
2998 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2999 return original.accept(methodWithReturn, newReturn);
3000 }
3001 // where
3002 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3003 public Type visitType(Type t, Type newReturn) {
3004 throw new IllegalArgumentException("Not a method type: " + t);
3005 }
3006 public Type visitMethodType(MethodType t, Type newReturn) {
3007 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
3008 }
3009 public Type visitForAll(ForAll t, Type newReturn) {
3010 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
3011 }
3012 };
3014 // <editor-fold defaultstate="collapsed" desc="createErrorType">
3015 public Type createErrorType(Type originalType) {
3016 return new ErrorType(originalType, syms.errSymbol);
3017 }
3019 public Type createErrorType(ClassSymbol c, Type originalType) {
3020 return new ErrorType(c, originalType);
3021 }
3023 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3024 return new ErrorType(name, container, originalType);
3025 }
3026 // </editor-fold>
3028 // <editor-fold defaultstate="collapsed" desc="rank">
3029 /**
3030 * The rank of a class is the length of the longest path between
3031 * the class and java.lang.Object in the class inheritance
3032 * graph. Undefined for all but reference types.
3033 */
3034 public int rank(Type t) {
3035 t = t.unannotatedType();
3036 switch(t.tag) {
3037 case CLASS: {
3038 ClassType cls = (ClassType)t;
3039 if (cls.rank_field < 0) {
3040 Name fullname = cls.tsym.getQualifiedName();
3041 if (fullname == names.java_lang_Object)
3042 cls.rank_field = 0;
3043 else {
3044 int r = rank(supertype(cls));
3045 for (List<Type> l = interfaces(cls);
3046 l.nonEmpty();
3047 l = l.tail) {
3048 if (rank(l.head) > r)
3049 r = rank(l.head);
3050 }
3051 cls.rank_field = r + 1;
3052 }
3053 }
3054 return cls.rank_field;
3055 }
3056 case TYPEVAR: {
3057 TypeVar tvar = (TypeVar)t;
3058 if (tvar.rank_field < 0) {
3059 int r = rank(supertype(tvar));
3060 for (List<Type> l = interfaces(tvar);
3061 l.nonEmpty();
3062 l = l.tail) {
3063 if (rank(l.head) > r) r = rank(l.head);
3064 }
3065 tvar.rank_field = r + 1;
3066 }
3067 return tvar.rank_field;
3068 }
3069 case ERROR:
3070 return 0;
3071 default:
3072 throw new AssertionError();
3073 }
3074 }
3075 // </editor-fold>
3077 /**
3078 * Helper method for generating a string representation of a given type
3079 * accordingly to a given locale
3080 */
3081 public String toString(Type t, Locale locale) {
3082 return Printer.createStandardPrinter(messages).visit(t, locale);
3083 }
3085 /**
3086 * Helper method for generating a string representation of a given type
3087 * accordingly to a given locale
3088 */
3089 public String toString(Symbol t, Locale locale) {
3090 return Printer.createStandardPrinter(messages).visit(t, locale);
3091 }
3093 // <editor-fold defaultstate="collapsed" desc="toString">
3094 /**
3095 * This toString is slightly more descriptive than the one on Type.
3096 *
3097 * @deprecated Types.toString(Type t, Locale l) provides better support
3098 * for localization
3099 */
3100 @Deprecated
3101 public String toString(Type t) {
3102 if (t.tag == FORALL) {
3103 ForAll forAll = (ForAll)t;
3104 return typaramsString(forAll.tvars) + forAll.qtype;
3105 }
3106 return "" + t;
3107 }
3108 // where
3109 private String typaramsString(List<Type> tvars) {
3110 StringBuilder s = new StringBuilder();
3111 s.append('<');
3112 boolean first = true;
3113 for (Type t : tvars) {
3114 if (!first) s.append(", ");
3115 first = false;
3116 appendTyparamString(((TypeVar)t), s);
3117 }
3118 s.append('>');
3119 return s.toString();
3120 }
3121 private void appendTyparamString(TypeVar t, StringBuilder buf) {
3122 buf.append(t);
3123 if (t.bound == null ||
3124 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
3125 return;
3126 buf.append(" extends "); // Java syntax; no need for i18n
3127 Type bound = t.bound;
3128 if (!bound.isCompound()) {
3129 buf.append(bound);
3130 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3131 buf.append(supertype(t));
3132 for (Type intf : interfaces(t)) {
3133 buf.append('&');
3134 buf.append(intf);
3135 }
3136 } else {
3137 // No superclass was given in bounds.
3138 // In this case, supertype is Object, erasure is first interface.
3139 boolean first = true;
3140 for (Type intf : interfaces(t)) {
3141 if (!first) buf.append('&');
3142 first = false;
3143 buf.append(intf);
3144 }
3145 }
3146 }
3147 // </editor-fold>
3149 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3150 /**
3151 * A cache for closures.
3152 *
3153 * <p>A closure is a list of all the supertypes and interfaces of
3154 * a class or interface type, ordered by ClassSymbol.precedes
3155 * (that is, subclasses come first, arbitrary but fixed
3156 * otherwise).
3157 */
3158 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
3160 /**
3161 * Returns the closure of a class or interface type.
3162 */
3163 public List<Type> closure(Type t) {
3164 List<Type> cl = closureCache.get(t);
3165 if (cl == null) {
3166 Type st = supertype(t);
3167 if (!t.isCompound()) {
3168 if (st.tag == CLASS) {
3169 cl = insert(closure(st), t);
3170 } else if (st.tag == TYPEVAR) {
3171 cl = closure(st).prepend(t);
3172 } else {
3173 cl = List.of(t);
3174 }
3175 } else {
3176 cl = closure(supertype(t));
3177 }
3178 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3179 cl = union(cl, closure(l.head));
3180 closureCache.put(t, cl);
3181 }
3182 return cl;
3183 }
3185 /**
3186 * Insert a type in a closure
3187 */
3188 public List<Type> insert(List<Type> cl, Type t) {
3189 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
3190 return cl.prepend(t);
3191 } else if (cl.head.tsym.precedes(t.tsym, this)) {
3192 return insert(cl.tail, t).prepend(cl.head);
3193 } else {
3194 return cl;
3195 }
3196 }
3198 /**
3199 * Form the union of two closures
3200 */
3201 public List<Type> union(List<Type> cl1, List<Type> cl2) {
3202 if (cl1.isEmpty()) {
3203 return cl2;
3204 } else if (cl2.isEmpty()) {
3205 return cl1;
3206 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3207 return union(cl1.tail, cl2).prepend(cl1.head);
3208 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3209 return union(cl1, cl2.tail).prepend(cl2.head);
3210 } else {
3211 return union(cl1.tail, cl2.tail).prepend(cl1.head);
3212 }
3213 }
3215 /**
3216 * Intersect two closures
3217 */
3218 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3219 if (cl1 == cl2)
3220 return cl1;
3221 if (cl1.isEmpty() || cl2.isEmpty())
3222 return List.nil();
3223 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3224 return intersect(cl1.tail, cl2);
3225 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3226 return intersect(cl1, cl2.tail);
3227 if (isSameType(cl1.head, cl2.head))
3228 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3229 if (cl1.head.tsym == cl2.head.tsym &&
3230 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
3231 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3232 Type merge = merge(cl1.head,cl2.head);
3233 return intersect(cl1.tail, cl2.tail).prepend(merge);
3234 }
3235 if (cl1.head.isRaw() || cl2.head.isRaw())
3236 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3237 }
3238 return intersect(cl1.tail, cl2.tail);
3239 }
3240 // where
3241 class TypePair {
3242 final Type t1;
3243 final Type t2;
3244 TypePair(Type t1, Type t2) {
3245 this.t1 = t1;
3246 this.t2 = t2;
3247 }
3248 @Override
3249 public int hashCode() {
3250 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3251 }
3252 @Override
3253 public boolean equals(Object obj) {
3254 if (!(obj instanceof TypePair))
3255 return false;
3256 TypePair typePair = (TypePair)obj;
3257 return isSameType(t1, typePair.t1)
3258 && isSameType(t2, typePair.t2);
3259 }
3260 }
3261 Set<TypePair> mergeCache = new HashSet<TypePair>();
3262 private Type merge(Type c1, Type c2) {
3263 ClassType class1 = (ClassType) c1;
3264 List<Type> act1 = class1.getTypeArguments();
3265 ClassType class2 = (ClassType) c2;
3266 List<Type> act2 = class2.getTypeArguments();
3267 ListBuffer<Type> merged = new ListBuffer<Type>();
3268 List<Type> typarams = class1.tsym.type.getTypeArguments();
3270 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3271 if (containsType(act1.head, act2.head)) {
3272 merged.append(act1.head);
3273 } else if (containsType(act2.head, act1.head)) {
3274 merged.append(act2.head);
3275 } else {
3276 TypePair pair = new TypePair(c1, c2);
3277 Type m;
3278 if (mergeCache.add(pair)) {
3279 m = new WildcardType(lub(upperBound(act1.head),
3280 upperBound(act2.head)),
3281 BoundKind.EXTENDS,
3282 syms.boundClass);
3283 mergeCache.remove(pair);
3284 } else {
3285 m = new WildcardType(syms.objectType,
3286 BoundKind.UNBOUND,
3287 syms.boundClass);
3288 }
3289 merged.append(m.withTypeVar(typarams.head));
3290 }
3291 act1 = act1.tail;
3292 act2 = act2.tail;
3293 typarams = typarams.tail;
3294 }
3295 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3296 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
3297 }
3299 /**
3300 * Return the minimum type of a closure, a compound type if no
3301 * unique minimum exists.
3302 */
3303 private Type compoundMin(List<Type> cl) {
3304 if (cl.isEmpty()) return syms.objectType;
3305 List<Type> compound = closureMin(cl);
3306 if (compound.isEmpty())
3307 return null;
3308 else if (compound.tail.isEmpty())
3309 return compound.head;
3310 else
3311 return makeCompoundType(compound);
3312 }
3314 /**
3315 * Return the minimum types of a closure, suitable for computing
3316 * compoundMin or glb.
3317 */
3318 private List<Type> closureMin(List<Type> cl) {
3319 ListBuffer<Type> classes = lb();
3320 ListBuffer<Type> interfaces = lb();
3321 while (!cl.isEmpty()) {
3322 Type current = cl.head;
3323 if (current.isInterface())
3324 interfaces.append(current);
3325 else
3326 classes.append(current);
3327 ListBuffer<Type> candidates = lb();
3328 for (Type t : cl.tail) {
3329 if (!isSubtypeNoCapture(current, t))
3330 candidates.append(t);
3331 }
3332 cl = candidates.toList();
3333 }
3334 return classes.appendList(interfaces).toList();
3335 }
3337 /**
3338 * Return the least upper bound of pair of types. if the lub does
3339 * not exist return null.
3340 */
3341 public Type lub(Type t1, Type t2) {
3342 return lub(List.of(t1, t2));
3343 }
3345 /**
3346 * Return the least upper bound (lub) of set of types. If the lub
3347 * does not exist return the type of null (bottom).
3348 */
3349 public Type lub(List<Type> ts) {
3350 final int ARRAY_BOUND = 1;
3351 final int CLASS_BOUND = 2;
3352 int boundkind = 0;
3353 for (Type t : ts) {
3354 switch (t.tag) {
3355 case CLASS:
3356 boundkind |= CLASS_BOUND;
3357 break;
3358 case ARRAY:
3359 boundkind |= ARRAY_BOUND;
3360 break;
3361 case TYPEVAR:
3362 do {
3363 t = t.getUpperBound();
3364 } while (t.tag == TYPEVAR);
3365 if (t.tag == ARRAY) {
3366 boundkind |= ARRAY_BOUND;
3367 } else {
3368 boundkind |= CLASS_BOUND;
3369 }
3370 break;
3371 default:
3372 if (t.isPrimitive())
3373 return syms.errType;
3374 }
3375 }
3376 switch (boundkind) {
3377 case 0:
3378 return syms.botType;
3380 case ARRAY_BOUND:
3381 // calculate lub(A[], B[])
3382 List<Type> elements = Type.map(ts, elemTypeFun);
3383 for (Type t : elements) {
3384 if (t.isPrimitive()) {
3385 // if a primitive type is found, then return
3386 // arraySuperType unless all the types are the
3387 // same
3388 Type first = ts.head;
3389 for (Type s : ts.tail) {
3390 if (!isSameType(first, s)) {
3391 // lub(int[], B[]) is Cloneable & Serializable
3392 return arraySuperType();
3393 }
3394 }
3395 // all the array types are the same, return one
3396 // lub(int[], int[]) is int[]
3397 return first;
3398 }
3399 }
3400 // lub(A[], B[]) is lub(A, B)[]
3401 return new ArrayType(lub(elements), syms.arrayClass);
3403 case CLASS_BOUND:
3404 // calculate lub(A, B)
3405 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
3406 ts = ts.tail;
3407 Assert.check(!ts.isEmpty());
3408 //step 1 - compute erased candidate set (EC)
3409 List<Type> cl = erasedSupertypes(ts.head);
3410 for (Type t : ts.tail) {
3411 if (t.tag == CLASS || t.tag == TYPEVAR)
3412 cl = intersect(cl, erasedSupertypes(t));
3413 }
3414 //step 2 - compute minimal erased candidate set (MEC)
3415 List<Type> mec = closureMin(cl);
3416 //step 3 - for each element G in MEC, compute lci(Inv(G))
3417 List<Type> candidates = List.nil();
3418 for (Type erasedSupertype : mec) {
3419 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
3420 for (Type t : ts) {
3421 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
3422 }
3423 candidates = candidates.appendList(lci);
3424 }
3425 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3426 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3427 return compoundMin(candidates);
3429 default:
3430 // calculate lub(A, B[])
3431 List<Type> classes = List.of(arraySuperType());
3432 for (Type t : ts) {
3433 if (t.tag != ARRAY) // Filter out any arrays
3434 classes = classes.prepend(t);
3435 }
3436 // lub(A, B[]) is lub(A, arraySuperType)
3437 return lub(classes);
3438 }
3439 }
3440 // where
3441 List<Type> erasedSupertypes(Type t) {
3442 ListBuffer<Type> buf = lb();
3443 for (Type sup : closure(t)) {
3444 if (sup.tag == TYPEVAR) {
3445 buf.append(sup);
3446 } else {
3447 buf.append(erasure(sup));
3448 }
3449 }
3450 return buf.toList();
3451 }
3453 private Type arraySuperType = null;
3454 private Type arraySuperType() {
3455 // initialized lazily to avoid problems during compiler startup
3456 if (arraySuperType == null) {
3457 synchronized (this) {
3458 if (arraySuperType == null) {
3459 // JLS 10.8: all arrays implement Cloneable and Serializable.
3460 arraySuperType = makeCompoundType(List.of(syms.serializableType,
3461 syms.cloneableType), true);
3462 }
3463 }
3464 }
3465 return arraySuperType;
3466 }
3467 // </editor-fold>
3469 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3470 public Type glb(List<Type> ts) {
3471 Type t1 = ts.head;
3472 for (Type t2 : ts.tail) {
3473 if (t1.isErroneous())
3474 return t1;
3475 t1 = glb(t1, t2);
3476 }
3477 return t1;
3478 }
3479 //where
3480 public Type glb(Type t, Type s) {
3481 if (s == null)
3482 return t;
3483 else if (t.isPrimitive() || s.isPrimitive())
3484 return syms.errType;
3485 else if (isSubtypeNoCapture(t, s))
3486 return t;
3487 else if (isSubtypeNoCapture(s, t))
3488 return s;
3490 List<Type> closure = union(closure(t), closure(s));
3491 List<Type> bounds = closureMin(closure);
3493 if (bounds.isEmpty()) { // length == 0
3494 return syms.objectType;
3495 } else if (bounds.tail.isEmpty()) { // length == 1
3496 return bounds.head;
3497 } else { // length > 1
3498 int classCount = 0;
3499 for (Type bound : bounds)
3500 if (!bound.isInterface())
3501 classCount++;
3502 if (classCount > 1)
3503 return createErrorType(t);
3504 }
3505 return makeCompoundType(bounds);
3506 }
3507 // </editor-fold>
3509 // <editor-fold defaultstate="collapsed" desc="hashCode">
3510 /**
3511 * Compute a hash code on a type.
3512 */
3513 public int hashCode(Type t) {
3514 return hashCode.visit(t);
3515 }
3516 // where
3517 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3519 public Integer visitType(Type t, Void ignored) {
3520 return t.tag.ordinal();
3521 }
3523 @Override
3524 public Integer visitClassType(ClassType t, Void ignored) {
3525 int result = visit(t.getEnclosingType());
3526 result *= 127;
3527 result += t.tsym.flatName().hashCode();
3528 for (Type s : t.getTypeArguments()) {
3529 result *= 127;
3530 result += visit(s);
3531 }
3532 return result;
3533 }
3535 @Override
3536 public Integer visitMethodType(MethodType t, Void ignored) {
3537 int h = METHOD.ordinal();
3538 for (List<Type> thisargs = t.argtypes;
3539 thisargs.tail != null;
3540 thisargs = thisargs.tail)
3541 h = (h << 5) + visit(thisargs.head);
3542 return (h << 5) + visit(t.restype);
3543 }
3545 @Override
3546 public Integer visitWildcardType(WildcardType t, Void ignored) {
3547 int result = t.kind.hashCode();
3548 if (t.type != null) {
3549 result *= 127;
3550 result += visit(t.type);
3551 }
3552 return result;
3553 }
3555 @Override
3556 public Integer visitArrayType(ArrayType t, Void ignored) {
3557 return visit(t.elemtype) + 12;
3558 }
3560 @Override
3561 public Integer visitTypeVar(TypeVar t, Void ignored) {
3562 return System.identityHashCode(t.tsym);
3563 }
3565 @Override
3566 public Integer visitUndetVar(UndetVar t, Void ignored) {
3567 return System.identityHashCode(t);
3568 }
3570 @Override
3571 public Integer visitErrorType(ErrorType t, Void ignored) {
3572 return 0;
3573 }
3574 };
3575 // </editor-fold>
3577 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3578 /**
3579 * Does t have a result that is a subtype of the result type of s,
3580 * suitable for covariant returns? It is assumed that both types
3581 * are (possibly polymorphic) method types. Monomorphic method
3582 * types are handled in the obvious way. Polymorphic method types
3583 * require renaming all type variables of one to corresponding
3584 * type variables in the other, where correspondence is by
3585 * position in the type parameter list. */
3586 public boolean resultSubtype(Type t, Type s, Warner warner) {
3587 List<Type> tvars = t.getTypeArguments();
3588 List<Type> svars = s.getTypeArguments();
3589 Type tres = t.getReturnType();
3590 Type sres = subst(s.getReturnType(), svars, tvars);
3591 return covariantReturnType(tres, sres, warner);
3592 }
3594 /**
3595 * Return-Type-Substitutable.
3596 * @jls section 8.4.5
3597 */
3598 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3599 if (hasSameArgs(r1, r2))
3600 return resultSubtype(r1, r2, noWarnings);
3601 else
3602 return covariantReturnType(r1.getReturnType(),
3603 erasure(r2.getReturnType()),
3604 noWarnings);
3605 }
3607 public boolean returnTypeSubstitutable(Type r1,
3608 Type r2, Type r2res,
3609 Warner warner) {
3610 if (isSameType(r1.getReturnType(), r2res))
3611 return true;
3612 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3613 return false;
3615 if (hasSameArgs(r1, r2))
3616 return covariantReturnType(r1.getReturnType(), r2res, warner);
3617 if (!allowCovariantReturns)
3618 return false;
3619 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3620 return true;
3621 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3622 return false;
3623 warner.warn(LintCategory.UNCHECKED);
3624 return true;
3625 }
3627 /**
3628 * Is t an appropriate return type in an overrider for a
3629 * method that returns s?
3630 */
3631 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3632 return
3633 isSameType(t, s) ||
3634 allowCovariantReturns &&
3635 !t.isPrimitive() &&
3636 !s.isPrimitive() &&
3637 isAssignable(t, s, warner);
3638 }
3639 // </editor-fold>
3641 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3642 /**
3643 * Return the class that boxes the given primitive.
3644 */
3645 public ClassSymbol boxedClass(Type t) {
3646 return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
3647 }
3649 /**
3650 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3651 */
3652 public Type boxedTypeOrType(Type t) {
3653 return t.isPrimitive() ?
3654 boxedClass(t).type :
3655 t;
3656 }
3658 /**
3659 * Return the primitive type corresponding to a boxed type.
3660 */
3661 public Type unboxedType(Type t) {
3662 if (allowBoxing) {
3663 for (int i=0; i<syms.boxedName.length; i++) {
3664 Name box = syms.boxedName[i];
3665 if (box != null &&
3666 asSuper(t, reader.enterClass(box)) != null)
3667 return syms.typeOfTag[i];
3668 }
3669 }
3670 return Type.noType;
3671 }
3673 /**
3674 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3675 */
3676 public Type unboxedTypeOrType(Type t) {
3677 Type unboxedType = unboxedType(t);
3678 return unboxedType.tag == NONE ? t : unboxedType;
3679 }
3680 // </editor-fold>
3682 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3683 /*
3684 * JLS 5.1.10 Capture Conversion:
3685 *
3686 * Let G name a generic type declaration with n formal type
3687 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3688 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3689 * where, for 1 <= i <= n:
3690 *
3691 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3692 * Si is a fresh type variable whose upper bound is
3693 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3694 * type.
3695 *
3696 * + If Ti is a wildcard type argument of the form ? extends Bi,
3697 * then Si is a fresh type variable whose upper bound is
3698 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3699 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3700 * a compile-time error if for any two classes (not interfaces)
3701 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3702 *
3703 * + If Ti is a wildcard type argument of the form ? super Bi,
3704 * then Si is a fresh type variable whose upper bound is
3705 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3706 *
3707 * + Otherwise, Si = Ti.
3708 *
3709 * Capture conversion on any type other than a parameterized type
3710 * (4.5) acts as an identity conversion (5.1.1). Capture
3711 * conversions never require a special action at run time and
3712 * therefore never throw an exception at run time.
3713 *
3714 * Capture conversion is not applied recursively.
3715 */
3716 /**
3717 * Capture conversion as specified by the JLS.
3718 */
3720 public List<Type> capture(List<Type> ts) {
3721 List<Type> buf = List.nil();
3722 for (Type t : ts) {
3723 buf = buf.prepend(capture(t));
3724 }
3725 return buf.reverse();
3726 }
3727 public Type capture(Type t) {
3728 if (t.tag != CLASS)
3729 return t;
3730 if (t.getEnclosingType() != Type.noType) {
3731 Type capturedEncl = capture(t.getEnclosingType());
3732 if (capturedEncl != t.getEnclosingType()) {
3733 Type type1 = memberType(capturedEncl, t.tsym);
3734 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3735 }
3736 }
3737 t = t.unannotatedType();
3738 ClassType cls = (ClassType)t;
3739 if (cls.isRaw() || !cls.isParameterized())
3740 return cls;
3742 ClassType G = (ClassType)cls.asElement().asType();
3743 List<Type> A = G.getTypeArguments();
3744 List<Type> T = cls.getTypeArguments();
3745 List<Type> S = freshTypeVariables(T);
3747 List<Type> currentA = A;
3748 List<Type> currentT = T;
3749 List<Type> currentS = S;
3750 boolean captured = false;
3751 while (!currentA.isEmpty() &&
3752 !currentT.isEmpty() &&
3753 !currentS.isEmpty()) {
3754 if (currentS.head != currentT.head) {
3755 captured = true;
3756 WildcardType Ti = (WildcardType)currentT.head;
3757 Type Ui = currentA.head.getUpperBound();
3758 CapturedType Si = (CapturedType)currentS.head;
3759 if (Ui == null)
3760 Ui = syms.objectType;
3761 switch (Ti.kind) {
3762 case UNBOUND:
3763 Si.bound = subst(Ui, A, S);
3764 Si.lower = syms.botType;
3765 break;
3766 case EXTENDS:
3767 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3768 Si.lower = syms.botType;
3769 break;
3770 case SUPER:
3771 Si.bound = subst(Ui, A, S);
3772 Si.lower = Ti.getSuperBound();
3773 break;
3774 }
3775 if (Si.bound == Si.lower)
3776 currentS.head = Si.bound;
3777 }
3778 currentA = currentA.tail;
3779 currentT = currentT.tail;
3780 currentS = currentS.tail;
3781 }
3782 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3783 return erasure(t); // some "rare" type involved
3785 if (captured)
3786 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3787 else
3788 return t;
3789 }
3790 // where
3791 public List<Type> freshTypeVariables(List<Type> types) {
3792 ListBuffer<Type> result = lb();
3793 for (Type t : types) {
3794 if (t.tag == WILDCARD) {
3795 Type bound = ((WildcardType)t).getExtendsBound();
3796 if (bound == null)
3797 bound = syms.objectType;
3798 result.append(new CapturedType(capturedName,
3799 syms.noSymbol,
3800 bound,
3801 syms.botType,
3802 (WildcardType)t));
3803 } else {
3804 result.append(t);
3805 }
3806 }
3807 return result.toList();
3808 }
3809 // </editor-fold>
3811 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3812 private List<Type> upperBounds(List<Type> ss) {
3813 if (ss.isEmpty()) return ss;
3814 Type head = upperBound(ss.head);
3815 List<Type> tail = upperBounds(ss.tail);
3816 if (head != ss.head || tail != ss.tail)
3817 return tail.prepend(head);
3818 else
3819 return ss;
3820 }
3822 private boolean sideCast(Type from, Type to, Warner warn) {
3823 // We are casting from type $from$ to type $to$, which are
3824 // non-final unrelated types. This method
3825 // tries to reject a cast by transferring type parameters
3826 // from $to$ to $from$ by common superinterfaces.
3827 boolean reverse = false;
3828 Type target = to;
3829 if ((to.tsym.flags() & INTERFACE) == 0) {
3830 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3831 reverse = true;
3832 to = from;
3833 from = target;
3834 }
3835 List<Type> commonSupers = superClosure(to, erasure(from));
3836 boolean giveWarning = commonSupers.isEmpty();
3837 // The arguments to the supers could be unified here to
3838 // get a more accurate analysis
3839 while (commonSupers.nonEmpty()) {
3840 Type t1 = asSuper(from, commonSupers.head.tsym);
3841 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3842 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3843 return false;
3844 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3845 commonSupers = commonSupers.tail;
3846 }
3847 if (giveWarning && !isReifiable(reverse ? from : to))
3848 warn.warn(LintCategory.UNCHECKED);
3849 if (!allowCovariantReturns)
3850 // reject if there is a common method signature with
3851 // incompatible return types.
3852 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3853 return true;
3854 }
3856 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3857 // We are casting from type $from$ to type $to$, which are
3858 // unrelated types one of which is final and the other of
3859 // which is an interface. This method
3860 // tries to reject a cast by transferring type parameters
3861 // from the final class to the interface.
3862 boolean reverse = false;
3863 Type target = to;
3864 if ((to.tsym.flags() & INTERFACE) == 0) {
3865 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3866 reverse = true;
3867 to = from;
3868 from = target;
3869 }
3870 Assert.check((from.tsym.flags() & FINAL) != 0);
3871 Type t1 = asSuper(from, to.tsym);
3872 if (t1 == null) return false;
3873 Type t2 = to;
3874 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3875 return false;
3876 if (!allowCovariantReturns)
3877 // reject if there is a common method signature with
3878 // incompatible return types.
3879 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3880 if (!isReifiable(target) &&
3881 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3882 warn.warn(LintCategory.UNCHECKED);
3883 return true;
3884 }
3886 private boolean giveWarning(Type from, Type to) {
3887 Type subFrom = asSub(from, to.tsym);
3888 return to.isParameterized() &&
3889 (!(isUnbounded(to) ||
3890 isSubtype(from, to) ||
3891 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3892 }
3894 private List<Type> superClosure(Type t, Type s) {
3895 List<Type> cl = List.nil();
3896 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3897 if (isSubtype(s, erasure(l.head))) {
3898 cl = insert(cl, l.head);
3899 } else {
3900 cl = union(cl, superClosure(l.head, s));
3901 }
3902 }
3903 return cl;
3904 }
3906 private boolean containsTypeEquivalent(Type t, Type s) {
3907 return
3908 isSameType(t, s) || // shortcut
3909 containsType(t, s) && containsType(s, t);
3910 }
3912 // <editor-fold defaultstate="collapsed" desc="adapt">
3913 /**
3914 * Adapt a type by computing a substitution which maps a source
3915 * type to a target type.
3916 *
3917 * @param source the source type
3918 * @param target the target type
3919 * @param from the type variables of the computed substitution
3920 * @param to the types of the computed substitution.
3921 */
3922 public void adapt(Type source,
3923 Type target,
3924 ListBuffer<Type> from,
3925 ListBuffer<Type> to) throws AdaptFailure {
3926 new Adapter(from, to).adapt(source, target);
3927 }
3929 class Adapter extends SimpleVisitor<Void, Type> {
3931 ListBuffer<Type> from;
3932 ListBuffer<Type> to;
3933 Map<Symbol,Type> mapping;
3935 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3936 this.from = from;
3937 this.to = to;
3938 mapping = new HashMap<Symbol,Type>();
3939 }
3941 public void adapt(Type source, Type target) throws AdaptFailure {
3942 visit(source, target);
3943 List<Type> fromList = from.toList();
3944 List<Type> toList = to.toList();
3945 while (!fromList.isEmpty()) {
3946 Type val = mapping.get(fromList.head.tsym);
3947 if (toList.head != val)
3948 toList.head = val;
3949 fromList = fromList.tail;
3950 toList = toList.tail;
3951 }
3952 }
3954 @Override
3955 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3956 if (target.tag == CLASS)
3957 adaptRecursive(source.allparams(), target.allparams());
3958 return null;
3959 }
3961 @Override
3962 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3963 if (target.tag == ARRAY)
3964 adaptRecursive(elemtype(source), elemtype(target));
3965 return null;
3966 }
3968 @Override
3969 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3970 if (source.isExtendsBound())
3971 adaptRecursive(upperBound(source), upperBound(target));
3972 else if (source.isSuperBound())
3973 adaptRecursive(lowerBound(source), lowerBound(target));
3974 return null;
3975 }
3977 @Override
3978 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3979 // Check to see if there is
3980 // already a mapping for $source$, in which case
3981 // the old mapping will be merged with the new
3982 Type val = mapping.get(source.tsym);
3983 if (val != null) {
3984 if (val.isSuperBound() && target.isSuperBound()) {
3985 val = isSubtype(lowerBound(val), lowerBound(target))
3986 ? target : val;
3987 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3988 val = isSubtype(upperBound(val), upperBound(target))
3989 ? val : target;
3990 } else if (!isSameType(val, target)) {
3991 throw new AdaptFailure();
3992 }
3993 } else {
3994 val = target;
3995 from.append(source);
3996 to.append(target);
3997 }
3998 mapping.put(source.tsym, val);
3999 return null;
4000 }
4002 @Override
4003 public Void visitType(Type source, Type target) {
4004 return null;
4005 }
4007 private Set<TypePair> cache = new HashSet<TypePair>();
4009 private void adaptRecursive(Type source, Type target) {
4010 TypePair pair = new TypePair(source, target);
4011 if (cache.add(pair)) {
4012 try {
4013 visit(source, target);
4014 } finally {
4015 cache.remove(pair);
4016 }
4017 }
4018 }
4020 private void adaptRecursive(List<Type> source, List<Type> target) {
4021 if (source.length() == target.length()) {
4022 while (source.nonEmpty()) {
4023 adaptRecursive(source.head, target.head);
4024 source = source.tail;
4025 target = target.tail;
4026 }
4027 }
4028 }
4029 }
4031 public static class AdaptFailure extends RuntimeException {
4032 static final long serialVersionUID = -7490231548272701566L;
4033 }
4035 private void adaptSelf(Type t,
4036 ListBuffer<Type> from,
4037 ListBuffer<Type> to) {
4038 try {
4039 //if (t.tsym.type != t)
4040 adapt(t.tsym.type, t, from, to);
4041 } catch (AdaptFailure ex) {
4042 // Adapt should never fail calculating a mapping from
4043 // t.tsym.type to t as there can be no merge problem.
4044 throw new AssertionError(ex);
4045 }
4046 }
4047 // </editor-fold>
4049 /**
4050 * Rewrite all type variables (universal quantifiers) in the given
4051 * type to wildcards (existential quantifiers). This is used to
4052 * determine if a cast is allowed. For example, if high is true
4053 * and {@code T <: Number}, then {@code List<T>} is rewritten to
4054 * {@code List<? extends Number>}. Since {@code List<Integer> <:
4055 * List<? extends Number>} a {@code List<T>} can be cast to {@code
4056 * List<Integer>} with a warning.
4057 * @param t a type
4058 * @param high if true return an upper bound; otherwise a lower
4059 * bound
4060 * @param rewriteTypeVars only rewrite captured wildcards if false;
4061 * otherwise rewrite all type variables
4062 * @return the type rewritten with wildcards (existential
4063 * quantifiers) only
4064 */
4065 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4066 return new Rewriter(high, rewriteTypeVars).visit(t);
4067 }
4069 class Rewriter extends UnaryVisitor<Type> {
4071 boolean high;
4072 boolean rewriteTypeVars;
4074 Rewriter(boolean high, boolean rewriteTypeVars) {
4075 this.high = high;
4076 this.rewriteTypeVars = rewriteTypeVars;
4077 }
4079 @Override
4080 public Type visitClassType(ClassType t, Void s) {
4081 ListBuffer<Type> rewritten = new ListBuffer<Type>();
4082 boolean changed = false;
4083 for (Type arg : t.allparams()) {
4084 Type bound = visit(arg);
4085 if (arg != bound) {
4086 changed = true;
4087 }
4088 rewritten.append(bound);
4089 }
4090 if (changed)
4091 return subst(t.tsym.type,
4092 t.tsym.type.allparams(),
4093 rewritten.toList());
4094 else
4095 return t;
4096 }
4098 public Type visitType(Type t, Void s) {
4099 return high ? upperBound(t) : lowerBound(t);
4100 }
4102 @Override
4103 public Type visitCapturedType(CapturedType t, Void s) {
4104 Type w_bound = t.wildcard.type;
4105 Type bound = w_bound.contains(t) ?
4106 erasure(w_bound) :
4107 visit(w_bound);
4108 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4109 }
4111 @Override
4112 public Type visitTypeVar(TypeVar t, Void s) {
4113 if (rewriteTypeVars) {
4114 Type bound = t.bound.contains(t) ?
4115 erasure(t.bound) :
4116 visit(t.bound);
4117 return rewriteAsWildcardType(bound, t, EXTENDS);
4118 } else {
4119 return t;
4120 }
4121 }
4123 @Override
4124 public Type visitWildcardType(WildcardType t, Void s) {
4125 Type bound2 = visit(t.type);
4126 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4127 }
4129 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4130 switch (bk) {
4131 case EXTENDS: return high ?
4132 makeExtendsWildcard(B(bound), formal) :
4133 makeExtendsWildcard(syms.objectType, formal);
4134 case SUPER: return high ?
4135 makeSuperWildcard(syms.botType, formal) :
4136 makeSuperWildcard(B(bound), formal);
4137 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4138 default:
4139 Assert.error("Invalid bound kind " + bk);
4140 return null;
4141 }
4142 }
4144 Type B(Type t) {
4145 while (t.tag == WILDCARD) {
4146 WildcardType w = (WildcardType)t;
4147 t = high ?
4148 w.getExtendsBound() :
4149 w.getSuperBound();
4150 if (t == null) {
4151 t = high ? syms.objectType : syms.botType;
4152 }
4153 }
4154 return t;
4155 }
4156 }
4159 /**
4160 * Create a wildcard with the given upper (extends) bound; create
4161 * an unbounded wildcard if bound is Object.
4162 *
4163 * @param bound the upper bound
4164 * @param formal the formal type parameter that will be
4165 * substituted by the wildcard
4166 */
4167 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4168 if (bound == syms.objectType) {
4169 return new WildcardType(syms.objectType,
4170 BoundKind.UNBOUND,
4171 syms.boundClass,
4172 formal);
4173 } else {
4174 return new WildcardType(bound,
4175 BoundKind.EXTENDS,
4176 syms.boundClass,
4177 formal);
4178 }
4179 }
4181 /**
4182 * Create a wildcard with the given lower (super) bound; create an
4183 * unbounded wildcard if bound is bottom (type of {@code null}).
4184 *
4185 * @param bound the lower bound
4186 * @param formal the formal type parameter that will be
4187 * substituted by the wildcard
4188 */
4189 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4190 if (bound.tag == BOT) {
4191 return new WildcardType(syms.objectType,
4192 BoundKind.UNBOUND,
4193 syms.boundClass,
4194 formal);
4195 } else {
4196 return new WildcardType(bound,
4197 BoundKind.SUPER,
4198 syms.boundClass,
4199 formal);
4200 }
4201 }
4203 /**
4204 * A wrapper for a type that allows use in sets.
4205 */
4206 public static class UniqueType {
4207 public final Type type;
4208 final Types types;
4210 public UniqueType(Type type, Types types) {
4211 this.type = type;
4212 this.types = types;
4213 }
4215 public int hashCode() {
4216 return types.hashCode(type);
4217 }
4219 public boolean equals(Object obj) {
4220 return (obj instanceof UniqueType) &&
4221 types.isSameType(type, ((UniqueType)obj).type);
4222 }
4224 public String toString() {
4225 return type.toString();
4226 }
4228 }
4229 // </editor-fold>
4231 // <editor-fold defaultstate="collapsed" desc="Visitors">
4232 /**
4233 * A default visitor for types. All visitor methods except
4234 * visitType are implemented by delegating to visitType. Concrete
4235 * subclasses must provide an implementation of visitType and can
4236 * override other methods as needed.
4237 *
4238 * @param <R> the return type of the operation implemented by this
4239 * visitor; use Void if no return type is needed.
4240 * @param <S> the type of the second argument (the first being the
4241 * type itself) of the operation implemented by this visitor; use
4242 * Void if a second argument is not needed.
4243 */
4244 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4245 final public R visit(Type t, S s) { return t.accept(this, s); }
4246 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
4247 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4248 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
4249 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
4250 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
4251 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
4252 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4253 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
4254 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
4255 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
4256 // Pretend annotations don't exist
4257 public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
4258 }
4260 /**
4261 * A default visitor for symbols. All visitor methods except
4262 * visitSymbol are implemented by delegating to visitSymbol. Concrete
4263 * subclasses must provide an implementation of visitSymbol and can
4264 * override other methods as needed.
4265 *
4266 * @param <R> the return type of the operation implemented by this
4267 * visitor; use Void if no return type is needed.
4268 * @param <S> the type of the second argument (the first being the
4269 * symbol itself) of the operation implemented by this visitor; use
4270 * Void if a second argument is not needed.
4271 */
4272 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4273 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
4274 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
4275 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
4276 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
4277 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
4278 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
4279 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
4280 }
4282 /**
4283 * A <em>simple</em> visitor for types. This visitor is simple as
4284 * captured wildcards, for-all types (generic methods), and
4285 * undetermined type variables (part of inference) are hidden.
4286 * Captured wildcards are hidden by treating them as type
4287 * variables and the rest are hidden by visiting their qtypes.
4288 *
4289 * @param <R> the return type of the operation implemented by this
4290 * visitor; use Void if no return type is needed.
4291 * @param <S> the type of the second argument (the first being the
4292 * type itself) of the operation implemented by this visitor; use
4293 * Void if a second argument is not needed.
4294 */
4295 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4296 @Override
4297 public R visitCapturedType(CapturedType t, S s) {
4298 return visitTypeVar(t, s);
4299 }
4300 @Override
4301 public R visitForAll(ForAll t, S s) {
4302 return visit(t.qtype, s);
4303 }
4304 @Override
4305 public R visitUndetVar(UndetVar t, S s) {
4306 return visit(t.qtype, s);
4307 }
4308 }
4310 /**
4311 * A plain relation on types. That is a 2-ary function on the
4312 * form Type × Type → Boolean.
4313 * <!-- In plain text: Type x Type -> Boolean -->
4314 */
4315 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4317 /**
4318 * A convenience visitor for implementing operations that only
4319 * require one argument (the type itself), that is, unary
4320 * operations.
4321 *
4322 * @param <R> the return type of the operation implemented by this
4323 * visitor; use Void if no return type is needed.
4324 */
4325 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4326 final public R visit(Type t) { return t.accept(this, null); }
4327 }
4329 /**
4330 * A visitor for implementing a mapping from types to types. The
4331 * default behavior of this class is to implement the identity
4332 * mapping (mapping a type to itself). This can be overridden in
4333 * subclasses.
4334 *
4335 * @param <S> the type of the second argument (the first being the
4336 * type itself) of this mapping; use Void if a second argument is
4337 * not needed.
4338 */
4339 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4340 final public Type visit(Type t) { return t.accept(this, null); }
4341 public Type visitType(Type t, S s) { return t; }
4342 }
4343 // </editor-fold>
4346 // <editor-fold defaultstate="collapsed" desc="Annotation support">
4348 public RetentionPolicy getRetention(Attribute.Compound a) {
4349 return getRetention(a.type.tsym);
4350 }
4352 public RetentionPolicy getRetention(Symbol sym) {
4353 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4354 Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4355 if (c != null) {
4356 Attribute value = c.member(names.value);
4357 if (value != null && value instanceof Attribute.Enum) {
4358 Name levelName = ((Attribute.Enum)value).value.name;
4359 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4360 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4361 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4362 else ;// /* fail soft */ throw new AssertionError(levelName);
4363 }
4364 }
4365 return vis;
4366 }
4367 // </editor-fold>
4369 // <editor-fold defaultstate="collapsed" desc="Signature Generation">
4371 public static abstract class SignatureGenerator {
4373 private final Types types;
4375 protected abstract void append(char ch);
4376 protected abstract void append(byte[] ba);
4377 protected abstract void append(Name name);
4378 protected void classReference(ClassSymbol c) { /* by default: no-op */ }
4380 protected SignatureGenerator(Types types) {
4381 this.types = types;
4382 }
4384 /**
4385 * Assemble signature of given type in string buffer.
4386 */
4387 public void assembleSig(Type type) {
4388 type = type.unannotatedType();
4389 switch (type.getTag()) {
4390 case BYTE:
4391 append('B');
4392 break;
4393 case SHORT:
4394 append('S');
4395 break;
4396 case CHAR:
4397 append('C');
4398 break;
4399 case INT:
4400 append('I');
4401 break;
4402 case LONG:
4403 append('J');
4404 break;
4405 case FLOAT:
4406 append('F');
4407 break;
4408 case DOUBLE:
4409 append('D');
4410 break;
4411 case BOOLEAN:
4412 append('Z');
4413 break;
4414 case VOID:
4415 append('V');
4416 break;
4417 case CLASS:
4418 append('L');
4419 assembleClassSig(type);
4420 append(';');
4421 break;
4422 case ARRAY:
4423 ArrayType at = (ArrayType) type;
4424 append('[');
4425 assembleSig(at.elemtype);
4426 break;
4427 case METHOD:
4428 MethodType mt = (MethodType) type;
4429 append('(');
4430 assembleSig(mt.argtypes);
4431 append(')');
4432 assembleSig(mt.restype);
4433 if (hasTypeVar(mt.thrown)) {
4434 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
4435 append('^');
4436 assembleSig(l.head);
4437 }
4438 }
4439 break;
4440 case WILDCARD: {
4441 Type.WildcardType ta = (Type.WildcardType) type;
4442 switch (ta.kind) {
4443 case SUPER:
4444 append('-');
4445 assembleSig(ta.type);
4446 break;
4447 case EXTENDS:
4448 append('+');
4449 assembleSig(ta.type);
4450 break;
4451 case UNBOUND:
4452 append('*');
4453 break;
4454 default:
4455 throw new AssertionError(ta.kind);
4456 }
4457 break;
4458 }
4459 case TYPEVAR:
4460 append('T');
4461 append(type.tsym.name);
4462 append(';');
4463 break;
4464 case FORALL:
4465 Type.ForAll ft = (Type.ForAll) type;
4466 assembleParamsSig(ft.tvars);
4467 assembleSig(ft.qtype);
4468 break;
4469 default:
4470 throw new AssertionError("typeSig " + type.getTag());
4471 }
4472 }
4474 public boolean hasTypeVar(List<Type> l) {
4475 while (l.nonEmpty()) {
4476 if (l.head.hasTag(TypeTag.TYPEVAR)) {
4477 return true;
4478 }
4479 l = l.tail;
4480 }
4481 return false;
4482 }
4484 public void assembleClassSig(Type type) {
4485 type = type.unannotatedType();
4486 ClassType ct = (ClassType) type;
4487 ClassSymbol c = (ClassSymbol) ct.tsym;
4488 classReference(c);
4489 Type outer = ct.getEnclosingType();
4490 if (outer.allparams().nonEmpty()) {
4491 boolean rawOuter =
4492 c.owner.kind == Kinds.MTH || // either a local class
4493 c.name == types.names.empty; // or anonymous
4494 assembleClassSig(rawOuter
4495 ? types.erasure(outer)
4496 : outer);
4497 append('.');
4498 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
4499 append(rawOuter
4500 ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
4501 : c.name);
4502 } else {
4503 append(externalize(c.flatname));
4504 }
4505 if (ct.getTypeArguments().nonEmpty()) {
4506 append('<');
4507 assembleSig(ct.getTypeArguments());
4508 append('>');
4509 }
4510 }
4512 public void assembleParamsSig(List<Type> typarams) {
4513 append('<');
4514 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
4515 Type.TypeVar tvar = (Type.TypeVar) ts.head;
4516 append(tvar.tsym.name);
4517 List<Type> bounds = types.getBounds(tvar);
4518 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
4519 append(':');
4520 }
4521 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
4522 append(':');
4523 assembleSig(l.head);
4524 }
4525 }
4526 append('>');
4527 }
4529 private void assembleSig(List<Type> types) {
4530 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
4531 assembleSig(ts.head);
4532 }
4533 }
4534 }
4535 // </editor-fold>
4536 }