Fri, 20 Jun 2014 20:36:54 +0100
8044546: Crash on faulty reduce/lambda
Reviewed-by: mcimadamore, dlsmith
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 Type.noType;
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) != Type.noType && 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 visitUndetVar(UndetVar t, Void ignored) {
2958 //do nothing - we should not replace inside undet variables
2959 return t;
2960 }
2962 @Override
2963 public Type visitClassType(ClassType t, Void ignored) {
2964 if (!t.isCompound()) {
2965 List<Type> typarams = t.getTypeArguments();
2966 List<Type> typarams1 = subst(typarams);
2967 Type outer = t.getEnclosingType();
2968 Type outer1 = subst(outer);
2969 if (typarams1 == typarams && outer1 == outer)
2970 return t;
2971 else
2972 return new ClassType(outer1, typarams1, t.tsym);
2973 } else {
2974 Type st = subst(supertype(t));
2975 List<Type> is = subst(interfaces(t));
2976 if (st == supertype(t) && is == interfaces(t))
2977 return t;
2978 else
2979 return makeCompoundType(is.prepend(st));
2980 }
2981 }
2983 @Override
2984 public Type visitWildcardType(WildcardType t, Void ignored) {
2985 Type bound = t.type;
2986 if (t.kind != BoundKind.UNBOUND)
2987 bound = subst(bound);
2988 if (bound == t.type) {
2989 return t;
2990 } else {
2991 if (t.isExtendsBound() && bound.isExtendsBound())
2992 bound = wildUpperBound(bound);
2993 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2994 }
2995 }
2997 @Override
2998 public Type visitArrayType(ArrayType t, Void ignored) {
2999 Type elemtype = subst(t.elemtype);
3000 if (elemtype == t.elemtype)
3001 return t;
3002 else
3003 return new ArrayType(elemtype, t.tsym);
3004 }
3006 @Override
3007 public Type visitForAll(ForAll t, Void ignored) {
3008 if (Type.containsAny(to, t.tvars)) {
3009 //perform alpha-renaming of free-variables in 't'
3010 //if 'to' types contain variables that are free in 't'
3011 List<Type> freevars = newInstances(t.tvars);
3012 t = new ForAll(freevars,
3013 Types.this.subst(t.qtype, t.tvars, freevars));
3014 }
3015 List<Type> tvars1 = substBounds(t.tvars, from, to);
3016 Type qtype1 = subst(t.qtype);
3017 if (tvars1 == t.tvars && qtype1 == t.qtype) {
3018 return t;
3019 } else if (tvars1 == t.tvars) {
3020 return new ForAll(tvars1, qtype1);
3021 } else {
3022 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
3023 }
3024 }
3026 @Override
3027 public Type visitErrorType(ErrorType t, Void ignored) {
3028 return t;
3029 }
3030 }
3032 public List<Type> substBounds(List<Type> tvars,
3033 List<Type> from,
3034 List<Type> to) {
3035 if (tvars.isEmpty())
3036 return tvars;
3037 ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
3038 boolean changed = false;
3039 // calculate new bounds
3040 for (Type t : tvars) {
3041 TypeVar tv = (TypeVar) t;
3042 Type bound = subst(tv.bound, from, to);
3043 if (bound != tv.bound)
3044 changed = true;
3045 newBoundsBuf.append(bound);
3046 }
3047 if (!changed)
3048 return tvars;
3049 ListBuffer<Type> newTvars = new ListBuffer<>();
3050 // create new type variables without bounds
3051 for (Type t : tvars) {
3052 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
3053 }
3054 // the new bounds should use the new type variables in place
3055 // of the old
3056 List<Type> newBounds = newBoundsBuf.toList();
3057 from = tvars;
3058 to = newTvars.toList();
3059 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
3060 newBounds.head = subst(newBounds.head, from, to);
3061 }
3062 newBounds = newBoundsBuf.toList();
3063 // set the bounds of new type variables to the new bounds
3064 for (Type t : newTvars.toList()) {
3065 TypeVar tv = (TypeVar) t;
3066 tv.bound = newBounds.head;
3067 newBounds = newBounds.tail;
3068 }
3069 return newTvars.toList();
3070 }
3072 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
3073 Type bound1 = subst(t.bound, from, to);
3074 if (bound1 == t.bound)
3075 return t;
3076 else {
3077 // create new type variable without bounds
3078 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
3079 // the new bound should use the new type variable in place
3080 // of the old
3081 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
3082 return tv;
3083 }
3084 }
3085 // </editor-fold>
3087 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
3088 /**
3089 * Does t have the same bounds for quantified variables as s?
3090 */
3091 public boolean hasSameBounds(ForAll t, ForAll s) {
3092 List<Type> l1 = t.tvars;
3093 List<Type> l2 = s.tvars;
3094 while (l1.nonEmpty() && l2.nonEmpty() &&
3095 isSameType(l1.head.getUpperBound(),
3096 subst(l2.head.getUpperBound(),
3097 s.tvars,
3098 t.tvars))) {
3099 l1 = l1.tail;
3100 l2 = l2.tail;
3101 }
3102 return l1.isEmpty() && l2.isEmpty();
3103 }
3104 // </editor-fold>
3106 // <editor-fold defaultstate="collapsed" desc="newInstances">
3107 /** Create new vector of type variables from list of variables
3108 * changing all recursive bounds from old to new list.
3109 */
3110 public List<Type> newInstances(List<Type> tvars) {
3111 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
3112 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
3113 TypeVar tv = (TypeVar) l.head;
3114 tv.bound = subst(tv.bound, tvars, tvars1);
3115 }
3116 return tvars1;
3117 }
3118 private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
3119 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
3120 };
3121 // </editor-fold>
3123 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
3124 return original.accept(methodWithParameters, newParams);
3125 }
3126 // where
3127 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
3128 public Type visitType(Type t, List<Type> newParams) {
3129 throw new IllegalArgumentException("Not a method type: " + t);
3130 }
3131 public Type visitMethodType(MethodType t, List<Type> newParams) {
3132 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
3133 }
3134 public Type visitForAll(ForAll t, List<Type> newParams) {
3135 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
3136 }
3137 };
3139 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
3140 return original.accept(methodWithThrown, newThrown);
3141 }
3142 // where
3143 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
3144 public Type visitType(Type t, List<Type> newThrown) {
3145 throw new IllegalArgumentException("Not a method type: " + t);
3146 }
3147 public Type visitMethodType(MethodType t, List<Type> newThrown) {
3148 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
3149 }
3150 public Type visitForAll(ForAll t, List<Type> newThrown) {
3151 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
3152 }
3153 };
3155 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
3156 return original.accept(methodWithReturn, newReturn);
3157 }
3158 // where
3159 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3160 public Type visitType(Type t, Type newReturn) {
3161 throw new IllegalArgumentException("Not a method type: " + t);
3162 }
3163 public Type visitMethodType(MethodType t, Type newReturn) {
3164 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
3165 }
3166 public Type visitForAll(ForAll t, Type newReturn) {
3167 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
3168 }
3169 };
3171 // <editor-fold defaultstate="collapsed" desc="createErrorType">
3172 public Type createErrorType(Type originalType) {
3173 return new ErrorType(originalType, syms.errSymbol);
3174 }
3176 public Type createErrorType(ClassSymbol c, Type originalType) {
3177 return new ErrorType(c, originalType);
3178 }
3180 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3181 return new ErrorType(name, container, originalType);
3182 }
3183 // </editor-fold>
3185 // <editor-fold defaultstate="collapsed" desc="rank">
3186 /**
3187 * The rank of a class is the length of the longest path between
3188 * the class and java.lang.Object in the class inheritance
3189 * graph. Undefined for all but reference types.
3190 */
3191 public int rank(Type t) {
3192 t = t.unannotatedType();
3193 switch(t.getTag()) {
3194 case CLASS: {
3195 ClassType cls = (ClassType)t;
3196 if (cls.rank_field < 0) {
3197 Name fullname = cls.tsym.getQualifiedName();
3198 if (fullname == names.java_lang_Object)
3199 cls.rank_field = 0;
3200 else {
3201 int r = rank(supertype(cls));
3202 for (List<Type> l = interfaces(cls);
3203 l.nonEmpty();
3204 l = l.tail) {
3205 if (rank(l.head) > r)
3206 r = rank(l.head);
3207 }
3208 cls.rank_field = r + 1;
3209 }
3210 }
3211 return cls.rank_field;
3212 }
3213 case TYPEVAR: {
3214 TypeVar tvar = (TypeVar)t;
3215 if (tvar.rank_field < 0) {
3216 int r = rank(supertype(tvar));
3217 for (List<Type> l = interfaces(tvar);
3218 l.nonEmpty();
3219 l = l.tail) {
3220 if (rank(l.head) > r) r = rank(l.head);
3221 }
3222 tvar.rank_field = r + 1;
3223 }
3224 return tvar.rank_field;
3225 }
3226 case ERROR:
3227 case NONE:
3228 return 0;
3229 default:
3230 throw new AssertionError();
3231 }
3232 }
3233 // </editor-fold>
3235 /**
3236 * Helper method for generating a string representation of a given type
3237 * accordingly to a given locale
3238 */
3239 public String toString(Type t, Locale locale) {
3240 return Printer.createStandardPrinter(messages).visit(t, locale);
3241 }
3243 /**
3244 * Helper method for generating a string representation of a given type
3245 * accordingly to a given locale
3246 */
3247 public String toString(Symbol t, Locale locale) {
3248 return Printer.createStandardPrinter(messages).visit(t, locale);
3249 }
3251 // <editor-fold defaultstate="collapsed" desc="toString">
3252 /**
3253 * This toString is slightly more descriptive than the one on Type.
3254 *
3255 * @deprecated Types.toString(Type t, Locale l) provides better support
3256 * for localization
3257 */
3258 @Deprecated
3259 public String toString(Type t) {
3260 if (t.hasTag(FORALL)) {
3261 ForAll forAll = (ForAll)t;
3262 return typaramsString(forAll.tvars) + forAll.qtype;
3263 }
3264 return "" + t;
3265 }
3266 // where
3267 private String typaramsString(List<Type> tvars) {
3268 StringBuilder s = new StringBuilder();
3269 s.append('<');
3270 boolean first = true;
3271 for (Type t : tvars) {
3272 if (!first) s.append(", ");
3273 first = false;
3274 appendTyparamString(((TypeVar)t.unannotatedType()), s);
3275 }
3276 s.append('>');
3277 return s.toString();
3278 }
3279 private void appendTyparamString(TypeVar t, StringBuilder buf) {
3280 buf.append(t);
3281 if (t.bound == null ||
3282 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
3283 return;
3284 buf.append(" extends "); // Java syntax; no need for i18n
3285 Type bound = t.bound;
3286 if (!bound.isCompound()) {
3287 buf.append(bound);
3288 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3289 buf.append(supertype(t));
3290 for (Type intf : interfaces(t)) {
3291 buf.append('&');
3292 buf.append(intf);
3293 }
3294 } else {
3295 // No superclass was given in bounds.
3296 // In this case, supertype is Object, erasure is first interface.
3297 boolean first = true;
3298 for (Type intf : interfaces(t)) {
3299 if (!first) buf.append('&');
3300 first = false;
3301 buf.append(intf);
3302 }
3303 }
3304 }
3305 // </editor-fold>
3307 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3308 /**
3309 * A cache for closures.
3310 *
3311 * <p>A closure is a list of all the supertypes and interfaces of
3312 * a class or interface type, ordered by ClassSymbol.precedes
3313 * (that is, subclasses come first, arbitrary but fixed
3314 * otherwise).
3315 */
3316 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
3318 /**
3319 * Returns the closure of a class or interface type.
3320 */
3321 public List<Type> closure(Type t) {
3322 List<Type> cl = closureCache.get(t);
3323 if (cl == null) {
3324 Type st = supertype(t);
3325 if (!t.isCompound()) {
3326 if (st.hasTag(CLASS)) {
3327 cl = insert(closure(st), t);
3328 } else if (st.hasTag(TYPEVAR)) {
3329 cl = closure(st).prepend(t);
3330 } else {
3331 cl = List.of(t);
3332 }
3333 } else {
3334 cl = closure(supertype(t));
3335 }
3336 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3337 cl = union(cl, closure(l.head));
3338 closureCache.put(t, cl);
3339 }
3340 return cl;
3341 }
3343 /**
3344 * Insert a type in a closure
3345 */
3346 public List<Type> insert(List<Type> cl, Type t) {
3347 if (cl.isEmpty()) {
3348 return cl.prepend(t);
3349 } else if (t.tsym == cl.head.tsym) {
3350 return cl;
3351 } else if (t.tsym.precedes(cl.head.tsym, this)) {
3352 return cl.prepend(t);
3353 } else {
3354 // t comes after head, or the two are unrelated
3355 return insert(cl.tail, t).prepend(cl.head);
3356 }
3357 }
3359 /**
3360 * Form the union of two closures
3361 */
3362 public List<Type> union(List<Type> cl1, List<Type> cl2) {
3363 if (cl1.isEmpty()) {
3364 return cl2;
3365 } else if (cl2.isEmpty()) {
3366 return cl1;
3367 } else if (cl1.head.tsym == cl2.head.tsym) {
3368 return union(cl1.tail, cl2.tail).prepend(cl1.head);
3369 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3370 return union(cl1.tail, cl2).prepend(cl1.head);
3371 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3372 return union(cl1, cl2.tail).prepend(cl2.head);
3373 } else {
3374 // unrelated types
3375 return union(cl1.tail, cl2).prepend(cl1.head);
3376 }
3377 }
3379 /**
3380 * Intersect two closures
3381 */
3382 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3383 if (cl1 == cl2)
3384 return cl1;
3385 if (cl1.isEmpty() || cl2.isEmpty())
3386 return List.nil();
3387 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3388 return intersect(cl1.tail, cl2);
3389 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3390 return intersect(cl1, cl2.tail);
3391 if (isSameType(cl1.head, cl2.head))
3392 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3393 if (cl1.head.tsym == cl2.head.tsym &&
3394 cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
3395 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3396 Type merge = merge(cl1.head,cl2.head);
3397 return intersect(cl1.tail, cl2.tail).prepend(merge);
3398 }
3399 if (cl1.head.isRaw() || cl2.head.isRaw())
3400 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3401 }
3402 return intersect(cl1.tail, cl2.tail);
3403 }
3404 // where
3405 class TypePair {
3406 final Type t1;
3407 final Type t2;
3408 boolean strict;
3410 TypePair(Type t1, Type t2) {
3411 this(t1, t2, false);
3412 }
3414 TypePair(Type t1, Type t2, boolean strict) {
3415 this.t1 = t1;
3416 this.t2 = t2;
3417 this.strict = strict;
3418 }
3419 @Override
3420 public int hashCode() {
3421 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3422 }
3423 @Override
3424 public boolean equals(Object obj) {
3425 if (!(obj instanceof TypePair))
3426 return false;
3427 TypePair typePair = (TypePair)obj;
3428 return isSameType(t1, typePair.t1, strict)
3429 && isSameType(t2, typePair.t2, strict);
3430 }
3431 }
3432 Set<TypePair> mergeCache = new HashSet<TypePair>();
3433 private Type merge(Type c1, Type c2) {
3434 ClassType class1 = (ClassType) c1;
3435 List<Type> act1 = class1.getTypeArguments();
3436 ClassType class2 = (ClassType) c2;
3437 List<Type> act2 = class2.getTypeArguments();
3438 ListBuffer<Type> merged = new ListBuffer<Type>();
3439 List<Type> typarams = class1.tsym.type.getTypeArguments();
3441 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3442 if (containsType(act1.head, act2.head)) {
3443 merged.append(act1.head);
3444 } else if (containsType(act2.head, act1.head)) {
3445 merged.append(act2.head);
3446 } else {
3447 TypePair pair = new TypePair(c1, c2);
3448 Type m;
3449 if (mergeCache.add(pair)) {
3450 m = new WildcardType(lub(wildUpperBound(act1.head),
3451 wildUpperBound(act2.head)),
3452 BoundKind.EXTENDS,
3453 syms.boundClass);
3454 mergeCache.remove(pair);
3455 } else {
3456 m = new WildcardType(syms.objectType,
3457 BoundKind.UNBOUND,
3458 syms.boundClass);
3459 }
3460 merged.append(m.withTypeVar(typarams.head));
3461 }
3462 act1 = act1.tail;
3463 act2 = act2.tail;
3464 typarams = typarams.tail;
3465 }
3466 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3467 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
3468 }
3470 /**
3471 * Return the minimum type of a closure, a compound type if no
3472 * unique minimum exists.
3473 */
3474 private Type compoundMin(List<Type> cl) {
3475 if (cl.isEmpty()) return syms.objectType;
3476 List<Type> compound = closureMin(cl);
3477 if (compound.isEmpty())
3478 return null;
3479 else if (compound.tail.isEmpty())
3480 return compound.head;
3481 else
3482 return makeCompoundType(compound);
3483 }
3485 /**
3486 * Return the minimum types of a closure, suitable for computing
3487 * compoundMin or glb.
3488 */
3489 private List<Type> closureMin(List<Type> cl) {
3490 ListBuffer<Type> classes = new ListBuffer<>();
3491 ListBuffer<Type> interfaces = new ListBuffer<>();
3492 Set<Type> toSkip = new HashSet<>();
3493 while (!cl.isEmpty()) {
3494 Type current = cl.head;
3495 boolean keep = !toSkip.contains(current);
3496 if (keep && current.hasTag(TYPEVAR)) {
3497 // skip lower-bounded variables with a subtype in cl.tail
3498 for (Type t : cl.tail) {
3499 if (isSubtypeNoCapture(t, current)) {
3500 keep = false;
3501 break;
3502 }
3503 }
3504 }
3505 if (keep) {
3506 if (current.isInterface())
3507 interfaces.append(current);
3508 else
3509 classes.append(current);
3510 for (Type t : cl.tail) {
3511 // skip supertypes of 'current' in cl.tail
3512 if (isSubtypeNoCapture(current, t))
3513 toSkip.add(t);
3514 }
3515 }
3516 cl = cl.tail;
3517 }
3518 return classes.appendList(interfaces).toList();
3519 }
3521 /**
3522 * Return the least upper bound of pair of types. if the lub does
3523 * not exist return null.
3524 */
3525 public Type lub(Type t1, Type t2) {
3526 return lub(List.of(t1, t2));
3527 }
3529 /**
3530 * Return the least upper bound (lub) of set of types. If the lub
3531 * does not exist return the type of null (bottom).
3532 */
3533 public Type lub(List<Type> ts) {
3534 final int ARRAY_BOUND = 1;
3535 final int CLASS_BOUND = 2;
3536 int boundkind = 0;
3537 for (Type t : ts) {
3538 switch (t.getTag()) {
3539 case CLASS:
3540 boundkind |= CLASS_BOUND;
3541 break;
3542 case ARRAY:
3543 boundkind |= ARRAY_BOUND;
3544 break;
3545 case TYPEVAR:
3546 do {
3547 t = t.getUpperBound();
3548 } while (t.hasTag(TYPEVAR));
3549 if (t.hasTag(ARRAY)) {
3550 boundkind |= ARRAY_BOUND;
3551 } else {
3552 boundkind |= CLASS_BOUND;
3553 }
3554 break;
3555 default:
3556 if (t.isPrimitive())
3557 return syms.errType;
3558 }
3559 }
3560 switch (boundkind) {
3561 case 0:
3562 return syms.botType;
3564 case ARRAY_BOUND:
3565 // calculate lub(A[], B[])
3566 List<Type> elements = Type.map(ts, elemTypeFun);
3567 for (Type t : elements) {
3568 if (t.isPrimitive()) {
3569 // if a primitive type is found, then return
3570 // arraySuperType unless all the types are the
3571 // same
3572 Type first = ts.head;
3573 for (Type s : ts.tail) {
3574 if (!isSameType(first, s)) {
3575 // lub(int[], B[]) is Cloneable & Serializable
3576 return arraySuperType();
3577 }
3578 }
3579 // all the array types are the same, return one
3580 // lub(int[], int[]) is int[]
3581 return first;
3582 }
3583 }
3584 // lub(A[], B[]) is lub(A, B)[]
3585 return new ArrayType(lub(elements), syms.arrayClass);
3587 case CLASS_BOUND:
3588 // calculate lub(A, B)
3589 while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
3590 ts = ts.tail;
3591 }
3592 Assert.check(!ts.isEmpty());
3593 //step 1 - compute erased candidate set (EC)
3594 List<Type> cl = erasedSupertypes(ts.head);
3595 for (Type t : ts.tail) {
3596 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
3597 cl = intersect(cl, erasedSupertypes(t));
3598 }
3599 //step 2 - compute minimal erased candidate set (MEC)
3600 List<Type> mec = closureMin(cl);
3601 //step 3 - for each element G in MEC, compute lci(Inv(G))
3602 List<Type> candidates = List.nil();
3603 for (Type erasedSupertype : mec) {
3604 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
3605 for (Type t : ts) {
3606 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
3607 }
3608 candidates = candidates.appendList(lci);
3609 }
3610 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3611 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3612 return compoundMin(candidates);
3614 default:
3615 // calculate lub(A, B[])
3616 List<Type> classes = List.of(arraySuperType());
3617 for (Type t : ts) {
3618 if (!t.hasTag(ARRAY)) // Filter out any arrays
3619 classes = classes.prepend(t);
3620 }
3621 // lub(A, B[]) is lub(A, arraySuperType)
3622 return lub(classes);
3623 }
3624 }
3625 // where
3626 List<Type> erasedSupertypes(Type t) {
3627 ListBuffer<Type> buf = new ListBuffer<>();
3628 for (Type sup : closure(t)) {
3629 if (sup.hasTag(TYPEVAR)) {
3630 buf.append(sup);
3631 } else {
3632 buf.append(erasure(sup));
3633 }
3634 }
3635 return buf.toList();
3636 }
3638 private Type arraySuperType = null;
3639 private Type arraySuperType() {
3640 // initialized lazily to avoid problems during compiler startup
3641 if (arraySuperType == null) {
3642 synchronized (this) {
3643 if (arraySuperType == null) {
3644 // JLS 10.8: all arrays implement Cloneable and Serializable.
3645 arraySuperType = makeCompoundType(List.of(syms.serializableType,
3646 syms.cloneableType), true);
3647 }
3648 }
3649 }
3650 return arraySuperType;
3651 }
3652 // </editor-fold>
3654 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3655 public Type glb(List<Type> ts) {
3656 Type t1 = ts.head;
3657 for (Type t2 : ts.tail) {
3658 if (t1.isErroneous())
3659 return t1;
3660 t1 = glb(t1, t2);
3661 }
3662 return t1;
3663 }
3664 //where
3665 public Type glb(Type t, Type s) {
3666 if (s == null)
3667 return t;
3668 else if (t.isPrimitive() || s.isPrimitive())
3669 return syms.errType;
3670 else if (isSubtypeNoCapture(t, s))
3671 return t;
3672 else if (isSubtypeNoCapture(s, t))
3673 return s;
3675 List<Type> closure = union(closure(t), closure(s));
3676 return glbFlattened(closure, t);
3677 }
3678 //where
3679 /**
3680 * Perform glb for a list of non-primitive, non-error, non-compound types;
3681 * redundant elements are removed. Bounds should be ordered according to
3682 * {@link Symbol#precedes(TypeSymbol,Types)}.
3683 *
3684 * @param flatBounds List of type to glb
3685 * @param errT Original type to use if the result is an error type
3686 */
3687 private Type glbFlattened(List<Type> flatBounds, Type errT) {
3688 List<Type> bounds = closureMin(flatBounds);
3690 if (bounds.isEmpty()) { // length == 0
3691 return syms.objectType;
3692 } else if (bounds.tail.isEmpty()) { // length == 1
3693 return bounds.head;
3694 } else { // length > 1
3695 int classCount = 0;
3696 List<Type> lowers = List.nil();
3697 for (Type bound : bounds) {
3698 if (!bound.isInterface()) {
3699 classCount++;
3700 Type lower = cvarLowerBound(bound);
3701 if (bound != lower && !lower.hasTag(BOT))
3702 lowers = insert(lowers, lower);
3703 }
3704 }
3705 if (classCount > 1) {
3706 if (lowers.isEmpty())
3707 return createErrorType(errT);
3708 else
3709 return glbFlattened(union(bounds, lowers), errT);
3710 }
3711 }
3712 return makeCompoundType(bounds);
3713 }
3714 // </editor-fold>
3716 // <editor-fold defaultstate="collapsed" desc="hashCode">
3717 /**
3718 * Compute a hash code on a type.
3719 */
3720 public int hashCode(Type t) {
3721 return hashCode.visit(t);
3722 }
3723 // where
3724 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3726 public Integer visitType(Type t, Void ignored) {
3727 return t.getTag().ordinal();
3728 }
3730 @Override
3731 public Integer visitClassType(ClassType t, Void ignored) {
3732 int result = visit(t.getEnclosingType());
3733 result *= 127;
3734 result += t.tsym.flatName().hashCode();
3735 for (Type s : t.getTypeArguments()) {
3736 result *= 127;
3737 result += visit(s);
3738 }
3739 return result;
3740 }
3742 @Override
3743 public Integer visitMethodType(MethodType t, Void ignored) {
3744 int h = METHOD.ordinal();
3745 for (List<Type> thisargs = t.argtypes;
3746 thisargs.tail != null;
3747 thisargs = thisargs.tail)
3748 h = (h << 5) + visit(thisargs.head);
3749 return (h << 5) + visit(t.restype);
3750 }
3752 @Override
3753 public Integer visitWildcardType(WildcardType t, Void ignored) {
3754 int result = t.kind.hashCode();
3755 if (t.type != null) {
3756 result *= 127;
3757 result += visit(t.type);
3758 }
3759 return result;
3760 }
3762 @Override
3763 public Integer visitArrayType(ArrayType t, Void ignored) {
3764 return visit(t.elemtype) + 12;
3765 }
3767 @Override
3768 public Integer visitTypeVar(TypeVar t, Void ignored) {
3769 return System.identityHashCode(t.tsym);
3770 }
3772 @Override
3773 public Integer visitUndetVar(UndetVar t, Void ignored) {
3774 return System.identityHashCode(t);
3775 }
3777 @Override
3778 public Integer visitErrorType(ErrorType t, Void ignored) {
3779 return 0;
3780 }
3781 };
3782 // </editor-fold>
3784 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3785 /**
3786 * Does t have a result that is a subtype of the result type of s,
3787 * suitable for covariant returns? It is assumed that both types
3788 * are (possibly polymorphic) method types. Monomorphic method
3789 * types are handled in the obvious way. Polymorphic method types
3790 * require renaming all type variables of one to corresponding
3791 * type variables in the other, where correspondence is by
3792 * position in the type parameter list. */
3793 public boolean resultSubtype(Type t, Type s, Warner warner) {
3794 List<Type> tvars = t.getTypeArguments();
3795 List<Type> svars = s.getTypeArguments();
3796 Type tres = t.getReturnType();
3797 Type sres = subst(s.getReturnType(), svars, tvars);
3798 return covariantReturnType(tres, sres, warner);
3799 }
3801 /**
3802 * Return-Type-Substitutable.
3803 * @jls section 8.4.5
3804 */
3805 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3806 if (hasSameArgs(r1, r2))
3807 return resultSubtype(r1, r2, noWarnings);
3808 else
3809 return covariantReturnType(r1.getReturnType(),
3810 erasure(r2.getReturnType()),
3811 noWarnings);
3812 }
3814 public boolean returnTypeSubstitutable(Type r1,
3815 Type r2, Type r2res,
3816 Warner warner) {
3817 if (isSameType(r1.getReturnType(), r2res))
3818 return true;
3819 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3820 return false;
3822 if (hasSameArgs(r1, r2))
3823 return covariantReturnType(r1.getReturnType(), r2res, warner);
3824 if (!allowCovariantReturns)
3825 return false;
3826 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3827 return true;
3828 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3829 return false;
3830 warner.warn(LintCategory.UNCHECKED);
3831 return true;
3832 }
3834 /**
3835 * Is t an appropriate return type in an overrider for a
3836 * method that returns s?
3837 */
3838 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3839 return
3840 isSameType(t, s) ||
3841 allowCovariantReturns &&
3842 !t.isPrimitive() &&
3843 !s.isPrimitive() &&
3844 isAssignable(t, s, warner);
3845 }
3846 // </editor-fold>
3848 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3849 /**
3850 * Return the class that boxes the given primitive.
3851 */
3852 public ClassSymbol boxedClass(Type t) {
3853 return reader.enterClass(syms.boxedName[t.getTag().ordinal()]);
3854 }
3856 /**
3857 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3858 */
3859 public Type boxedTypeOrType(Type t) {
3860 return t.isPrimitive() ?
3861 boxedClass(t).type :
3862 t;
3863 }
3865 /**
3866 * Return the primitive type corresponding to a boxed type.
3867 */
3868 public Type unboxedType(Type t) {
3869 if (allowBoxing) {
3870 for (int i=0; i<syms.boxedName.length; i++) {
3871 Name box = syms.boxedName[i];
3872 if (box != null &&
3873 asSuper(t, reader.enterClass(box)) != null)
3874 return syms.typeOfTag[i];
3875 }
3876 }
3877 return Type.noType;
3878 }
3880 /**
3881 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3882 */
3883 public Type unboxedTypeOrType(Type t) {
3884 Type unboxedType = unboxedType(t);
3885 return unboxedType.hasTag(NONE) ? t : unboxedType;
3886 }
3887 // </editor-fold>
3889 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3890 /*
3891 * JLS 5.1.10 Capture Conversion:
3892 *
3893 * Let G name a generic type declaration with n formal type
3894 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3895 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3896 * where, for 1 <= i <= n:
3897 *
3898 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3899 * Si is a fresh type variable whose upper bound is
3900 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3901 * type.
3902 *
3903 * + If Ti is a wildcard type argument of the form ? extends Bi,
3904 * then Si is a fresh type variable whose upper bound is
3905 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3906 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3907 * a compile-time error if for any two classes (not interfaces)
3908 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3909 *
3910 * + If Ti is a wildcard type argument of the form ? super Bi,
3911 * then Si is a fresh type variable whose upper bound is
3912 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3913 *
3914 * + Otherwise, Si = Ti.
3915 *
3916 * Capture conversion on any type other than a parameterized type
3917 * (4.5) acts as an identity conversion (5.1.1). Capture
3918 * conversions never require a special action at run time and
3919 * therefore never throw an exception at run time.
3920 *
3921 * Capture conversion is not applied recursively.
3922 */
3923 /**
3924 * Capture conversion as specified by the JLS.
3925 */
3927 public List<Type> capture(List<Type> ts) {
3928 List<Type> buf = List.nil();
3929 for (Type t : ts) {
3930 buf = buf.prepend(capture(t));
3931 }
3932 return buf.reverse();
3933 }
3935 public Type capture(Type t) {
3936 if (!t.hasTag(CLASS)) {
3937 return t;
3938 }
3939 if (t.getEnclosingType() != Type.noType) {
3940 Type capturedEncl = capture(t.getEnclosingType());
3941 if (capturedEncl != t.getEnclosingType()) {
3942 Type type1 = memberType(capturedEncl, t.tsym);
3943 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3944 }
3945 }
3946 t = t.unannotatedType();
3947 ClassType cls = (ClassType)t;
3948 if (cls.isRaw() || !cls.isParameterized())
3949 return cls;
3951 ClassType G = (ClassType)cls.asElement().asType();
3952 List<Type> A = G.getTypeArguments();
3953 List<Type> T = cls.getTypeArguments();
3954 List<Type> S = freshTypeVariables(T);
3956 List<Type> currentA = A;
3957 List<Type> currentT = T;
3958 List<Type> currentS = S;
3959 boolean captured = false;
3960 while (!currentA.isEmpty() &&
3961 !currentT.isEmpty() &&
3962 !currentS.isEmpty()) {
3963 if (currentS.head != currentT.head) {
3964 captured = true;
3965 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
3966 Type Ui = currentA.head.getUpperBound();
3967 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
3968 if (Ui == null)
3969 Ui = syms.objectType;
3970 switch (Ti.kind) {
3971 case UNBOUND:
3972 Si.bound = subst(Ui, A, S);
3973 Si.lower = syms.botType;
3974 break;
3975 case EXTENDS:
3976 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3977 Si.lower = syms.botType;
3978 break;
3979 case SUPER:
3980 Si.bound = subst(Ui, A, S);
3981 Si.lower = Ti.getSuperBound();
3982 break;
3983 }
3984 Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
3985 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
3986 if (!Si.bound.hasTag(ERROR) &&
3987 !Si.lower.hasTag(ERROR) &&
3988 isSameType(tmpBound, tmpLower, false)) {
3989 currentS.head = Si.bound;
3990 }
3991 }
3992 currentA = currentA.tail;
3993 currentT = currentT.tail;
3994 currentS = currentS.tail;
3995 }
3996 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3997 return erasure(t); // some "rare" type involved
3999 if (captured)
4000 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
4001 else
4002 return t;
4003 }
4004 // where
4005 public List<Type> freshTypeVariables(List<Type> types) {
4006 ListBuffer<Type> result = new ListBuffer<>();
4007 for (Type t : types) {
4008 if (t.hasTag(WILDCARD)) {
4009 t = t.unannotatedType();
4010 Type bound = ((WildcardType)t).getExtendsBound();
4011 if (bound == null)
4012 bound = syms.objectType;
4013 result.append(new CapturedType(capturedName,
4014 syms.noSymbol,
4015 bound,
4016 syms.botType,
4017 (WildcardType)t));
4018 } else {
4019 result.append(t);
4020 }
4021 }
4022 return result.toList();
4023 }
4024 // </editor-fold>
4026 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
4027 private boolean sideCast(Type from, Type to, Warner warn) {
4028 // We are casting from type $from$ to type $to$, which are
4029 // non-final unrelated types. This method
4030 // tries to reject a cast by transferring type parameters
4031 // from $to$ to $from$ by common superinterfaces.
4032 boolean reverse = false;
4033 Type target = to;
4034 if ((to.tsym.flags() & INTERFACE) == 0) {
4035 Assert.check((from.tsym.flags() & INTERFACE) != 0);
4036 reverse = true;
4037 to = from;
4038 from = target;
4039 }
4040 List<Type> commonSupers = superClosure(to, erasure(from));
4041 boolean giveWarning = commonSupers.isEmpty();
4042 // The arguments to the supers could be unified here to
4043 // get a more accurate analysis
4044 while (commonSupers.nonEmpty()) {
4045 Type t1 = asSuper(from, commonSupers.head.tsym);
4046 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
4047 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4048 return false;
4049 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
4050 commonSupers = commonSupers.tail;
4051 }
4052 if (giveWarning && !isReifiable(reverse ? from : to))
4053 warn.warn(LintCategory.UNCHECKED);
4054 if (!allowCovariantReturns)
4055 // reject if there is a common method signature with
4056 // incompatible return types.
4057 chk.checkCompatibleAbstracts(warn.pos(), from, to);
4058 return true;
4059 }
4061 private boolean sideCastFinal(Type from, Type to, Warner warn) {
4062 // We are casting from type $from$ to type $to$, which are
4063 // unrelated types one of which is final and the other of
4064 // which is an interface. This method
4065 // tries to reject a cast by transferring type parameters
4066 // from the final class to the interface.
4067 boolean reverse = false;
4068 Type target = to;
4069 if ((to.tsym.flags() & INTERFACE) == 0) {
4070 Assert.check((from.tsym.flags() & INTERFACE) != 0);
4071 reverse = true;
4072 to = from;
4073 from = target;
4074 }
4075 Assert.check((from.tsym.flags() & FINAL) != 0);
4076 Type t1 = asSuper(from, to.tsym);
4077 if (t1 == null) return false;
4078 Type t2 = to;
4079 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4080 return false;
4081 if (!allowCovariantReturns)
4082 // reject if there is a common method signature with
4083 // incompatible return types.
4084 chk.checkCompatibleAbstracts(warn.pos(), from, to);
4085 if (!isReifiable(target) &&
4086 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
4087 warn.warn(LintCategory.UNCHECKED);
4088 return true;
4089 }
4091 private boolean giveWarning(Type from, Type to) {
4092 List<Type> bounds = to.isCompound() ?
4093 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
4094 for (Type b : bounds) {
4095 Type subFrom = asSub(from, b.tsym);
4096 if (b.isParameterized() &&
4097 (!(isUnbounded(b) ||
4098 isSubtype(from, b) ||
4099 ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
4100 return true;
4101 }
4102 }
4103 return false;
4104 }
4106 private List<Type> superClosure(Type t, Type s) {
4107 List<Type> cl = List.nil();
4108 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
4109 if (isSubtype(s, erasure(l.head))) {
4110 cl = insert(cl, l.head);
4111 } else {
4112 cl = union(cl, superClosure(l.head, s));
4113 }
4114 }
4115 return cl;
4116 }
4118 private boolean containsTypeEquivalent(Type t, Type s) {
4119 return
4120 isSameType(t, s) || // shortcut
4121 containsType(t, s) && containsType(s, t);
4122 }
4124 // <editor-fold defaultstate="collapsed" desc="adapt">
4125 /**
4126 * Adapt a type by computing a substitution which maps a source
4127 * type to a target type.
4128 *
4129 * @param source the source type
4130 * @param target the target type
4131 * @param from the type variables of the computed substitution
4132 * @param to the types of the computed substitution.
4133 */
4134 public void adapt(Type source,
4135 Type target,
4136 ListBuffer<Type> from,
4137 ListBuffer<Type> to) throws AdaptFailure {
4138 new Adapter(from, to).adapt(source, target);
4139 }
4141 class Adapter extends SimpleVisitor<Void, Type> {
4143 ListBuffer<Type> from;
4144 ListBuffer<Type> to;
4145 Map<Symbol,Type> mapping;
4147 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
4148 this.from = from;
4149 this.to = to;
4150 mapping = new HashMap<Symbol,Type>();
4151 }
4153 public void adapt(Type source, Type target) throws AdaptFailure {
4154 visit(source, target);
4155 List<Type> fromList = from.toList();
4156 List<Type> toList = to.toList();
4157 while (!fromList.isEmpty()) {
4158 Type val = mapping.get(fromList.head.tsym);
4159 if (toList.head != val)
4160 toList.head = val;
4161 fromList = fromList.tail;
4162 toList = toList.tail;
4163 }
4164 }
4166 @Override
4167 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
4168 if (target.hasTag(CLASS))
4169 adaptRecursive(source.allparams(), target.allparams());
4170 return null;
4171 }
4173 @Override
4174 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
4175 if (target.hasTag(ARRAY))
4176 adaptRecursive(elemtype(source), elemtype(target));
4177 return null;
4178 }
4180 @Override
4181 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
4182 if (source.isExtendsBound())
4183 adaptRecursive(wildUpperBound(source), wildUpperBound(target));
4184 else if (source.isSuperBound())
4185 adaptRecursive(wildLowerBound(source), wildLowerBound(target));
4186 return null;
4187 }
4189 @Override
4190 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
4191 // Check to see if there is
4192 // already a mapping for $source$, in which case
4193 // the old mapping will be merged with the new
4194 Type val = mapping.get(source.tsym);
4195 if (val != null) {
4196 if (val.isSuperBound() && target.isSuperBound()) {
4197 val = isSubtype(wildLowerBound(val), wildLowerBound(target))
4198 ? target : val;
4199 } else if (val.isExtendsBound() && target.isExtendsBound()) {
4200 val = isSubtype(wildUpperBound(val), wildUpperBound(target))
4201 ? val : target;
4202 } else if (!isSameType(val, target)) {
4203 throw new AdaptFailure();
4204 }
4205 } else {
4206 val = target;
4207 from.append(source);
4208 to.append(target);
4209 }
4210 mapping.put(source.tsym, val);
4211 return null;
4212 }
4214 @Override
4215 public Void visitType(Type source, Type target) {
4216 return null;
4217 }
4219 private Set<TypePair> cache = new HashSet<TypePair>();
4221 private void adaptRecursive(Type source, Type target) {
4222 TypePair pair = new TypePair(source, target);
4223 if (cache.add(pair)) {
4224 try {
4225 visit(source, target);
4226 } finally {
4227 cache.remove(pair);
4228 }
4229 }
4230 }
4232 private void adaptRecursive(List<Type> source, List<Type> target) {
4233 if (source.length() == target.length()) {
4234 while (source.nonEmpty()) {
4235 adaptRecursive(source.head, target.head);
4236 source = source.tail;
4237 target = target.tail;
4238 }
4239 }
4240 }
4241 }
4243 public static class AdaptFailure extends RuntimeException {
4244 static final long serialVersionUID = -7490231548272701566L;
4245 }
4247 private void adaptSelf(Type t,
4248 ListBuffer<Type> from,
4249 ListBuffer<Type> to) {
4250 try {
4251 //if (t.tsym.type != t)
4252 adapt(t.tsym.type, t, from, to);
4253 } catch (AdaptFailure ex) {
4254 // Adapt should never fail calculating a mapping from
4255 // t.tsym.type to t as there can be no merge problem.
4256 throw new AssertionError(ex);
4257 }
4258 }
4259 // </editor-fold>
4261 /**
4262 * Rewrite all type variables (universal quantifiers) in the given
4263 * type to wildcards (existential quantifiers). This is used to
4264 * determine if a cast is allowed. For example, if high is true
4265 * and {@code T <: Number}, then {@code List<T>} is rewritten to
4266 * {@code List<? extends Number>}. Since {@code List<Integer> <:
4267 * List<? extends Number>} a {@code List<T>} can be cast to {@code
4268 * List<Integer>} with a warning.
4269 * @param t a type
4270 * @param high if true return an upper bound; otherwise a lower
4271 * bound
4272 * @param rewriteTypeVars only rewrite captured wildcards if false;
4273 * otherwise rewrite all type variables
4274 * @return the type rewritten with wildcards (existential
4275 * quantifiers) only
4276 */
4277 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4278 return new Rewriter(high, rewriteTypeVars).visit(t);
4279 }
4281 class Rewriter extends UnaryVisitor<Type> {
4283 boolean high;
4284 boolean rewriteTypeVars;
4286 Rewriter(boolean high, boolean rewriteTypeVars) {
4287 this.high = high;
4288 this.rewriteTypeVars = rewriteTypeVars;
4289 }
4291 @Override
4292 public Type visitClassType(ClassType t, Void s) {
4293 ListBuffer<Type> rewritten = new ListBuffer<Type>();
4294 boolean changed = false;
4295 for (Type arg : t.allparams()) {
4296 Type bound = visit(arg);
4297 if (arg != bound) {
4298 changed = true;
4299 }
4300 rewritten.append(bound);
4301 }
4302 if (changed)
4303 return subst(t.tsym.type,
4304 t.tsym.type.allparams(),
4305 rewritten.toList());
4306 else
4307 return t;
4308 }
4310 public Type visitType(Type t, Void s) {
4311 return t;
4312 }
4314 @Override
4315 public Type visitCapturedType(CapturedType t, Void s) {
4316 Type w_bound = t.wildcard.type;
4317 Type bound = w_bound.contains(t) ?
4318 erasure(w_bound) :
4319 visit(w_bound);
4320 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4321 }
4323 @Override
4324 public Type visitTypeVar(TypeVar t, Void s) {
4325 if (rewriteTypeVars) {
4326 Type bound = t.bound.contains(t) ?
4327 erasure(t.bound) :
4328 visit(t.bound);
4329 return rewriteAsWildcardType(bound, t, EXTENDS);
4330 } else {
4331 return t;
4332 }
4333 }
4335 @Override
4336 public Type visitWildcardType(WildcardType t, Void s) {
4337 Type bound2 = visit(t.type);
4338 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4339 }
4341 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4342 switch (bk) {
4343 case EXTENDS: return high ?
4344 makeExtendsWildcard(B(bound), formal) :
4345 makeExtendsWildcard(syms.objectType, formal);
4346 case SUPER: return high ?
4347 makeSuperWildcard(syms.botType, formal) :
4348 makeSuperWildcard(B(bound), formal);
4349 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4350 default:
4351 Assert.error("Invalid bound kind " + bk);
4352 return null;
4353 }
4354 }
4356 Type B(Type t) {
4357 while (t.hasTag(WILDCARD)) {
4358 WildcardType w = (WildcardType)t.unannotatedType();
4359 t = high ?
4360 w.getExtendsBound() :
4361 w.getSuperBound();
4362 if (t == null) {
4363 t = high ? syms.objectType : syms.botType;
4364 }
4365 }
4366 return t;
4367 }
4368 }
4371 /**
4372 * Create a wildcard with the given upper (extends) bound; create
4373 * an unbounded wildcard if bound is Object.
4374 *
4375 * @param bound the upper bound
4376 * @param formal the formal type parameter that will be
4377 * substituted by the wildcard
4378 */
4379 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4380 if (bound == syms.objectType) {
4381 return new WildcardType(syms.objectType,
4382 BoundKind.UNBOUND,
4383 syms.boundClass,
4384 formal);
4385 } else {
4386 return new WildcardType(bound,
4387 BoundKind.EXTENDS,
4388 syms.boundClass,
4389 formal);
4390 }
4391 }
4393 /**
4394 * Create a wildcard with the given lower (super) bound; create an
4395 * unbounded wildcard if bound is bottom (type of {@code null}).
4396 *
4397 * @param bound the lower bound
4398 * @param formal the formal type parameter that will be
4399 * substituted by the wildcard
4400 */
4401 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4402 if (bound.hasTag(BOT)) {
4403 return new WildcardType(syms.objectType,
4404 BoundKind.UNBOUND,
4405 syms.boundClass,
4406 formal);
4407 } else {
4408 return new WildcardType(bound,
4409 BoundKind.SUPER,
4410 syms.boundClass,
4411 formal);
4412 }
4413 }
4415 /**
4416 * A wrapper for a type that allows use in sets.
4417 */
4418 public static class UniqueType {
4419 public final Type type;
4420 final Types types;
4422 public UniqueType(Type type, Types types) {
4423 this.type = type;
4424 this.types = types;
4425 }
4427 public int hashCode() {
4428 return types.hashCode(type);
4429 }
4431 public boolean equals(Object obj) {
4432 return (obj instanceof UniqueType) &&
4433 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
4434 }
4436 public String toString() {
4437 return type.toString();
4438 }
4440 }
4441 // </editor-fold>
4443 // <editor-fold defaultstate="collapsed" desc="Visitors">
4444 /**
4445 * A default visitor for types. All visitor methods except
4446 * visitType are implemented by delegating to visitType. Concrete
4447 * subclasses must provide an implementation of visitType and can
4448 * override other methods as needed.
4449 *
4450 * @param <R> the return type of the operation implemented by this
4451 * visitor; use Void if no return type is needed.
4452 * @param <S> the type of the second argument (the first being the
4453 * type itself) of the operation implemented by this visitor; use
4454 * Void if a second argument is not needed.
4455 */
4456 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4457 final public R visit(Type t, S s) { return t.accept(this, s); }
4458 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
4459 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4460 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
4461 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
4462 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
4463 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
4464 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4465 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
4466 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
4467 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
4468 // Pretend annotations don't exist
4469 public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.unannotatedType(), s); }
4470 }
4472 /**
4473 * A default visitor for symbols. All visitor methods except
4474 * visitSymbol are implemented by delegating to visitSymbol. Concrete
4475 * subclasses must provide an implementation of visitSymbol and can
4476 * override other methods as needed.
4477 *
4478 * @param <R> the return type of the operation implemented by this
4479 * visitor; use Void if no return type is needed.
4480 * @param <S> the type of the second argument (the first being the
4481 * symbol itself) of the operation implemented by this visitor; use
4482 * Void if a second argument is not needed.
4483 */
4484 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4485 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
4486 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
4487 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
4488 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
4489 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
4490 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
4491 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
4492 }
4494 /**
4495 * A <em>simple</em> visitor for types. This visitor is simple as
4496 * captured wildcards, for-all types (generic methods), and
4497 * undetermined type variables (part of inference) are hidden.
4498 * Captured wildcards are hidden by treating them as type
4499 * variables and the rest are hidden by visiting their qtypes.
4500 *
4501 * @param <R> the return type of the operation implemented by this
4502 * visitor; use Void if no return type is needed.
4503 * @param <S> the type of the second argument (the first being the
4504 * type itself) of the operation implemented by this visitor; use
4505 * Void if a second argument is not needed.
4506 */
4507 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4508 @Override
4509 public R visitCapturedType(CapturedType t, S s) {
4510 return visitTypeVar(t, s);
4511 }
4512 @Override
4513 public R visitForAll(ForAll t, S s) {
4514 return visit(t.qtype, s);
4515 }
4516 @Override
4517 public R visitUndetVar(UndetVar t, S s) {
4518 return visit(t.qtype, s);
4519 }
4520 }
4522 /**
4523 * A plain relation on types. That is a 2-ary function on the
4524 * form Type × Type → Boolean.
4525 * <!-- In plain text: Type x Type -> Boolean -->
4526 */
4527 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4529 /**
4530 * A convenience visitor for implementing operations that only
4531 * require one argument (the type itself), that is, unary
4532 * operations.
4533 *
4534 * @param <R> the return type of the operation implemented by this
4535 * visitor; use Void if no return type is needed.
4536 */
4537 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4538 final public R visit(Type t) { return t.accept(this, null); }
4539 }
4541 /**
4542 * A visitor for implementing a mapping from types to types. The
4543 * default behavior of this class is to implement the identity
4544 * mapping (mapping a type to itself). This can be overridden in
4545 * subclasses.
4546 *
4547 * @param <S> the type of the second argument (the first being the
4548 * type itself) of this mapping; use Void if a second argument is
4549 * not needed.
4550 */
4551 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4552 final public Type visit(Type t) { return t.accept(this, null); }
4553 public Type visitType(Type t, S s) { return t; }
4554 }
4555 // </editor-fold>
4558 // <editor-fold defaultstate="collapsed" desc="Annotation support">
4560 public RetentionPolicy getRetention(Attribute.Compound a) {
4561 return getRetention(a.type.tsym);
4562 }
4564 public RetentionPolicy getRetention(Symbol sym) {
4565 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4566 Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4567 if (c != null) {
4568 Attribute value = c.member(names.value);
4569 if (value != null && value instanceof Attribute.Enum) {
4570 Name levelName = ((Attribute.Enum)value).value.name;
4571 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4572 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4573 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4574 else ;// /* fail soft */ throw new AssertionError(levelName);
4575 }
4576 }
4577 return vis;
4578 }
4579 // </editor-fold>
4581 // <editor-fold defaultstate="collapsed" desc="Signature Generation">
4583 public static abstract class SignatureGenerator {
4585 private final Types types;
4587 protected abstract void append(char ch);
4588 protected abstract void append(byte[] ba);
4589 protected abstract void append(Name name);
4590 protected void classReference(ClassSymbol c) { /* by default: no-op */ }
4592 protected SignatureGenerator(Types types) {
4593 this.types = types;
4594 }
4596 /**
4597 * Assemble signature of given type in string buffer.
4598 */
4599 public void assembleSig(Type type) {
4600 type = type.unannotatedType();
4601 switch (type.getTag()) {
4602 case BYTE:
4603 append('B');
4604 break;
4605 case SHORT:
4606 append('S');
4607 break;
4608 case CHAR:
4609 append('C');
4610 break;
4611 case INT:
4612 append('I');
4613 break;
4614 case LONG:
4615 append('J');
4616 break;
4617 case FLOAT:
4618 append('F');
4619 break;
4620 case DOUBLE:
4621 append('D');
4622 break;
4623 case BOOLEAN:
4624 append('Z');
4625 break;
4626 case VOID:
4627 append('V');
4628 break;
4629 case CLASS:
4630 append('L');
4631 assembleClassSig(type);
4632 append(';');
4633 break;
4634 case ARRAY:
4635 ArrayType at = (ArrayType) type;
4636 append('[');
4637 assembleSig(at.elemtype);
4638 break;
4639 case METHOD:
4640 MethodType mt = (MethodType) type;
4641 append('(');
4642 assembleSig(mt.argtypes);
4643 append(')');
4644 assembleSig(mt.restype);
4645 if (hasTypeVar(mt.thrown)) {
4646 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
4647 append('^');
4648 assembleSig(l.head);
4649 }
4650 }
4651 break;
4652 case WILDCARD: {
4653 Type.WildcardType ta = (Type.WildcardType) type;
4654 switch (ta.kind) {
4655 case SUPER:
4656 append('-');
4657 assembleSig(ta.type);
4658 break;
4659 case EXTENDS:
4660 append('+');
4661 assembleSig(ta.type);
4662 break;
4663 case UNBOUND:
4664 append('*');
4665 break;
4666 default:
4667 throw new AssertionError(ta.kind);
4668 }
4669 break;
4670 }
4671 case TYPEVAR:
4672 append('T');
4673 append(type.tsym.name);
4674 append(';');
4675 break;
4676 case FORALL:
4677 Type.ForAll ft = (Type.ForAll) type;
4678 assembleParamsSig(ft.tvars);
4679 assembleSig(ft.qtype);
4680 break;
4681 default:
4682 throw new AssertionError("typeSig " + type.getTag());
4683 }
4684 }
4686 public boolean hasTypeVar(List<Type> l) {
4687 while (l.nonEmpty()) {
4688 if (l.head.hasTag(TypeTag.TYPEVAR)) {
4689 return true;
4690 }
4691 l = l.tail;
4692 }
4693 return false;
4694 }
4696 public void assembleClassSig(Type type) {
4697 type = type.unannotatedType();
4698 ClassType ct = (ClassType) type;
4699 ClassSymbol c = (ClassSymbol) ct.tsym;
4700 classReference(c);
4701 Type outer = ct.getEnclosingType();
4702 if (outer.allparams().nonEmpty()) {
4703 boolean rawOuter =
4704 c.owner.kind == Kinds.MTH || // either a local class
4705 c.name == types.names.empty; // or anonymous
4706 assembleClassSig(rawOuter
4707 ? types.erasure(outer)
4708 : outer);
4709 append(rawOuter ? '$' : '.');
4710 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
4711 append(rawOuter
4712 ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
4713 : c.name);
4714 } else {
4715 append(externalize(c.flatname));
4716 }
4717 if (ct.getTypeArguments().nonEmpty()) {
4718 append('<');
4719 assembleSig(ct.getTypeArguments());
4720 append('>');
4721 }
4722 }
4724 public void assembleParamsSig(List<Type> typarams) {
4725 append('<');
4726 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
4727 Type.TypeVar tvar = (Type.TypeVar) ts.head;
4728 append(tvar.tsym.name);
4729 List<Type> bounds = types.getBounds(tvar);
4730 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
4731 append(':');
4732 }
4733 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
4734 append(':');
4735 assembleSig(l.head);
4736 }
4737 }
4738 append('>');
4739 }
4741 private void assembleSig(List<Type> types) {
4742 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
4743 assembleSig(ts.head);
4744 }
4745 }
4746 }
4747 // </editor-fold>
4748 }