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