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