1 /*
2 * Copyright (c) 2003, 2024, 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 */
25
26 package com.sun.tools.javac.code;
27
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.Optional;
34 import java.util.Set;
35 import java.util.WeakHashMap;
36 import java.util.function.BiPredicate;
37 import java.util.function.Function;
38 import java.util.function.Predicate;
39 import java.util.stream.Collector;
40
41 import javax.tools.JavaFileObject;
42
43 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
44 import com.sun.tools.javac.code.Lint.LintCategory;
45 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
46 import com.sun.tools.javac.code.TypeMetadata.Annotations;
47 import com.sun.tools.javac.comp.AttrContext;
48 import com.sun.tools.javac.comp.Check;
49 import com.sun.tools.javac.comp.Enter;
50 import com.sun.tools.javac.comp.Env;
51 import com.sun.tools.javac.jvm.ClassFile;
52 import com.sun.tools.javac.util.*;
53
54 import static com.sun.tools.javac.code.BoundKind.*;
55 import static com.sun.tools.javac.code.Flags.*;
56 import static com.sun.tools.javac.code.Kinds.Kind.*;
57 import static com.sun.tools.javac.code.Scope.*;
58 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
59 import static com.sun.tools.javac.code.Symbol.*;
60 import static com.sun.tools.javac.code.Type.*;
61 import static com.sun.tools.javac.code.TypeTag.*;
62 import static com.sun.tools.javac.jvm.ClassFile.externalize;
63 import static com.sun.tools.javac.main.Option.DOE;
64
65 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
66
67 /**
68 * Utility class containing various operations on types.
69 *
70 * <p>Unless other names are more illustrative, the following naming
71 * conventions should be observed in this file:
72 *
73 * <dl>
74 * <dt>t</dt>
75 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
76 * <dt>s</dt>
77 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
78 * <dt>ts</dt>
79 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
80 * <dt>ss</dt>
81 * <dd>A second list of types should be named ss.</dd>
82 * </dl>
83 *
84 * <p><b>This is NOT part of any supported API.
85 * If you write code that depends on this, you do so at your own risk.
86 * This code and its internal interfaces are subject to change or
87 * deletion without notice.</b>
88 */
89 public class Types {
90 protected static final Context.Key<Types> typesKey = new Context.Key<>();
91
92 final Symtab syms;
93 final JavacMessages messages;
94 final Names names;
95 final Check chk;
96 final Enter enter;
97 JCDiagnostic.Factory diags;
98 List<Warner> warnStack = List.nil();
99 final Name capturedName;
100
101 public final Warner noWarnings;
102 public final boolean dumpStacktraceOnError;
103
104 // <editor-fold defaultstate="collapsed" desc="Instantiating">
105 public static Types instance(Context context) {
106 Types instance = context.get(typesKey);
107 if (instance == null)
108 instance = new Types(context);
109 return instance;
110 }
111
112 @SuppressWarnings("this-escape")
113 protected Types(Context context) {
114 context.put(typesKey, this);
115 syms = Symtab.instance(context);
116 names = Names.instance(context);
117 Source source = Source.instance(context);
118 chk = Check.instance(context);
119 enter = Enter.instance(context);
120 capturedName = names.fromString("<captured wildcard>");
121 messages = JavacMessages.instance(context);
122 diags = JCDiagnostic.Factory.instance(context);
123 noWarnings = new Warner(null);
124 Options options = Options.instance(context);
125 dumpStacktraceOnError = options.isSet("dev") || options.isSet(DOE);
126 }
127 // </editor-fold>
128
129 // <editor-fold defaultstate="collapsed" desc="bounds">
130 /**
131 * Get a wildcard's upper bound, returning non-wildcards unchanged.
132 * @param t a type argument, either a wildcard or a type
133 */
134 public Type wildUpperBound(Type t) {
135 if (t.hasTag(WILDCARD)) {
136 WildcardType w = (WildcardType) t;
137 if (w.isSuperBound())
138 return w.bound == null ? syms.objectType : w.bound.getUpperBound();
139 else
140 return wildUpperBound(w.type);
141 }
142 else return t;
143 }
144
145 /**
146 * Get a capture variable's upper bound, returning other types unchanged.
147 * @param t a type
148 */
149 public Type cvarUpperBound(Type t) {
150 if (t.hasTag(TYPEVAR)) {
151 TypeVar v = (TypeVar) t;
152 return v.isCaptured() ? cvarUpperBound(v.getUpperBound()) : v;
153 }
154 else return t;
155 }
156
157 /**
158 * Get a wildcard's lower bound, returning non-wildcards unchanged.
159 * @param t a type argument, either a wildcard or a type
160 */
161 public Type wildLowerBound(Type t) {
162 if (t.hasTag(WILDCARD)) {
163 WildcardType w = (WildcardType) t;
164 return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
165 }
166 else return t;
167 }
168
169 /**
170 * Get a capture variable's lower bound, returning other types unchanged.
171 * @param t a type
172 */
173 public Type cvarLowerBound(Type t) {
174 if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
175 return cvarLowerBound(t.getLowerBound());
176 }
177 else return t;
178 }
179
180 /**
181 * Recursively skip type-variables until a class/array type is found; capture conversion is then
182 * (optionally) applied to the resulting type. This is useful for i.e. computing a site that is
183 * suitable for a method lookup.
184 */
185 public Type skipTypeVars(Type site, boolean capture) {
186 while (site.hasTag(TYPEVAR)) {
187 site = site.getUpperBound();
188 }
189 return capture ? capture(site) : site;
190 }
191 // </editor-fold>
192
193 // <editor-fold defaultstate="collapsed" desc="projections">
194
195 /**
196 * A projection kind. See {@link TypeProjection}
197 */
198 enum ProjectionKind {
199 UPWARDS() {
200 @Override
201 ProjectionKind complement() {
202 return DOWNWARDS;
203 }
204 },
205 DOWNWARDS() {
206 @Override
207 ProjectionKind complement() {
208 return UPWARDS;
209 }
210 };
211
212 abstract ProjectionKind complement();
213 }
214
215 /**
216 * This visitor performs upwards and downwards projections on types.
217 *
218 * A projection is defined as a function that takes a type T, a set of type variables V and that
219 * produces another type S.
220 *
221 * An upwards projection maps a type T into a type S such that (i) T has no variables in V,
222 * and (ii) S is an upper bound of T.
223 *
224 * A downwards projection maps a type T into a type S such that (i) T has no variables in V,
225 * and (ii) S is a lower bound of T.
226 *
227 * Note that projections are only allowed to touch variables in V. Therefore, it is possible for
228 * a projection to leave its input type unchanged if it does not contain any variables in V.
229 *
230 * Moreover, note that while an upwards projection is always defined (every type as an upper bound),
231 * a downwards projection is not always defined.
232 *
233 * Examples:
234 *
235 * {@code upwards(List<#CAP1>, [#CAP1]) = List<? extends String>, where #CAP1 <: String }
236 * {@code downwards(List<#CAP2>, [#CAP2]) = List<? super String>, where #CAP2 :> String }
237 * {@code upwards(List<#CAP1>, [#CAP2]) = List<#CAP1> }
238 * {@code downwards(List<#CAP1>, [#CAP1]) = not defined }
239 */
240 class TypeProjection extends TypeMapping<ProjectionKind> {
241
242 List<Type> vars;
243 Set<Type> seen = new HashSet<>();
244
245 public TypeProjection(List<Type> vars) {
246 this.vars = vars;
247 }
248
249 @Override
250 public Type visitClassType(ClassType t, ProjectionKind pkind) {
251 if (t.isCompound()) {
252 List<Type> components = directSupertypes(t);
253 List<Type> components1 = components.map(c -> c.map(this, pkind));
254 if (components == components1) return t;
255 else return makeIntersectionType(components1);
256 } else {
257 Type outer = t.getEnclosingType();
258 Type outer1 = visit(outer, pkind);
259 List<Type> typarams = t.getTypeArguments();
260 List<Type> formals = t.tsym.type.getTypeArguments();
261 ListBuffer<Type> typarams1 = new ListBuffer<>();
262 boolean changed = false;
263 for (Type actual : typarams) {
264 Type t2 = mapTypeArgument(t, formals.head.getUpperBound(), actual, pkind);
265 if (t2.hasTag(BOT)) {
266 //not defined
267 return syms.botType;
268 }
269 typarams1.add(t2);
270 changed |= actual != t2;
271 formals = formals.tail;
272 }
273 if (outer1 == outer && !changed) return t;
274 else return new ClassType(outer1, typarams1.toList(), t.tsym, t.getMetadata()) {
275 @Override
276 protected boolean needsStripping() {
277 return true;
278 }
279 };
280 }
281 }
282
283 @Override
284 public Type visitArrayType(ArrayType t, ProjectionKind s) {
285 Type elemtype = t.elemtype;
286 Type elemtype1 = visit(elemtype, s);
287 if (elemtype1 == elemtype) {
288 return t;
289 } else if (elemtype1.hasTag(BOT)) {
290 //undefined
291 return syms.botType;
292 } else {
293 return new ArrayType(elemtype1, t.tsym, t.metadata) {
294 @Override
295 protected boolean needsStripping() {
296 return true;
297 }
298 };
299 }
300 }
301
302 @Override
303 public Type visitTypeVar(TypeVar t, ProjectionKind pkind) {
304 if (vars.contains(t)) {
305 if (seen.add(t)) {
306 try {
307 final Type bound;
308 switch (pkind) {
309 case UPWARDS:
310 bound = t.getUpperBound();
311 break;
312 case DOWNWARDS:
313 bound = (t.getLowerBound() == null) ?
314 syms.botType :
315 t.getLowerBound();
316 break;
317 default:
318 Assert.error();
319 return null;
320 }
321 return bound.map(this, pkind);
322 } finally {
323 seen.remove(t);
324 }
325 } else {
326 //cycle
327 return pkind == ProjectionKind.UPWARDS ?
328 syms.objectType : syms.botType;
329 }
330 } else {
331 return t;
332 }
333 }
334
335 private Type mapTypeArgument(Type site, Type declaredBound, Type t, ProjectionKind pkind) {
336 return t.containsAny(vars) ?
337 t.map(new TypeArgumentProjection(site, declaredBound), pkind) :
338 t;
339 }
340
341 class TypeArgumentProjection extends TypeMapping<ProjectionKind> {
342
343 Type site;
344 Type declaredBound;
345
346 TypeArgumentProjection(Type site, Type declaredBound) {
347 this.site = site;
348 this.declaredBound = declaredBound;
349 }
350
351 @Override
352 public Type visitType(Type t, ProjectionKind pkind) {
353 //type argument is some type containing restricted vars
354 if (pkind == ProjectionKind.DOWNWARDS) {
355 //not defined
356 return syms.botType;
357 }
358 Type upper = t.map(TypeProjection.this, ProjectionKind.UPWARDS);
359 Type lower = t.map(TypeProjection.this, ProjectionKind.DOWNWARDS);
360 List<Type> formals = site.tsym.type.getTypeArguments();
361 BoundKind bk;
362 Type bound;
363 if (!isSameType(upper, syms.objectType) &&
364 (declaredBound.containsAny(formals) ||
365 !isSubtype(declaredBound, upper))) {
366 bound = upper;
367 bk = EXTENDS;
368 } else if (!lower.hasTag(BOT)) {
369 bound = lower;
370 bk = SUPER;
371 } else {
372 bound = syms.objectType;
373 bk = UNBOUND;
374 }
375 return makeWildcard(bound, bk);
376 }
377
378 @Override
379 public Type visitWildcardType(WildcardType wt, ProjectionKind pkind) {
380 //type argument is some wildcard whose bound contains restricted vars
381 Type bound = syms.botType;
382 BoundKind bk = wt.kind;
383 switch (wt.kind) {
384 case EXTENDS:
385 bound = wt.type.map(TypeProjection.this, pkind);
386 if (bound.hasTag(BOT)) {
387 return syms.botType;
388 }
389 break;
390 case SUPER:
391 bound = wt.type.map(TypeProjection.this, pkind.complement());
392 if (bound.hasTag(BOT)) {
393 bound = syms.objectType;
394 bk = UNBOUND;
395 }
396 break;
397 }
398 return makeWildcard(bound, bk);
399 }
400
401 private Type makeWildcard(Type bound, BoundKind bk) {
402 return new WildcardType(bound, bk, syms.boundClass) {
403 @Override
404 protected boolean needsStripping() {
405 return true;
406 }
407 };
408 }
409 }
410 }
411
412 /**
413 * Computes an upward projection of given type, and vars. See {@link TypeProjection}.
414 *
415 * @param t the type to be projected
416 * @param vars the set of type variables to be mapped
417 * @return the type obtained as result of the projection
418 */
419 public Type upward(Type t, List<Type> vars) {
420 return t.map(new TypeProjection(vars), ProjectionKind.UPWARDS);
421 }
422
423 /**
424 * Computes the set of captured variables mentioned in a given type. See {@link CaptureScanner}.
425 * This routine is typically used to computed the input set of variables to be used during
426 * an upwards projection (see {@link Types#upward(Type, List)}).
427 *
428 * @param t the type where occurrences of captured variables have to be found
429 * @return the set of captured variables found in t
430 */
431 public List<Type> captures(Type t) {
432 CaptureScanner cs = new CaptureScanner();
433 Set<Type> captures = new HashSet<>();
434 cs.visit(t, captures);
435 return List.from(captures);
436 }
437
438 /**
439 * This visitor scans a type recursively looking for occurrences of captured type variables.
440 */
441 class CaptureScanner extends SimpleVisitor<Void, Set<Type>> {
442
443 @Override
444 public Void visitType(Type t, Set<Type> types) {
445 return null;
446 }
447
448 @Override
449 public Void visitClassType(ClassType t, Set<Type> seen) {
450 if (t.isCompound()) {
451 directSupertypes(t).forEach(s -> visit(s, seen));
452 } else {
453 t.allparams().forEach(ta -> visit(ta, seen));
454 }
455 return null;
456 }
457
458 @Override
459 public Void visitArrayType(ArrayType t, Set<Type> seen) {
460 return visit(t.elemtype, seen);
461 }
462
463 @Override
464 public Void visitWildcardType(WildcardType t, Set<Type> seen) {
465 visit(t.type, seen);
466 return null;
467 }
468
469 @Override
470 public Void visitTypeVar(TypeVar t, Set<Type> seen) {
471 if ((t.tsym.flags() & Flags.SYNTHETIC) != 0 && seen.add(t)) {
472 visit(t.getUpperBound(), seen);
473 }
474 return null;
475 }
476
477 @Override
478 public Void visitCapturedType(CapturedType t, Set<Type> seen) {
479 if (seen.add(t)) {
480 visit(t.getUpperBound(), seen);
481 visit(t.getLowerBound(), seen);
482 }
483 return null;
484 }
485 }
486
487 // </editor-fold>
488
489 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
490 /**
491 * Checks that all the arguments to a class are unbounded
492 * wildcards or something else that doesn't make any restrictions
493 * on the arguments. If a class isUnbounded, a raw super- or
494 * subclass can be cast to it without a warning.
495 * @param t a type
496 * @return true iff the given type is unbounded or raw
497 */
498 public boolean isUnbounded(Type t) {
499 return isUnbounded.visit(t);
500 }
501 // where
502 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
503
504 public Boolean visitType(Type t, Void ignored) {
505 return true;
506 }
507
508 @Override
509 public Boolean visitClassType(ClassType t, Void ignored) {
510 List<Type> parms = t.tsym.type.allparams();
511 List<Type> args = t.allparams();
512 while (parms.nonEmpty()) {
513 WildcardType unb = new WildcardType(syms.objectType,
514 BoundKind.UNBOUND,
515 syms.boundClass,
516 (TypeVar)parms.head);
517 if (!containsType(args.head, unb))
518 return false;
519 parms = parms.tail;
520 args = args.tail;
521 }
522 return true;
523 }
524 };
525 // </editor-fold>
526
527 // <editor-fold defaultstate="collapsed" desc="asSub">
528 /**
529 * Return the least specific subtype of t that starts with symbol
530 * sym. If none exists, return null. The least specific subtype
531 * is determined as follows:
532 *
533 * <p>If there is exactly one parameterized instance of sym that is a
534 * subtype of t, that parameterized instance is returned.<br>
535 * Otherwise, if the plain type or raw type `sym' is a subtype of
536 * type t, the type `sym' itself is returned. Otherwise, null is
537 * returned.
538 */
539 public Type asSub(Type t, Symbol sym) {
540 return asSub.visit(t, sym);
541 }
542 // where
543 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
544
545 public Type visitType(Type t, Symbol sym) {
546 return null;
547 }
548
549 @Override
550 public Type visitClassType(ClassType t, Symbol sym) {
551 if (t.tsym == sym)
552 return t;
553 Type base = asSuper(sym.type, t.tsym);
554 if (base == null)
555 return null;
556 ListBuffer<Type> from = new ListBuffer<>();
557 ListBuffer<Type> to = new ListBuffer<>();
558 try {
559 adapt(base, t, from, to);
560 } catch (AdaptFailure ex) {
561 return null;
562 }
563 Type res = subst(sym.type, from.toList(), to.toList());
564 if (!isSubtype(res, t))
565 return null;
566 ListBuffer<Type> openVars = new ListBuffer<>();
567 for (List<Type> l = sym.type.allparams();
568 l.nonEmpty(); l = l.tail)
569 if (res.contains(l.head) && !t.contains(l.head))
570 openVars.append(l.head);
571 if (openVars.nonEmpty()) {
572 if (t.isRaw()) {
573 // The subtype of a raw type is raw
574 res = erasure(res);
575 } else {
576 // Unbound type arguments default to ?
577 List<Type> opens = openVars.toList();
578 ListBuffer<Type> qs = new ListBuffer<>();
579 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
580 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND,
581 syms.boundClass, (TypeVar) iter.head));
582 }
583 res = subst(res, opens, qs.toList());
584 }
585 }
586 return res;
587 }
588
589 @Override
590 public Type visitErrorType(ErrorType t, Symbol sym) {
591 return t;
592 }
593 };
594 // </editor-fold>
595
596 // <editor-fold defaultstate="collapsed" desc="isConvertible">
597 /**
598 * Is t a subtype of or convertible via boxing/unboxing
599 * conversion to s?
600 */
601 public boolean isConvertible(Type t, Type s, Warner warn) {
602 if (t.hasTag(ERROR)) {
603 return true;
604 }
605 boolean tPrimitive = t.isPrimitive();
606 boolean sPrimitive = s.isPrimitive();
607 if (tPrimitive == sPrimitive) {
608 return isSubtypeUnchecked(t, s, warn);
609 }
610 boolean tUndet = t.hasTag(UNDETVAR);
611 boolean sUndet = s.hasTag(UNDETVAR);
612
613 if (tUndet || sUndet) {
614 return tUndet ?
615 isSubtype(t, boxedTypeOrType(s)) :
616 isSubtype(boxedTypeOrType(t), s);
617 }
618
619 return tPrimitive
620 ? isSubtype(boxedClass(t).type, s)
621 : isSubtype(unboxedType(t), s);
622 }
623
624 /**
625 * Is t a subtype of or convertible via boxing/unboxing
626 * conversions to s?
627 */
628 public boolean isConvertible(Type t, Type s) {
629 return isConvertible(t, s, noWarnings);
630 }
631 // </editor-fold>
632
633 // <editor-fold defaultstate="collapsed" desc="findSam">
634
635 /**
636 * Exception used to report a function descriptor lookup failure. The exception
637 * wraps a diagnostic that can be used to generate more details error
638 * messages.
639 */
640 public static class FunctionDescriptorLookupError extends CompilerInternalException {
641 private static final long serialVersionUID = 0;
642
643 transient JCDiagnostic diagnostic;
644
645 FunctionDescriptorLookupError(boolean dumpStackTraceOnError) {
646 super(dumpStackTraceOnError);
647 this.diagnostic = null;
648 }
649
650 FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
651 this.diagnostic = diag;
652 return this;
653 }
654
655 public JCDiagnostic getDiagnostic() {
656 return diagnostic;
657 }
658 }
659
660 /**
661 * A cache that keeps track of function descriptors associated with given
662 * functional interfaces.
663 */
664 class DescriptorCache {
665
666 private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>();
667
668 class FunctionDescriptor {
669 Symbol descSym;
670
671 FunctionDescriptor(Symbol descSym) {
672 this.descSym = descSym;
673 }
674
675 public Symbol getSymbol() {
676 return descSym;
677 }
678
679 public Type getType(Type site) {
680 site = removeWildcards(site);
681 if (site.isIntersection()) {
682 IntersectionClassType ict = (IntersectionClassType)site;
683 for (Type component : ict.getExplicitComponents()) {
684 if (!chk.checkValidGenericType(component)) {
685 //if the inferred functional interface type is not well-formed,
686 //or if it's not a subtype of the original target, issue an error
687 throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
688 }
689 }
690 } else {
691 if (!chk.checkValidGenericType(site)) {
692 //if the inferred functional interface type is not well-formed,
693 //or if it's not a subtype of the original target, issue an error
694 throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
695 }
696 }
697 return memberType(site, descSym);
698 }
699 }
700
701 class Entry {
702 final FunctionDescriptor cachedDescRes;
703 final int prevMark;
704
705 public Entry(FunctionDescriptor cachedDescRes,
706 int prevMark) {
707 this.cachedDescRes = cachedDescRes;
708 this.prevMark = prevMark;
709 }
710
711 boolean matches(int mark) {
712 return this.prevMark == mark;
713 }
714 }
715
716 FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
717 Entry e = _map.get(origin);
718 CompoundScope members = membersClosure(origin.type, false);
719 if (e == null ||
720 !e.matches(members.getMark())) {
721 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
722 _map.put(origin, new Entry(descRes, members.getMark()));
723 return descRes;
724 }
725 else {
726 return e.cachedDescRes;
727 }
728 }
729
730 /**
731 * Compute the function descriptor associated with a given functional interface
732 */
733 public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
734 CompoundScope membersCache) throws FunctionDescriptorLookupError {
735 if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0 || origin.isSealed()) {
736 //t must be an interface
737 throw failure("not.a.functional.intf", origin);
738 }
739
740 final ListBuffer<Symbol> abstracts = new ListBuffer<>();
741 for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) {
742 Type mtype = memberType(origin.type, sym);
743 if (abstracts.isEmpty()) {
744 abstracts.append(sym);
745 } else if ((sym.name == abstracts.first().name &&
746 overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
747 if (!abstracts.stream().filter(msym -> msym.owner.isSubClass(sym.enclClass(), Types.this))
748 .map(msym -> memberType(origin.type, msym))
749 .anyMatch(abstractMType -> isSubSignature(abstractMType, mtype))) {
750 abstracts.append(sym);
751 }
752 } else {
753 //the target method(s) should be the only abstract members of t
754 throw failure("not.a.functional.intf.1", origin,
755 diags.fragment(Fragments.IncompatibleAbstracts(Kinds.kindName(origin), origin)));
756 }
757 }
758 if (abstracts.isEmpty()) {
759 //t must define a suitable non-generic method
760 throw failure("not.a.functional.intf.1", origin,
761 diags.fragment(Fragments.NoAbstracts(Kinds.kindName(origin), origin)));
762 } else if (abstracts.size() == 1) {
763 return new FunctionDescriptor(abstracts.first());
764 } else { // size > 1
765 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
766 if (descRes == null) {
767 //we can get here if the functional interface is ill-formed
768 ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
769 for (Symbol desc : abstracts) {
770 String key = desc.type.getThrownTypes().nonEmpty() ?
771 "descriptor.throws" : "descriptor";
772 descriptors.append(diags.fragment(key, desc.name,
773 desc.type.getParameterTypes(),
774 desc.type.getReturnType(),
775 desc.type.getThrownTypes()));
776 }
777 JCDiagnostic msg =
778 diags.fragment(Fragments.IncompatibleDescsInFunctionalIntf(Kinds.kindName(origin),
779 origin));
780 JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
781 new JCDiagnostic.MultilineDiagnostic(msg, descriptors.toList());
782 throw failure(incompatibleDescriptors);
783 }
784 return descRes;
785 }
786 }
787
788 /**
789 * Compute a synthetic type for the target descriptor given a list
790 * of override-equivalent methods in the functional interface type.
791 * The resulting method type is a method type that is override-equivalent
792 * and return-type substitutable with each method in the original list.
793 */
794 private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
795 return mergeAbstracts(methodSyms, origin.type, false)
796 .map(bestSoFar -> new FunctionDescriptor(bestSoFar.baseSymbol()) {
797 @Override
798 public Type getType(Type origin) {
799 Type mt = memberType(origin, getSymbol());
800 return createMethodTypeWithThrown(mt, bestSoFar.type.getThrownTypes());
801 }
802 }).orElse(null);
803 }
804
805 FunctionDescriptorLookupError failure(String msg, Object... args) {
806 return failure(diags.fragment(msg, args));
807 }
808
809 FunctionDescriptorLookupError failure(JCDiagnostic diag) {
810 return new FunctionDescriptorLookupError(Types.this.dumpStacktraceOnError).setMessage(diag);
811 }
812 }
813
814 private DescriptorCache descCache = new DescriptorCache();
815
816 /**
817 * Find the method descriptor associated to this class symbol - if the
818 * symbol 'origin' is not a functional interface, an exception is thrown.
819 */
820 public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
821 return descCache.get(origin).getSymbol();
822 }
823
824 /**
825 * Find the type of the method descriptor associated to this class symbol -
826 * if the symbol 'origin' is not a functional interface, an exception is thrown.
827 */
828 public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
829 return descCache.get(origin.tsym).getType(origin);
830 }
831
832 /**
833 * Is given type a functional interface?
834 */
835 public boolean isFunctionalInterface(TypeSymbol tsym) {
836 try {
837 findDescriptorSymbol(tsym);
838 return true;
839 } catch (FunctionDescriptorLookupError ex) {
840 return false;
841 }
842 }
843
844 public boolean isFunctionalInterface(Type site) {
845 try {
846 findDescriptorType(site);
847 return true;
848 } catch (FunctionDescriptorLookupError ex) {
849 return false;
850 }
851 }
852
853 public Type removeWildcards(Type site) {
854 if (site.getTypeArguments().stream().anyMatch(t -> t.hasTag(WILDCARD))) {
855 //compute non-wildcard parameterization - JLS 9.9
856 List<Type> actuals = site.getTypeArguments();
857 List<Type> formals = site.tsym.type.getTypeArguments();
858 ListBuffer<Type> targs = new ListBuffer<>();
859 for (Type formal : formals) {
860 Type actual = actuals.head;
861 Type bound = formal.getUpperBound();
862 if (actuals.head.hasTag(WILDCARD)) {
863 WildcardType wt = (WildcardType)actual;
864 //check that bound does not contain other formals
865 if (bound.containsAny(formals)) {
866 targs.add(wt.type);
867 } else {
868 //compute new type-argument based on declared bound and wildcard bound
869 switch (wt.kind) {
870 case UNBOUND:
871 targs.add(bound);
872 break;
873 case EXTENDS:
874 targs.add(glb(bound, wt.type));
875 break;
876 case SUPER:
877 targs.add(wt.type);
878 break;
879 default:
880 Assert.error("Cannot get here!");
881 }
882 }
883 } else {
884 //not a wildcard - the new type argument remains unchanged
885 targs.add(actual);
886 }
887 actuals = actuals.tail;
888 }
889 return subst(site.tsym.type, formals, targs.toList());
890 } else {
891 return site;
892 }
893 }
894
895 /**
896 * Create a symbol for a class that implements a given functional interface
897 * and overrides its functional descriptor. This routine is used for two
898 * main purposes: (i) checking well-formedness of a functional interface;
899 * (ii) perform functional interface bridge calculation.
900 */
901 public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, Type target, long cflags) {
902 if (target == null || target == syms.unknownType) {
903 return null;
904 }
905 Symbol descSym = findDescriptorSymbol(target.tsym);
906 Type descType = findDescriptorType(target);
907 ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
908 csym.completer = Completer.NULL_COMPLETER;
909 csym.members_field = WriteableScope.create(csym);
910 MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
911 csym.members_field.enter(instDescSym);
912 Type.ClassType ctype = new Type.ClassType(Type.noType, List.nil(), csym);
913 ctype.supertype_field = syms.objectType;
914 ctype.interfaces_field = target.isIntersection() ?
915 directSupertypes(target) :
916 List.of(target);
917 csym.type = ctype;
918 csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
919 return csym;
920 }
921
922 /**
923 * Find the minimal set of methods that are overridden by the functional
924 * descriptor in 'origin'. All returned methods are assumed to have different
925 * erased signatures.
926 */
927 public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
928 Assert.check(isFunctionalInterface(origin));
929 Symbol descSym = findDescriptorSymbol(origin);
930 CompoundScope members = membersClosure(origin.type, false);
931 ListBuffer<Symbol> overridden = new ListBuffer<>();
932 outer: for (Symbol m2 : members.getSymbolsByName(descSym.name, bridgeFilter)) {
933 if (m2 == descSym) continue;
934 else if (descSym.overrides(m2, origin, Types.this, false)) {
935 for (Symbol m3 : overridden) {
936 if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
937 (m3.overrides(m2, origin, Types.this, false) &&
938 (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
939 (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
940 continue outer;
941 }
942 }
943 overridden.add(m2);
944 }
945 }
946 return overridden.toList();
947 }
948 //where
949 // Use anonymous class instead of lambda expression intentionally,
950 // because the variable `names` has modifier: final.
951 private Predicate<Symbol> bridgeFilter = new Predicate<Symbol>() {
952 public boolean test(Symbol t) {
953 return t.kind == MTH &&
954 t.name != names.init &&
955 t.name != names.clinit &&
956 (t.flags() & SYNTHETIC) == 0;
957 }
958 };
959
960 private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
961 //a symbol will be completed from a classfile if (a) symbol has
962 //an associated file object with CLASS kind and (b) the symbol has
963 //not been entered
964 if (origin.classfile != null &&
965 origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
966 enter.getEnv(origin) == null) {
967 return false;
968 }
969 if (origin == s) {
970 return true;
971 }
972 for (Type t : interfaces(origin.type)) {
973 if (pendingBridges((ClassSymbol)t.tsym, s)) {
974 return true;
975 }
976 }
977 return false;
978 }
979 // </editor-fold>
980
981 /**
982 * Scope filter used to skip methods that should be ignored (such as methods
983 * overridden by j.l.Object) during function interface conversion interface check
984 */
985 class DescriptorFilter implements Predicate<Symbol> {
986
987 TypeSymbol origin;
988
989 DescriptorFilter(TypeSymbol origin) {
990 this.origin = origin;
991 }
992
993 @Override
994 public boolean test(Symbol sym) {
995 return sym.kind == MTH &&
996 (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
997 !overridesObjectMethod(origin, sym) &&
998 (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
999 }
1000 }
1001
1002 // <editor-fold defaultstate="collapsed" desc="isSubtype">
1003 /**
1004 * Is t an unchecked subtype of s?
1005 */
1006 public boolean isSubtypeUnchecked(Type t, Type s) {
1007 return isSubtypeUnchecked(t, s, noWarnings);
1008 }
1009 /**
1010 * Is t an unchecked subtype of s?
1011 */
1012 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
1013 boolean result = isSubtypeUncheckedInternal(t, s, true, warn);
1014 if (result) {
1015 checkUnsafeVarargsConversion(t, s, warn);
1016 }
1017 return result;
1018 }
1019 //where
1020 private boolean isSubtypeUncheckedInternal(Type t, Type s, boolean capture, Warner warn) {
1021 if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
1022 if (((ArrayType)t).elemtype.isPrimitive()) {
1023 return isSameType(elemtype(t), elemtype(s));
1024 } else {
1025 return isSubtypeUncheckedInternal(elemtype(t), elemtype(s), false, warn);
1026 }
1027 } else if (isSubtype(t, s, capture)) {
1028 return true;
1029 } else if (t.hasTag(TYPEVAR)) {
1030 return isSubtypeUncheckedInternal(t.getUpperBound(), s, false, warn);
1031 } else if (!s.isRaw()) {
1032 Type t2 = asSuper(t, s.tsym);
1033 if (t2 != null && t2.isRaw()) {
1034 if (isReifiable(s)) {
1035 warn.silentWarn(LintCategory.UNCHECKED);
1036 } else {
1037 warn.warn(LintCategory.UNCHECKED);
1038 }
1039 return true;
1040 }
1041 }
1042 return false;
1043 }
1044
1045 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
1046 if (!t.hasTag(ARRAY) || isReifiable(t)) {
1047 return;
1048 }
1049 ArrayType from = (ArrayType)t;
1050 boolean shouldWarn = false;
1051 switch (s.getTag()) {
1052 case ARRAY:
1053 ArrayType to = (ArrayType)s;
1054 shouldWarn = from.isVarargs() &&
1055 !to.isVarargs() &&
1056 !isReifiable(from);
1057 break;
1058 case CLASS:
1059 shouldWarn = from.isVarargs();
1060 break;
1061 }
1062 if (shouldWarn) {
1063 warn.warn(LintCategory.VARARGS);
1064 }
1065 }
1066
1067 /**
1068 * Is t a subtype of s?<br>
1069 * (not defined for Method and ForAll types)
1070 */
1071 public final boolean isSubtype(Type t, Type s) {
1072 return isSubtype(t, s, true);
1073 }
1074 public final boolean isSubtypeNoCapture(Type t, Type s) {
1075 return isSubtype(t, s, false);
1076 }
1077 public boolean isSubtype(Type t, Type s, boolean capture) {
1078 if (t.equalsIgnoreMetadata(s))
1079 return true;
1080 if (s.isPartial())
1081 return isSuperType(s, t);
1082
1083 if (s.isCompound()) {
1084 for (Type s2 : interfaces(s).prepend(supertype(s))) {
1085 if (!isSubtype(t, s2, capture))
1086 return false;
1087 }
1088 return true;
1089 }
1090
1091 // Generally, if 's' is a lower-bounded type variable, recur on lower bound; but
1092 // for inference variables and intersections, we need to keep 's'
1093 // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars)
1094 if (!t.hasTag(UNDETVAR) && !t.isCompound()) {
1095 // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
1096 Type lower = cvarLowerBound(wildLowerBound(s));
1097 if (s != lower && !lower.hasTag(BOT))
1098 return isSubtype(capture ? capture(t) : t, lower, false);
1099 }
1100
1101 return isSubtype.visit(capture ? capture(t) : t, s);
1102 }
1103 // where
1104 private TypeRelation isSubtype = new TypeRelation()
1105 {
1106 @Override
1107 public Boolean visitType(Type t, Type s) {
1108 switch (t.getTag()) {
1109 case BYTE:
1110 return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
1111 case CHAR:
1112 return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
1113 case SHORT: case INT: case LONG:
1114 case FLOAT: case DOUBLE:
1115 return t.getTag().isSubRangeOf(s.getTag());
1116 case BOOLEAN: case VOID:
1117 return t.hasTag(s.getTag());
1118 case TYPEVAR:
1119 return isSubtypeNoCapture(t.getUpperBound(), s);
1120 case BOT:
1121 return
1122 s.hasTag(BOT) || s.hasTag(CLASS) ||
1123 s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
1124 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
1125 case NONE:
1126 return false;
1127 default:
1128 throw new AssertionError("isSubtype " + t.getTag());
1129 }
1130 }
1131
1132 private Set<TypePair> cache = new HashSet<>();
1133
1134 private boolean containsTypeRecursive(Type t, Type s) {
1135 TypePair pair = new TypePair(t, s);
1136 if (cache.add(pair)) {
1137 try {
1138 return containsType(t.getTypeArguments(),
1139 s.getTypeArguments());
1140 } finally {
1141 cache.remove(pair);
1142 }
1143 } else {
1144 return containsType(t.getTypeArguments(),
1145 rewriteSupers(s).getTypeArguments());
1146 }
1147 }
1148
1149 private Type rewriteSupers(Type t) {
1150 if (!t.isParameterized())
1151 return t;
1152 ListBuffer<Type> from = new ListBuffer<>();
1153 ListBuffer<Type> to = new ListBuffer<>();
1154 adaptSelf(t, from, to);
1155 if (from.isEmpty())
1156 return t;
1157 ListBuffer<Type> rewrite = new ListBuffer<>();
1158 boolean changed = false;
1159 for (Type orig : to.toList()) {
1160 Type s = rewriteSupers(orig);
1161 if (s.isSuperBound() && !s.isExtendsBound()) {
1162 s = new WildcardType(syms.objectType,
1163 BoundKind.UNBOUND,
1164 syms.boundClass,
1165 s.getMetadata());
1166 changed = true;
1167 } else if (s != orig) {
1168 s = new WildcardType(wildUpperBound(s),
1169 BoundKind.EXTENDS,
1170 syms.boundClass,
1171 s.getMetadata());
1172 changed = true;
1173 }
1174 rewrite.append(s);
1175 }
1176 if (changed)
1177 return subst(t.tsym.type, from.toList(), rewrite.toList());
1178 else
1179 return t;
1180 }
1181
1182 @Override
1183 public Boolean visitClassType(ClassType t, Type s) {
1184 Type sup = asSuper(t, s.tsym);
1185 if (sup == null) return false;
1186 // If t is an intersection, sup might not be a class type
1187 if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s);
1188 return sup.tsym == s.tsym
1189 // Check type variable containment
1190 && (!s.isParameterized() || containsTypeRecursive(s, sup))
1191 && isSubtypeNoCapture(sup.getEnclosingType(),
1192 s.getEnclosingType());
1193 }
1194
1195 @Override
1196 public Boolean visitArrayType(ArrayType t, Type s) {
1197 if (s.hasTag(ARRAY)) {
1198 if (t.elemtype.isPrimitive())
1199 return isSameType(t.elemtype, elemtype(s));
1200 else
1201 return isSubtypeNoCapture(t.elemtype, elemtype(s));
1202 }
1203
1204 if (s.hasTag(CLASS)) {
1205 Name sname = s.tsym.getQualifiedName();
1206 return sname == names.java_lang_Object
1207 || sname == names.java_lang_Cloneable
1208 || sname == names.java_io_Serializable;
1209 }
1210
1211 return false;
1212 }
1213
1214 @Override
1215 public Boolean visitUndetVar(UndetVar t, Type s) {
1216 //todo: test against origin needed? or replace with substitution?
1217 if (t == s || t.qtype == s || s.hasTag(ERROR)) {
1218 return true;
1219 } else if (s.hasTag(BOT)) {
1220 //if 's' is 'null' there's no instantiated type U for which
1221 //U <: s (but 'null' itself, which is not a valid type)
1222 return false;
1223 }
1224
1225 t.addBound(InferenceBound.UPPER, s, Types.this);
1226 return true;
1227 }
1228
1229 @Override
1230 public Boolean visitErrorType(ErrorType t, Type s) {
1231 return true;
1232 }
1233 };
1234
1235 /**
1236 * Is t a subtype of every type in given list `ts'?<br>
1237 * (not defined for Method and ForAll types)<br>
1238 * Allows unchecked conversions.
1239 */
1240 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
1241 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1242 if (!isSubtypeUnchecked(t, l.head, warn))
1243 return false;
1244 return true;
1245 }
1246
1247 /**
1248 * Are corresponding elements of ts subtypes of ss? If lists are
1249 * of different length, return false.
1250 */
1251 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
1252 while (ts.tail != null && ss.tail != null
1253 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1254 isSubtype(ts.head, ss.head)) {
1255 ts = ts.tail;
1256 ss = ss.tail;
1257 }
1258 return ts.tail == null && ss.tail == null;
1259 /*inlined: ts.isEmpty() && ss.isEmpty();*/
1260 }
1261
1262 /**
1263 * Are corresponding elements of ts subtypes of ss, allowing
1264 * unchecked conversions? If lists are of different length,
1265 * return false.
1266 **/
1267 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
1268 while (ts.tail != null && ss.tail != null
1269 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1270 isSubtypeUnchecked(ts.head, ss.head, warn)) {
1271 ts = ts.tail;
1272 ss = ss.tail;
1273 }
1274 return ts.tail == null && ss.tail == null;
1275 /*inlined: ts.isEmpty() && ss.isEmpty();*/
1276 }
1277 // </editor-fold>
1278
1279 // <editor-fold defaultstate="collapsed" desc="isSuperType">
1280 /**
1281 * Is t a supertype of s?
1282 */
1283 public boolean isSuperType(Type t, Type s) {
1284 switch (t.getTag()) {
1285 case ERROR:
1286 return true;
1287 case UNDETVAR: {
1288 UndetVar undet = (UndetVar)t;
1289 if (t == s ||
1290 undet.qtype == s ||
1291 s.hasTag(ERROR) ||
1292 s.hasTag(BOT)) {
1293 return true;
1294 }
1295 undet.addBound(InferenceBound.LOWER, s, this);
1296 return true;
1297 }
1298 default:
1299 return isSubtype(s, t);
1300 }
1301 }
1302 // </editor-fold>
1303
1304 // <editor-fold defaultstate="collapsed" desc="isSameType">
1305 /**
1306 * Are corresponding elements of the lists the same type? If
1307 * lists are of different length, return false.
1308 */
1309 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
1310 while (ts.tail != null && ss.tail != null
1311 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1312 isSameType(ts.head, ss.head)) {
1313 ts = ts.tail;
1314 ss = ss.tail;
1315 }
1316 return ts.tail == null && ss.tail == null;
1317 /*inlined: ts.isEmpty() && ss.isEmpty();*/
1318 }
1319
1320 /**
1321 * A polymorphic signature method (JLS 15.12.3) is a method that
1322 * (i) is declared in the java.lang.invoke.MethodHandle/VarHandle classes;
1323 * (ii) takes a single variable arity parameter;
1324 * (iii) whose declared type is Object[];
1325 * (iv) has any return type, Object signifying a polymorphic return type; and
1326 * (v) is native.
1327 */
1328 public boolean isSignaturePolymorphic(MethodSymbol msym) {
1329 List<Type> argtypes = msym.type.getParameterTypes();
1330 return (msym.flags_field & NATIVE) != 0 &&
1331 (msym.owner == syms.methodHandleType.tsym || msym.owner == syms.varHandleType.tsym) &&
1332 argtypes.length() == 1 &&
1333 argtypes.head.hasTag(TypeTag.ARRAY) &&
1334 ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
1335 }
1336
1337 /**
1338 * Is t the same type as s?
1339 */
1340 public boolean isSameType(Type t, Type s) {
1341 return isSameTypeVisitor.visit(t, s);
1342 }
1343 // where
1344
1345 /**
1346 * Type-equality relation - type variables are considered
1347 * equals if they share the same object identity.
1348 */
1349 TypeRelation isSameTypeVisitor = new TypeRelation() {
1350
1351 public Boolean visitType(Type t, Type s) {
1352 if (t.equalsIgnoreMetadata(s))
1353 return true;
1354
1355 if (s.isPartial())
1356 return visit(s, t);
1357
1358 switch (t.getTag()) {
1359 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1360 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
1361 return t.hasTag(s.getTag());
1362 case TYPEVAR: {
1363 if (s.hasTag(TYPEVAR)) {
1364 //type-substitution does not preserve type-var types
1365 //check that type var symbols and bounds are indeed the same
1366 return t == s;
1367 }
1368 else {
1369 //special case for s == ? super X, where upper(s) = u
1370 //check that u == t, where u has been set by Type.withTypeVar
1371 return s.isSuperBound() &&
1372 !s.isExtendsBound() &&
1373 visit(t, wildUpperBound(s));
1374 }
1375 }
1376 default:
1377 throw new AssertionError("isSameType " + t.getTag());
1378 }
1379 }
1380
1381 @Override
1382 public Boolean visitWildcardType(WildcardType t, Type s) {
1383 if (!s.hasTag(WILDCARD)) {
1384 return false;
1385 } else {
1386 WildcardType t2 = (WildcardType)s;
1387 return (t.kind == t2.kind || (t.isExtendsBound() && s.isExtendsBound())) &&
1388 isSameType(t.type, t2.type);
1389 }
1390 }
1391
1392 @Override
1393 public Boolean visitClassType(ClassType t, Type s) {
1394 if (t == s)
1395 return true;
1396
1397 if (s.isPartial())
1398 return visit(s, t);
1399
1400 if (s.isSuperBound() && !s.isExtendsBound())
1401 return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s));
1402
1403 if (t.isCompound() && s.isCompound()) {
1404 if (!visit(supertype(t), supertype(s)))
1405 return false;
1406
1407 Map<Symbol,Type> tMap = new HashMap<>();
1408 for (Type ti : interfaces(t)) {
1409 tMap.put(ti.tsym, ti);
1410 }
1411 for (Type si : interfaces(s)) {
1412 if (!tMap.containsKey(si.tsym))
1413 return false;
1414 Type ti = tMap.remove(si.tsym);
1415 if (!visit(ti, si))
1416 return false;
1417 }
1418 return tMap.isEmpty();
1419 }
1420 return t.tsym == s.tsym
1421 && visit(t.getEnclosingType(), s.getEnclosingType())
1422 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
1423 }
1424
1425 @Override
1426 public Boolean visitArrayType(ArrayType t, Type s) {
1427 if (t == s)
1428 return true;
1429
1430 if (s.isPartial())
1431 return visit(s, t);
1432
1433 return s.hasTag(ARRAY)
1434 && containsTypeEquivalent(t.elemtype, elemtype(s));
1435 }
1436
1437 @Override
1438 public Boolean visitMethodType(MethodType t, Type s) {
1439 // isSameType for methods does not take thrown
1440 // exceptions into account!
1441 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
1442 }
1443
1444 @Override
1445 public Boolean visitPackageType(PackageType t, Type s) {
1446 return t == s;
1447 }
1448
1449 @Override
1450 public Boolean visitForAll(ForAll t, Type s) {
1451 if (!s.hasTag(FORALL)) {
1452 return false;
1453 }
1454
1455 ForAll forAll = (ForAll)s;
1456 return hasSameBounds(t, forAll)
1457 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1458 }
1459
1460 @Override
1461 public Boolean visitUndetVar(UndetVar t, Type s) {
1462 if (s.hasTag(WILDCARD)) {
1463 // FIXME, this might be leftovers from before capture conversion
1464 return false;
1465 }
1466
1467 if (t == s || t.qtype == s || s.hasTag(ERROR)) {
1468 return true;
1469 }
1470
1471 t.addBound(InferenceBound.EQ, s, Types.this);
1472
1473 return true;
1474 }
1475
1476 @Override
1477 public Boolean visitErrorType(ErrorType t, Type s) {
1478 return true;
1479 }
1480 };
1481
1482 // </editor-fold>
1483
1484 // <editor-fold defaultstate="collapsed" desc="Contains Type">
1485 public boolean containedBy(Type t, Type s) {
1486 switch (t.getTag()) {
1487 case UNDETVAR:
1488 if (s.hasTag(WILDCARD)) {
1489 UndetVar undetvar = (UndetVar)t;
1490 WildcardType wt = (WildcardType)s;
1491 switch(wt.kind) {
1492 case UNBOUND:
1493 break;
1494 case EXTENDS: {
1495 Type bound = wildUpperBound(s);
1496 undetvar.addBound(InferenceBound.UPPER, bound, this);
1497 break;
1498 }
1499 case SUPER: {
1500 Type bound = wildLowerBound(s);
1501 undetvar.addBound(InferenceBound.LOWER, bound, this);
1502 break;
1503 }
1504 }
1505 return true;
1506 } else {
1507 return isSameType(t, s);
1508 }
1509 case ERROR:
1510 return true;
1511 default:
1512 return containsType(s, t);
1513 }
1514 }
1515
1516 boolean containsType(List<Type> ts, List<Type> ss) {
1517 while (ts.nonEmpty() && ss.nonEmpty()
1518 && containsType(ts.head, ss.head)) {
1519 ts = ts.tail;
1520 ss = ss.tail;
1521 }
1522 return ts.isEmpty() && ss.isEmpty();
1523 }
1524
1525 /**
1526 * Check if t contains s.
1527 *
1528 * <p>T contains S if:
1529 *
1530 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1531 *
1532 * <p>This relation is only used by ClassType.isSubtype(), that
1533 * is,
1534 *
1535 * <p>{@code C<S> <: C<T> if T contains S.}
1536 *
1537 * <p>Because of F-bounds, this relation can lead to infinite
1538 * recursion. Thus we must somehow break that recursion. Notice
1539 * that containsType() is only called from ClassType.isSubtype().
1540 * Since the arguments have already been checked against their
1541 * bounds, we know:
1542 *
1543 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1544 *
1545 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1546 *
1547 * @param t a type
1548 * @param s a type
1549 */
1550 public boolean containsType(Type t, Type s) {
1551 return containsType.visit(t, s);
1552 }
1553 // where
1554 private TypeRelation containsType = new TypeRelation() {
1555
1556 public Boolean visitType(Type t, Type s) {
1557 if (s.isPartial())
1558 return containedBy(s, t);
1559 else
1560 return isSameType(t, s);
1561 }
1562
1563 // void debugContainsType(WildcardType t, Type s) {
1564 // System.err.println();
1565 // System.err.format(" does %s contain %s?%n", t, s);
1566 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1567 // wildUpperBound(s), s, t, wildUpperBound(t),
1568 // t.isSuperBound()
1569 // || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t)));
1570 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1571 // wildLowerBound(t), t, s, wildLowerBound(s),
1572 // t.isExtendsBound()
1573 // || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s)));
1574 // System.err.println();
1575 // }
1576
1577 @Override
1578 public Boolean visitWildcardType(WildcardType t, Type s) {
1579 if (s.isPartial())
1580 return containedBy(s, t);
1581 else {
1582 // debugContainsType(t, s);
1583 return isSameWildcard(t, s)
1584 || isCaptureOf(s, t)
1585 || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))) &&
1586 (t.isSuperBound() || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t))));
1587 }
1588 }
1589
1590 @Override
1591 public Boolean visitUndetVar(UndetVar t, Type s) {
1592 if (!s.hasTag(WILDCARD)) {
1593 return isSameType(t, s);
1594 } else {
1595 return false;
1596 }
1597 }
1598
1599 @Override
1600 public Boolean visitErrorType(ErrorType t, Type s) {
1601 return true;
1602 }
1603 };
1604
1605 public boolean isCaptureOf(Type s, WildcardType t) {
1606 if (!s.hasTag(TYPEVAR) || !((TypeVar)s).isCaptured())
1607 return false;
1608 return isSameWildcard(t, ((CapturedType)s).wildcard);
1609 }
1610
1611 public boolean isSameWildcard(WildcardType t, Type s) {
1612 if (!s.hasTag(WILDCARD))
1613 return false;
1614 WildcardType w = (WildcardType)s;
1615 return w.kind == t.kind && w.type == t.type;
1616 }
1617
1618 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1619 while (ts.nonEmpty() && ss.nonEmpty()
1620 && containsTypeEquivalent(ts.head, ss.head)) {
1621 ts = ts.tail;
1622 ss = ss.tail;
1623 }
1624 return ts.isEmpty() && ss.isEmpty();
1625 }
1626 // </editor-fold>
1627
1628 // <editor-fold defaultstate="collapsed" desc="isCastable">
1629 public boolean isCastable(Type t, Type s) {
1630 return isCastable(t, s, noWarnings);
1631 }
1632
1633 /**
1634 * Is t castable to s?<br>
1635 * s is assumed to be an erased type.<br>
1636 * (not defined for Method and ForAll types).
1637 */
1638 public boolean isCastable(Type t, Type s, Warner warn) {
1639 // if same type
1640 if (t == s)
1641 return true;
1642 // if one of the types is primitive
1643 if (t.isPrimitive() != s.isPrimitive()) {
1644 t = skipTypeVars(t, false);
1645 return (isConvertible(t, s, warn)
1646 || (s.isPrimitive() &&
1647 isSubtype(boxedClass(s).type, t)));
1648 }
1649 boolean result;
1650 if (warn != warnStack.head) {
1651 try {
1652 warnStack = warnStack.prepend(warn);
1653 checkUnsafeVarargsConversion(t, s, warn);
1654 result = isCastable.visit(t,s);
1655 } finally {
1656 warnStack = warnStack.tail;
1657 }
1658 } else {
1659 result = isCastable.visit(t,s);
1660 }
1661 if (result && t.hasTag(CLASS) && t.tsym.kind.matches(Kinds.KindSelector.TYP)
1662 && s.hasTag(CLASS) && s.tsym.kind.matches(Kinds.KindSelector.TYP)
1663 && (t.tsym.isSealed() || s.tsym.isSealed())) {
1664 return (t.isCompound() || s.isCompound()) ?
1665 true :
1666 !(new DisjointChecker().areDisjoint((ClassSymbol)t.tsym, (ClassSymbol)s.tsym));
1667 }
1668 return result;
1669 }
1670 // where
1671 class DisjointChecker {
1672 Set<Pair<ClassSymbol, ClassSymbol>> pairsSeen = new HashSet<>();
1673 /* there are three cases for ts and ss:
1674 * - one is a class and the other one is an interface (case I)
1675 * - both are classes (case II)
1676 * - both are interfaces (case III)
1677 * all those cases are covered in JLS 23, section: "5.1.6.1 Allowed Narrowing Reference Conversion"
1678 */
1679 private boolean areDisjoint(ClassSymbol ts, ClassSymbol ss) {
1680 Pair<ClassSymbol, ClassSymbol> newPair = new Pair<>(ts, ss);
1681 /* if we are seeing the same pair again then there is an issue with the sealed hierarchy
1682 * bail out, a detailed error will be reported downstream
1683 */
1684 if (!pairsSeen.add(newPair))
1685 return false;
1686
1687 if (ts.isInterface() != ss.isInterface()) { // case I: one is a class and the other one is an interface
1688 ClassSymbol isym = ts.isInterface() ? ts : ss; // isym is the interface and csym the class
1689 ClassSymbol csym = isym == ts ? ss : ts;
1690 if (!isSubtype(erasure(csym.type), erasure(isym.type))) {
1691 if (csym.isFinal()) {
1692 return true;
1693 } else if (csym.isSealed()) {
1694 return areDisjoint(isym, csym.getPermittedSubclasses());
1695 } else if (isym.isSealed()) {
1696 // if the class is not final and not sealed then it has to be freely extensible
1697 return areDisjoint(csym, isym.getPermittedSubclasses());
1698 }
1699 } // now both are classes or both are interfaces
1700 } else if (!ts.isInterface()) { // case II: both are classes
1701 return !isSubtype(erasure(ss.type), erasure(ts.type)) && !isSubtype(erasure(ts.type), erasure(ss.type));
1702 } else { // case III: both are interfaces
1703 if (!isSubtype(erasure(ts.type), erasure(ss.type)) && !isSubtype(erasure(ss.type), erasure(ts.type))) {
1704 if (ts.isSealed()) {
1705 return areDisjoint(ss, ts.getPermittedSubclasses());
1706 } else if (ss.isSealed()) {
1707 return areDisjoint(ts, ss.getPermittedSubclasses());
1708 }
1709 }
1710 }
1711 // at this point we haven't been able to statically prove that the classes or interfaces are disjoint
1712 return false;
1713 }
1714
1715 boolean areDisjoint(ClassSymbol csym, List<Type> permittedSubtypes) {
1716 return permittedSubtypes.stream().allMatch(psubtype -> areDisjoint(csym, (ClassSymbol) psubtype.tsym));
1717 }
1718 }
1719
1720 private TypeRelation isCastable = new TypeRelation() {
1721
1722 public Boolean visitType(Type t, Type s) {
1723 if (s.hasTag(ERROR) || t.hasTag(NONE))
1724 return true;
1725
1726 switch (t.getTag()) {
1727 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1728 case DOUBLE:
1729 return s.isNumeric();
1730 case BOOLEAN:
1731 return s.hasTag(BOOLEAN);
1732 case VOID:
1733 return false;
1734 case BOT:
1735 return isSubtype(t, s);
1736 default:
1737 throw new AssertionError();
1738 }
1739 }
1740
1741 @Override
1742 public Boolean visitWildcardType(WildcardType t, Type s) {
1743 return isCastable(wildUpperBound(t), s, warnStack.head);
1744 }
1745
1746 @Override
1747 public Boolean visitClassType(ClassType t, Type s) {
1748 if (s.hasTag(ERROR) || s.hasTag(BOT))
1749 return true;
1750
1751 if (s.hasTag(TYPEVAR)) {
1752 if (isCastable(t, s.getUpperBound(), noWarnings)) {
1753 warnStack.head.warn(LintCategory.UNCHECKED);
1754 return true;
1755 } else {
1756 return false;
1757 }
1758 }
1759
1760 if (t.isCompound() || s.isCompound()) {
1761 return !t.isCompound() ?
1762 visitCompoundType((ClassType)s, t, true) :
1763 visitCompoundType(t, s, false);
1764 }
1765
1766 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
1767 boolean upcast;
1768 if ((upcast = isSubtype(erasure(t), erasure(s)))
1769 || isSubtype(erasure(s), erasure(t))) {
1770 if (!upcast && s.hasTag(ARRAY)) {
1771 if (!isReifiable(s))
1772 warnStack.head.warn(LintCategory.UNCHECKED);
1773 return true;
1774 } else if (s.isRaw()) {
1775 return true;
1776 } else if (t.isRaw()) {
1777 if (!isUnbounded(s))
1778 warnStack.head.warn(LintCategory.UNCHECKED);
1779 return true;
1780 }
1781 // Assume |a| <: |b|
1782 final Type a = upcast ? t : s;
1783 final Type b = upcast ? s : t;
1784 final boolean HIGH = true;
1785 final boolean LOW = false;
1786 final boolean DONT_REWRITE_TYPEVARS = false;
1787 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1788 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1789 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1790 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1791 Type lowSub = asSub(bLow, aLow.tsym);
1792 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1793 if (highSub == null) {
1794 final boolean REWRITE_TYPEVARS = true;
1795 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1796 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1797 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1798 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1799 lowSub = asSub(bLow, aLow.tsym);
1800 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1801 }
1802 if (highSub != null) {
1803 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1804 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1805 }
1806 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1807 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1808 && !disjointTypes(aLow.allparams(), highSub.allparams())
1809 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1810 if (upcast ? giveWarning(a, b) :
1811 giveWarning(b, a))
1812 warnStack.head.warn(LintCategory.UNCHECKED);
1813 return true;
1814 }
1815 }
1816 if (isReifiable(s))
1817 return isSubtypeUnchecked(a, b);
1818 else
1819 return isSubtypeUnchecked(a, b, warnStack.head);
1820 }
1821
1822 // Sidecast
1823 if (s.hasTag(CLASS)) {
1824 if ((s.tsym.flags() & INTERFACE) != 0) {
1825 return ((t.tsym.flags() & FINAL) == 0)
1826 ? sideCast(t, s, warnStack.head)
1827 : sideCastFinal(t, s, warnStack.head);
1828 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1829 return ((s.tsym.flags() & FINAL) == 0)
1830 ? sideCast(t, s, warnStack.head)
1831 : sideCastFinal(t, s, warnStack.head);
1832 } else {
1833 // unrelated class types
1834 return false;
1835 }
1836 }
1837 }
1838 return false;
1839 }
1840
1841 boolean visitCompoundType(ClassType ct, Type s, boolean reverse) {
1842 Warner warn = noWarnings;
1843 for (Type c : directSupertypes(ct)) {
1844 warn.clear();
1845 if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
1846 return false;
1847 }
1848 if (warn.hasLint(LintCategory.UNCHECKED))
1849 warnStack.head.warn(LintCategory.UNCHECKED);
1850 return true;
1851 }
1852
1853 @Override
1854 public Boolean visitArrayType(ArrayType t, Type s) {
1855 switch (s.getTag()) {
1856 case ERROR:
1857 case BOT:
1858 return true;
1859 case TYPEVAR:
1860 if (isCastable(s, t, noWarnings)) {
1861 warnStack.head.warn(LintCategory.UNCHECKED);
1862 return true;
1863 } else {
1864 return false;
1865 }
1866 case CLASS:
1867 return isSubtype(t, s);
1868 case ARRAY:
1869 if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
1870 return elemtype(t).hasTag(elemtype(s).getTag());
1871 } else {
1872 return isCastable(elemtype(t), elemtype(s), warnStack.head);
1873 }
1874 default:
1875 return false;
1876 }
1877 }
1878
1879 @Override
1880 public Boolean visitTypeVar(TypeVar t, Type s) {
1881 switch (s.getTag()) {
1882 case ERROR:
1883 case BOT:
1884 return true;
1885 case TYPEVAR:
1886 if (isSubtype(t, s)) {
1887 return true;
1888 } else if (isCastable(t.getUpperBound(), s, noWarnings)) {
1889 warnStack.head.warn(LintCategory.UNCHECKED);
1890 return true;
1891 } else {
1892 return false;
1893 }
1894 default:
1895 return isCastable(t.getUpperBound(), s, warnStack.head);
1896 }
1897 }
1898
1899 @Override
1900 public Boolean visitErrorType(ErrorType t, Type s) {
1901 return true;
1902 }
1903 };
1904 // </editor-fold>
1905
1906 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1907 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1908 while (ts.tail != null && ss.tail != null) {
1909 if (disjointType(ts.head, ss.head)) return true;
1910 ts = ts.tail;
1911 ss = ss.tail;
1912 }
1913 return false;
1914 }
1915
1916 /**
1917 * Two types or wildcards are considered disjoint if it can be
1918 * proven that no type can be contained in both. It is
1919 * conservative in that it is allowed to say that two types are
1920 * not disjoint, even though they actually are.
1921 *
1922 * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1923 * {@code X} and {@code Y} are not disjoint.
1924 */
1925 public boolean disjointType(Type t, Type s) {
1926 return disjointType.visit(t, s);
1927 }
1928 // where
1929 private TypeRelation disjointType = new TypeRelation() {
1930
1931 private Set<TypePair> cache = new HashSet<>();
1932
1933 @Override
1934 public Boolean visitType(Type t, Type s) {
1935 if (s.hasTag(WILDCARD))
1936 return visit(s, t);
1937 else
1938 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1939 }
1940
1941 private boolean isCastableRecursive(Type t, Type s) {
1942 TypePair pair = new TypePair(t, s);
1943 if (cache.add(pair)) {
1944 try {
1945 return Types.this.isCastable(t, s);
1946 } finally {
1947 cache.remove(pair);
1948 }
1949 } else {
1950 return true;
1951 }
1952 }
1953
1954 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1955 TypePair pair = new TypePair(t, s);
1956 if (cache.add(pair)) {
1957 try {
1958 return Types.this.notSoftSubtype(t, s);
1959 } finally {
1960 cache.remove(pair);
1961 }
1962 } else {
1963 return false;
1964 }
1965 }
1966
1967 @Override
1968 public Boolean visitWildcardType(WildcardType t, Type s) {
1969 if (t.isUnbound())
1970 return false;
1971
1972 if (!s.hasTag(WILDCARD)) {
1973 if (t.isExtendsBound())
1974 return notSoftSubtypeRecursive(s, t.type);
1975 else
1976 return notSoftSubtypeRecursive(t.type, s);
1977 }
1978
1979 if (s.isUnbound())
1980 return false;
1981
1982 if (t.isExtendsBound()) {
1983 if (s.isExtendsBound())
1984 return !isCastableRecursive(t.type, wildUpperBound(s));
1985 else if (s.isSuperBound())
1986 return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
1987 } else if (t.isSuperBound()) {
1988 if (s.isExtendsBound())
1989 return notSoftSubtypeRecursive(t.type, wildUpperBound(s));
1990 }
1991 return false;
1992 }
1993 };
1994 // </editor-fold>
1995
1996 // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
1997 public List<Type> cvarLowerBounds(List<Type> ts) {
1998 return ts.map(cvarLowerBoundMapping);
1999 }
2000 private final TypeMapping<Void> cvarLowerBoundMapping = new TypeMapping<Void>() {
2001 @Override
2002 public Type visitCapturedType(CapturedType t, Void _unused) {
2003 return cvarLowerBound(t);
2004 }
2005 };
2006 // </editor-fold>
2007
2008 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
2009 /**
2010 * This relation answers the question: is impossible that
2011 * something of type `t' can be a subtype of `s'? This is
2012 * different from the question "is `t' not a subtype of `s'?"
2013 * when type variables are involved: Integer is not a subtype of T
2014 * where {@code <T extends Number>} but it is not true that Integer cannot
2015 * possibly be a subtype of T.
2016 */
2017 public boolean notSoftSubtype(Type t, Type s) {
2018 if (t == s) return false;
2019 if (t.hasTag(TYPEVAR)) {
2020 TypeVar tv = (TypeVar) t;
2021 return !isCastable(tv.getUpperBound(),
2022 relaxBound(s),
2023 noWarnings);
2024 }
2025 if (!s.hasTag(WILDCARD))
2026 s = cvarUpperBound(s);
2027
2028 return !isSubtype(t, relaxBound(s));
2029 }
2030
2031 private Type relaxBound(Type t) {
2032 return (t.hasTag(TYPEVAR)) ?
2033 rewriteQuantifiers(skipTypeVars(t, false), true, true) :
2034 t;
2035 }
2036 // </editor-fold>
2037
2038 // <editor-fold defaultstate="collapsed" desc="isReifiable">
2039 public boolean isReifiable(Type t) {
2040 return isReifiable.visit(t);
2041 }
2042 // where
2043 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
2044
2045 public Boolean visitType(Type t, Void ignored) {
2046 return true;
2047 }
2048
2049 @Override
2050 public Boolean visitClassType(ClassType t, Void ignored) {
2051 if (t.isCompound())
2052 return false;
2053 else {
2054 if (!t.isParameterized())
2055 return true;
2056
2057 for (Type param : t.allparams()) {
2058 if (!param.isUnbound())
2059 return false;
2060 }
2061 return true;
2062 }
2063 }
2064
2065 @Override
2066 public Boolean visitArrayType(ArrayType t, Void ignored) {
2067 return visit(t.elemtype);
2068 }
2069
2070 @Override
2071 public Boolean visitTypeVar(TypeVar t, Void ignored) {
2072 return false;
2073 }
2074 };
2075 // </editor-fold>
2076
2077 // <editor-fold defaultstate="collapsed" desc="Array Utils">
2078 public boolean isArray(Type t) {
2079 while (t.hasTag(WILDCARD))
2080 t = wildUpperBound(t);
2081 return t.hasTag(ARRAY);
2082 }
2083
2084 /**
2085 * The element type of an array.
2086 */
2087 public Type elemtype(Type t) {
2088 switch (t.getTag()) {
2089 case WILDCARD:
2090 return elemtype(wildUpperBound(t));
2091 case ARRAY:
2092 return ((ArrayType)t).elemtype;
2093 case FORALL:
2094 return elemtype(((ForAll)t).qtype);
2095 case ERROR:
2096 return t;
2097 default:
2098 return null;
2099 }
2100 }
2101
2102 public Type elemtypeOrType(Type t) {
2103 Type elemtype = elemtype(t);
2104 return elemtype != null ?
2105 elemtype :
2106 t;
2107 }
2108
2109 /**
2110 * Mapping to take element type of an arraytype
2111 */
2112 private TypeMapping<Void> elemTypeFun = new TypeMapping<Void>() {
2113 @Override
2114 public Type visitArrayType(ArrayType t, Void _unused) {
2115 return t.elemtype;
2116 }
2117
2118 @Override
2119 public Type visitTypeVar(TypeVar t, Void _unused) {
2120 return visit(skipTypeVars(t, false));
2121 }
2122 };
2123
2124 /**
2125 * The number of dimensions of an array type.
2126 */
2127 public int dimensions(Type t) {
2128 int result = 0;
2129 while (t.hasTag(ARRAY)) {
2130 result++;
2131 t = elemtype(t);
2132 }
2133 return result;
2134 }
2135
2136 /**
2137 * Returns an ArrayType with the component type t
2138 *
2139 * @param t The component type of the ArrayType
2140 * @return the ArrayType for the given component
2141 */
2142 public ArrayType makeArrayType(Type t) {
2143 if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
2144 Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
2145 }
2146 return new ArrayType(t, syms.arrayClass);
2147 }
2148 // </editor-fold>
2149
2150 // <editor-fold defaultstate="collapsed" desc="asSuper">
2151 /**
2152 * Return the (most specific) base type of t that starts with the
2153 * given symbol. If none exists, return null.
2154 *
2155 * Caveat Emptor: Since javac represents the class of all arrays with a singleton
2156 * symbol Symtab.arrayClass, which by being a singleton cannot hold any discriminant,
2157 * this method could yield surprising answers when invoked on arrays. For example when
2158 * invoked with t being byte [] and sym being t.sym itself, asSuper would answer null.
2159 *
2160 * @param t a type
2161 * @param sym a symbol
2162 */
2163 public Type asSuper(Type t, Symbol sym) {
2164 /* Some examples:
2165 *
2166 * (Enum<E>, Comparable) => Comparable<E>
2167 * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
2168 * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
2169 * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
2170 * Iterable<capture#160 of ? extends c.s.s.d.DocTree>
2171 */
2172 if (sym.type == syms.objectType) { //optimization
2173 return syms.objectType;
2174 }
2175 return asSuper.visit(t, sym);
2176 }
2177 // where
2178 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
2179
2180 private Set<Symbol> seenTypes = new HashSet<>();
2181
2182 public Type visitType(Type t, Symbol sym) {
2183 return null;
2184 }
2185
2186 @Override
2187 public Type visitClassType(ClassType t, Symbol sym) {
2188 if (t.tsym == sym)
2189 return t;
2190
2191 Symbol c = t.tsym;
2192 if (!seenTypes.add(c)) {
2193 return null;
2194 }
2195 try {
2196 Type st = supertype(t);
2197 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) {
2198 Type x = asSuper(st, sym);
2199 if (x != null)
2200 return x;
2201 }
2202 if ((sym.flags() & INTERFACE) != 0) {
2203 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
2204 if (!l.head.hasTag(ERROR)) {
2205 Type x = asSuper(l.head, sym);
2206 if (x != null)
2207 return x;
2208 }
2209 }
2210 }
2211 return null;
2212 } finally {
2213 seenTypes.remove(c);
2214 }
2215 }
2216
2217 @Override
2218 public Type visitArrayType(ArrayType t, Symbol sym) {
2219 return isSubtype(t, sym.type) ? sym.type : null;
2220 }
2221
2222 @Override
2223 public Type visitTypeVar(TypeVar t, Symbol sym) {
2224 if (t.tsym == sym)
2225 return t;
2226 else
2227 return asSuper(t.getUpperBound(), sym);
2228 }
2229
2230 @Override
2231 public Type visitErrorType(ErrorType t, Symbol sym) {
2232 return t;
2233 }
2234 };
2235
2236 /**
2237 * This method returns the first type in a sequence (starting at `t`) that is
2238 * a subclass of `sym`. The next type in the sequence is obtained by calling
2239 * `getEnclosingType()` on the previous type in the sequence. Note, this is
2240 * typically used to compute the implicit qualifier in a method/field access
2241 * expression. Example:
2242 *
2243 * static class Sup<F> { public F f; }
2244 * class Outer {
2245 * static class Sub extends Sup<String> {
2246 * class I {
2247 * void test() {
2248 * String f2 = f; // Sup<String>::f
2249 * }
2250 * }
2251 * }
2252 * }
2253 *
2254 * @param t a type
2255 * @param sym a symbol
2256 */
2257 public Type asOuterSuper(Type t, Symbol sym) {
2258 Type t1 = t;
2259 while (!t1.hasTag(NONE)) {
2260 Type s = asSuper(t1, sym);
2261 if (s != null) return s;
2262 t1 = t1.getEnclosingType();
2263 }
2264 return null;
2265 }
2266
2267 /**
2268 * This method returns the first type in a sequence (starting at `t`) that is
2269 * a subclass of `sym`. The next type in the sequence is obtained by obtaining
2270 * innermost lexically enclosing class type of the previous type in the sequence.
2271 * Note, this is typically used to compute the implicit qualifier in
2272 * a type expression. Example:
2273 *
2274 * class A<T> { class B { } }
2275 *
2276 * class C extends A<String> {
2277 * static class D {
2278 * B b; // A<String>.B
2279 * }
2280 * }
2281 *
2282 * @param t a type
2283 * @param sym a symbol
2284 */
2285 public Type asEnclosingSuper(Type t, Symbol sym) {
2286 Type t1 = t;
2287 while (!t1.hasTag(NONE)) {
2288 Type s = asSuper(t1, sym);
2289 if (s != null) return s;
2290 t1 = (t1.tsym.owner.enclClass() != null)
2291 ? t1.tsym.owner.enclClass().type
2292 : noType;
2293 }
2294 return null;
2295 }
2296 // </editor-fold>
2297
2298 // <editor-fold defaultstate="collapsed" desc="memberType">
2299 /**
2300 * The type of given symbol, seen as a member of t.
2301 *
2302 * @param t a type
2303 * @param sym a symbol
2304 */
2305 public Type memberType(Type t, Symbol sym) {
2306 return (sym.flags() & STATIC) != 0
2307 ? sym.type
2308 : memberType.visit(t, sym);
2309 }
2310 // where
2311 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
2312
2313 public Type visitType(Type t, Symbol sym) {
2314 return sym.type;
2315 }
2316
2317 @Override
2318 public Type visitWildcardType(WildcardType t, Symbol sym) {
2319 return memberType(wildUpperBound(t), sym);
2320 }
2321
2322 @Override
2323 public Type visitClassType(ClassType t, Symbol sym) {
2324 Symbol owner = sym.owner;
2325 long flags = sym.flags();
2326 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
2327 Type base = asOuterSuper(t, owner);
2328 //if t is an intersection type T = CT & I1 & I2 ... & In
2329 //its supertypes CT, I1, ... In might contain wildcards
2330 //so we need to go through capture conversion
2331 base = t.isCompound() ? capture(base) : base;
2332 if (base != null) {
2333 List<Type> ownerParams = owner.type.allparams();
2334 List<Type> baseParams = base.allparams();
2335 if (ownerParams.nonEmpty()) {
2336 if (baseParams.isEmpty()) {
2337 // then base is a raw type
2338 return erasure(sym.type);
2339 } else {
2340 return subst(sym.type, ownerParams, baseParams);
2341 }
2342 }
2343 }
2344 }
2345 return sym.type;
2346 }
2347
2348 @Override
2349 public Type visitTypeVar(TypeVar t, Symbol sym) {
2350 return memberType(t.getUpperBound(), sym);
2351 }
2352
2353 @Override
2354 public Type visitErrorType(ErrorType t, Symbol sym) {
2355 return t;
2356 }
2357 };
2358 // </editor-fold>
2359
2360 // <editor-fold defaultstate="collapsed" desc="isAssignable">
2361 public boolean isAssignable(Type t, Type s) {
2362 return isAssignable(t, s, noWarnings);
2363 }
2364
2365 /**
2366 * Is t assignable to s?<br>
2367 * Equivalent to subtype except for constant values and raw
2368 * types.<br>
2369 * (not defined for Method and ForAll types)
2370 */
2371 public boolean isAssignable(Type t, Type s, Warner warn) {
2372 if (t.hasTag(ERROR))
2373 return true;
2374 if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
2375 int value = ((Number)t.constValue()).intValue();
2376 switch (s.getTag()) {
2377 case BYTE:
2378 case CHAR:
2379 case SHORT:
2380 case INT:
2381 if (s.getTag().checkRange(value))
2382 return true;
2383 break;
2384 case CLASS:
2385 switch (unboxedType(s).getTag()) {
2386 case BYTE:
2387 case CHAR:
2388 case SHORT:
2389 return isAssignable(t, unboxedType(s), warn);
2390 }
2391 break;
2392 }
2393 }
2394 return isConvertible(t, s, warn);
2395 }
2396 // </editor-fold>
2397
2398 // <editor-fold defaultstate="collapsed" desc="erasure">
2399 /**
2400 * The erasure of t {@code |t|} -- the type that results when all
2401 * type parameters in t are deleted.
2402 */
2403 public Type erasure(Type t) {
2404 return eraseNotNeeded(t) ? t : erasure(t, false);
2405 }
2406 //where
2407 private boolean eraseNotNeeded(Type t) {
2408 // We don't want to erase primitive types and String type as that
2409 // operation is idempotent. Also, erasing these could result in loss
2410 // of information such as constant values attached to such types.
2411 return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
2412 }
2413
2414 private Type erasure(Type t, boolean recurse) {
2415 if (t.isPrimitive()) {
2416 return t; /* fast special case */
2417 } else {
2418 Type out = erasure.visit(t, recurse);
2419 return out;
2420 }
2421 }
2422 // where
2423 private TypeMapping<Boolean> erasure = new StructuralTypeMapping<Boolean>() {
2424 @SuppressWarnings("fallthrough")
2425 private Type combineMetadata(final Type s,
2426 final Type t) {
2427 if (t.getMetadata().nonEmpty()) {
2428 switch (s.getTag()) {
2429 case CLASS:
2430 if (s instanceof UnionClassType ||
2431 s instanceof IntersectionClassType) {
2432 return s;
2433 }
2434 //fall-through
2435 case BYTE, CHAR, SHORT, LONG, FLOAT, INT, DOUBLE, BOOLEAN,
2436 ARRAY, MODULE, TYPEVAR, WILDCARD, BOT:
2437 return s.dropMetadata(Annotations.class);
2438 case VOID, METHOD, PACKAGE, FORALL, DEFERRED,
2439 NONE, ERROR, UNDETVAR, UNINITIALIZED_THIS,
2440 UNINITIALIZED_OBJECT:
2441 return s;
2442 default:
2443 throw new AssertionError(s.getTag().name());
2444 }
2445 } else {
2446 return s;
2447 }
2448 }
2449
2450 public Type visitType(Type t, Boolean recurse) {
2451 if (t.isPrimitive())
2452 return t; /*fast special case*/
2453 else {
2454 //other cases already handled
2455 return combineMetadata(t, t);
2456 }
2457 }
2458
2459 @Override
2460 public Type visitWildcardType(WildcardType t, Boolean recurse) {
2461 Type erased = erasure(wildUpperBound(t), recurse);
2462 return combineMetadata(erased, t);
2463 }
2464
2465 @Override
2466 public Type visitClassType(ClassType t, Boolean recurse) {
2467 Type erased = t.tsym.erasure(Types.this);
2468 if (recurse) {
2469 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym,
2470 t.dropMetadata(Annotations.class).getMetadata());
2471 return erased;
2472 } else {
2473 return combineMetadata(erased, t);
2474 }
2475 }
2476
2477 @Override
2478 public Type visitTypeVar(TypeVar t, Boolean recurse) {
2479 Type erased = erasure(t.getUpperBound(), recurse);
2480 return combineMetadata(erased, t);
2481 }
2482 };
2483
2484 public List<Type> erasure(List<Type> ts) {
2485 return erasure.visit(ts, false);
2486 }
2487
2488 public Type erasureRecursive(Type t) {
2489 return erasure(t, true);
2490 }
2491
2492 public List<Type> erasureRecursive(List<Type> ts) {
2493 return erasure.visit(ts, true);
2494 }
2495 // </editor-fold>
2496
2497 // <editor-fold defaultstate="collapsed" desc="makeIntersectionType">
2498 /**
2499 * Make an intersection type from non-empty list of types. The list should be ordered according to
2500 * {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion.
2501 * Hence, this version of makeIntersectionType may not be called during a classfile read.
2502 *
2503 * @param bounds the types from which the intersection type is formed
2504 */
2505 public IntersectionClassType makeIntersectionType(List<Type> bounds) {
2506 return makeIntersectionType(bounds, bounds.head.tsym.isInterface());
2507 }
2508
2509 /**
2510 * Make an intersection type from non-empty list of types. The list should be ordered according to
2511 * {@link TypeSymbol#precedes(TypeSymbol, Types)}. This does not cause symbol completion as
2512 * an extra parameter indicates as to whether all bounds are interfaces - in which case the
2513 * supertype is implicitly assumed to be 'Object'.
2514 *
2515 * @param bounds the types from which the intersection type is formed
2516 * @param allInterfaces are all bounds interface types?
2517 */
2518 public IntersectionClassType makeIntersectionType(List<Type> bounds, boolean allInterfaces) {
2519 Assert.check(bounds.nonEmpty());
2520 Type firstExplicitBound = bounds.head;
2521 if (allInterfaces) {
2522 bounds = bounds.prepend(syms.objectType);
2523 }
2524 ClassSymbol bc =
2525 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
2526 Type.moreInfo
2527 ? names.fromString(bounds.toString())
2528 : names.empty,
2529 null,
2530 syms.noSymbol);
2531 IntersectionClassType intersectionType = new IntersectionClassType(bounds, bc, allInterfaces);
2532 bc.type = intersectionType;
2533 bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
2534 syms.objectType : // error condition, recover
2535 erasure(firstExplicitBound);
2536 bc.members_field = WriteableScope.create(bc);
2537 return intersectionType;
2538 }
2539 // </editor-fold>
2540
2541 // <editor-fold defaultstate="collapsed" desc="supertype">
2542 public Type supertype(Type t) {
2543 return supertype.visit(t);
2544 }
2545 // where
2546 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2547
2548 public Type visitType(Type t, Void ignored) {
2549 // A note on wildcards: there is no good way to
2550 // determine a supertype for a lower-bounded wildcard.
2551 return Type.noType;
2552 }
2553
2554 @Override
2555 public Type visitClassType(ClassType t, Void ignored) {
2556 if (t.supertype_field == null) {
2557 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2558 // An interface has no superclass; its supertype is Object.
2559 if (t.isInterface())
2560 supertype = ((ClassType)t.tsym.type).supertype_field;
2561 if (t.supertype_field == null) {
2562 List<Type> actuals = classBound(t).allparams();
2563 List<Type> formals = t.tsym.type.allparams();
2564 if (t.hasErasedSupertypes()) {
2565 t.supertype_field = erasureRecursive(supertype);
2566 } else if (formals.nonEmpty()) {
2567 t.supertype_field = subst(supertype, formals, actuals);
2568 }
2569 else {
2570 t.supertype_field = supertype;
2571 }
2572 }
2573 }
2574 return t.supertype_field;
2575 }
2576
2577 /**
2578 * The supertype is always a class type. If the type
2579 * variable's bounds start with a class type, this is also
2580 * the supertype. Otherwise, the supertype is
2581 * java.lang.Object.
2582 */
2583 @Override
2584 public Type visitTypeVar(TypeVar t, Void ignored) {
2585 if (t.getUpperBound().hasTag(TYPEVAR) ||
2586 (!t.getUpperBound().isCompound() && !t.getUpperBound().isInterface())) {
2587 return t.getUpperBound();
2588 } else {
2589 return supertype(t.getUpperBound());
2590 }
2591 }
2592
2593 @Override
2594 public Type visitArrayType(ArrayType t, Void ignored) {
2595 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2596 return arraySuperType();
2597 else
2598 return new ArrayType(supertype(t.elemtype), t.tsym);
2599 }
2600
2601 @Override
2602 public Type visitErrorType(ErrorType t, Void ignored) {
2603 return Type.noType;
2604 }
2605 };
2606 // </editor-fold>
2607
2608 // <editor-fold defaultstate="collapsed" desc="interfaces">
2609 /**
2610 * Return the interfaces implemented by this class.
2611 */
2612 public List<Type> interfaces(Type t) {
2613 return interfaces.visit(t);
2614 }
2615 // where
2616 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2617
2618 public List<Type> visitType(Type t, Void ignored) {
2619 return List.nil();
2620 }
2621
2622 @Override
2623 public List<Type> visitClassType(ClassType t, Void ignored) {
2624 if (t.interfaces_field == null) {
2625 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2626 if (t.interfaces_field == null) {
2627 // If t.interfaces_field is null, then t must
2628 // be a parameterized type (not to be confused
2629 // with a generic type declaration).
2630 // Terminology:
2631 // Parameterized type: List<String>
2632 // Generic type declaration: class List<E> { ... }
2633 // So t corresponds to List<String> and
2634 // t.tsym.type corresponds to List<E>.
2635 // The reason t must be parameterized type is
2636 // that completion will happen as a side
2637 // effect of calling
2638 // ClassSymbol.getInterfaces. Since
2639 // t.interfaces_field is null after
2640 // completion, we can assume that t is not the
2641 // type of a class/interface declaration.
2642 Assert.check(t != t.tsym.type, t);
2643 List<Type> actuals = t.allparams();
2644 List<Type> formals = t.tsym.type.allparams();
2645 if (t.hasErasedSupertypes()) {
2646 t.interfaces_field = erasureRecursive(interfaces);
2647 } else if (formals.nonEmpty()) {
2648 t.interfaces_field = subst(interfaces, formals, actuals);
2649 }
2650 else {
2651 t.interfaces_field = interfaces;
2652 }
2653 }
2654 }
2655 return t.interfaces_field;
2656 }
2657
2658 @Override
2659 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2660 if (t.getUpperBound().isCompound())
2661 return interfaces(t.getUpperBound());
2662
2663 if (t.getUpperBound().isInterface())
2664 return List.of(t.getUpperBound());
2665
2666 return List.nil();
2667 }
2668 };
2669
2670 public List<Type> directSupertypes(Type t) {
2671 return directSupertypes.visit(t);
2672 }
2673 // where
2674 private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
2675
2676 public List<Type> visitType(final Type type, final Void ignored) {
2677 if (!type.isIntersection()) {
2678 final Type sup = supertype(type);
2679 return (sup == Type.noType || sup == type || sup == null)
2680 ? interfaces(type)
2681 : interfaces(type).prepend(sup);
2682 } else {
2683 return ((IntersectionClassType)type).getExplicitComponents();
2684 }
2685 }
2686 };
2687
2688 public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
2689 for (Type i2 : interfaces(origin.type)) {
2690 if (isym == i2.tsym) return true;
2691 }
2692 return false;
2693 }
2694 // </editor-fold>
2695
2696 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2697 Map<Type,Boolean> isDerivedRawCache = new HashMap<>();
2698
2699 public boolean isDerivedRaw(Type t) {
2700 Boolean result = isDerivedRawCache.get(t);
2701 if (result == null) {
2702 result = isDerivedRawInternal(t);
2703 isDerivedRawCache.put(t, result);
2704 }
2705 return result;
2706 }
2707
2708 public boolean isDerivedRawInternal(Type t) {
2709 if (t.isErroneous())
2710 return false;
2711 return
2712 t.isRaw() ||
2713 supertype(t) != Type.noType && isDerivedRaw(supertype(t)) ||
2714 isDerivedRaw(interfaces(t));
2715 }
2716
2717 public boolean isDerivedRaw(List<Type> ts) {
2718 List<Type> l = ts;
2719 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2720 return l.nonEmpty();
2721 }
2722 // </editor-fold>
2723
2724 // <editor-fold defaultstate="collapsed" desc="setBounds">
2725 /**
2726 * Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly,
2727 * as follows: if all all bounds are interface types, the computed supertype is Object,otherwise
2728 * the supertype is simply left null (in this case, the supertype is assumed to be the head of
2729 * the bound list passed as second argument). Note that this check might cause a symbol completion.
2730 * Hence, this version of setBounds may not be called during a classfile read.
2731 *
2732 * @param t a type variable
2733 * @param bounds the bounds, must be nonempty
2734 */
2735 public void setBounds(TypeVar t, List<Type> bounds) {
2736 setBounds(t, bounds, bounds.head.tsym.isInterface());
2737 }
2738
2739 /**
2740 * Set the bounds field of the given type variable to reflect a (possibly multiple) list of bounds.
2741 * This does not cause symbol completion as an extra parameter indicates as to whether all bounds
2742 * are interfaces - in which case the supertype is implicitly assumed to be 'Object'.
2743 *
2744 * @param t a type variable
2745 * @param bounds the bounds, must be nonempty
2746 * @param allInterfaces are all bounds interface types?
2747 */
2748 public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
2749 t.setUpperBound( bounds.tail.isEmpty() ?
2750 bounds.head :
2751 makeIntersectionType(bounds, allInterfaces) );
2752 t.rank_field = -1;
2753 }
2754 // </editor-fold>
2755
2756 // <editor-fold defaultstate="collapsed" desc="getBounds">
2757 /**
2758 * Return list of bounds of the given type variable.
2759 */
2760 public List<Type> getBounds(TypeVar t) {
2761 if (t.getUpperBound().hasTag(NONE))
2762 return List.nil();
2763 else if (t.getUpperBound().isErroneous() || !t.getUpperBound().isCompound())
2764 return List.of(t.getUpperBound());
2765 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2766 return interfaces(t).prepend(supertype(t));
2767 else
2768 // No superclass was given in bounds.
2769 // In this case, supertype is Object, erasure is first interface.
2770 return interfaces(t);
2771 }
2772 // </editor-fold>
2773
2774 // <editor-fold defaultstate="collapsed" desc="classBound">
2775 /**
2776 * If the given type is a (possibly selected) type variable,
2777 * return the bounding class of this type, otherwise return the
2778 * type itself.
2779 */
2780 public Type classBound(Type t) {
2781 return classBound.visit(t);
2782 }
2783 // where
2784 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2785
2786 public Type visitType(Type t, Void ignored) {
2787 return t;
2788 }
2789
2790 @Override
2791 public Type visitClassType(ClassType t, Void ignored) {
2792 Type outer1 = classBound(t.getEnclosingType());
2793 if (outer1 != t.getEnclosingType())
2794 return new ClassType(outer1, t.getTypeArguments(), t.tsym,
2795 t.getMetadata());
2796 else
2797 return t;
2798 }
2799
2800 @Override
2801 public Type visitTypeVar(TypeVar t, Void ignored) {
2802 return classBound(supertype(t));
2803 }
2804
2805 @Override
2806 public Type visitErrorType(ErrorType t, Void ignored) {
2807 return t;
2808 }
2809 };
2810 // </editor-fold>
2811
2812 // <editor-fold defaultstate="collapsed" desc="subsignature / override equivalence">
2813 /**
2814 * Returns true iff the first signature is a <em>subsignature</em>
2815 * of the other. This is <b>not</b> an equivalence
2816 * relation.
2817 *
2818 * @jls 8.4.2 Method Signature
2819 * @see #overrideEquivalent(Type t, Type s)
2820 * @param t first signature (possibly raw).
2821 * @param s second signature (could be subjected to erasure).
2822 * @return true if t is a subsignature of s.
2823 */
2824 public boolean isSubSignature(Type t, Type s) {
2825 return hasSameArgs(t, s, true) || hasSameArgs(t, erasure(s), true);
2826 }
2827
2828 /**
2829 * Returns true iff these signatures are related by <em>override
2830 * equivalence</em>. This is the natural extension of
2831 * isSubSignature to an equivalence relation.
2832 *
2833 * @jls 8.4.2 Method Signature
2834 * @see #isSubSignature(Type t, Type s)
2835 * @param t a signature (possible raw, could be subjected to
2836 * erasure).
2837 * @param s a signature (possible raw, could be subjected to
2838 * erasure).
2839 * @return true if either argument is a subsignature of the other.
2840 */
2841 public boolean overrideEquivalent(Type t, Type s) {
2842 return hasSameArgs(t, s) ||
2843 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2844 }
2845
2846 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2847 for (Symbol sym : syms.objectType.tsym.members().getSymbolsByName(msym.name)) {
2848 if (msym.overrides(sym, origin, Types.this, true)) {
2849 return true;
2850 }
2851 }
2852 return false;
2853 }
2854
2855 /**
2856 * This enum defines the strategy for implementing most specific return type check
2857 * during the most specific and functional interface checks.
2858 */
2859 public enum MostSpecificReturnCheck {
2860 /**
2861 * Return r1 is more specific than r2 if {@code r1 <: r2}. Extra care required for (i) handling
2862 * method type variables (if either method is generic) and (ii) subtyping should be replaced
2863 * by type-equivalence for primitives. This is essentially an inlined version of
2864 * {@link Types#resultSubtype(Type, Type, Warner)}, where the assignability check has been
2865 * replaced with a strict subtyping check.
2866 */
2867 BASIC() {
2868 @Override
2869 public boolean test(Type mt1, Type mt2, Types types) {
2870 List<Type> tvars = mt1.getTypeArguments();
2871 List<Type> svars = mt2.getTypeArguments();
2872 Type t = mt1.getReturnType();
2873 Type s = types.subst(mt2.getReturnType(), svars, tvars);
2874 return types.isSameType(t, s) ||
2875 !t.isPrimitive() &&
2876 !s.isPrimitive() &&
2877 types.isSubtype(t, s);
2878 }
2879 },
2880 /**
2881 * Return r1 is more specific than r2 if r1 is return-type-substitutable for r2.
2882 */
2883 RTS() {
2884 @Override
2885 public boolean test(Type mt1, Type mt2, Types types) {
2886 return types.returnTypeSubstitutable(mt1, mt2);
2887 }
2888 };
2889
2890 public abstract boolean test(Type mt1, Type mt2, Types types);
2891 }
2892
2893 /**
2894 * Merge multiple abstract methods. The preferred method is a method that is a subsignature
2895 * of all the other signatures and whose return type is more specific {@link MostSpecificReturnCheck}.
2896 * The resulting preferred method has a throws clause that is the intersection of the merged
2897 * methods' clauses.
2898 */
2899 public Optional<Symbol> mergeAbstracts(List<Symbol> ambiguousInOrder, Type site, boolean sigCheck) {
2900 //first check for preconditions
2901 boolean shouldErase = false;
2902 List<Type> erasedParams = ambiguousInOrder.head.erasure(this).getParameterTypes();
2903 for (Symbol s : ambiguousInOrder) {
2904 if ((s.flags() & ABSTRACT) == 0 ||
2905 (sigCheck && !isSameTypes(erasedParams, s.erasure(this).getParameterTypes()))) {
2906 return Optional.empty();
2907 } else if (s.type.hasTag(FORALL)) {
2908 shouldErase = true;
2909 }
2910 }
2911 //then merge abstracts
2912 for (MostSpecificReturnCheck mostSpecificReturnCheck : MostSpecificReturnCheck.values()) {
2913 outer: for (Symbol s : ambiguousInOrder) {
2914 Type mt = memberType(site, s);
2915 List<Type> allThrown = mt.getThrownTypes();
2916 for (Symbol s2 : ambiguousInOrder) {
2917 if (s != s2) {
2918 Type mt2 = memberType(site, s2);
2919 if (!isSubSignature(mt, mt2) ||
2920 !mostSpecificReturnCheck.test(mt, mt2, this)) {
2921 //ambiguity cannot be resolved
2922 continue outer;
2923 } else {
2924 List<Type> thrownTypes2 = mt2.getThrownTypes();
2925 if (!mt.hasTag(FORALL) && shouldErase) {
2926 thrownTypes2 = erasure(thrownTypes2);
2927 } else if (mt.hasTag(FORALL)) {
2928 //subsignature implies that if most specific is generic, then all other
2929 //methods are too
2930 Assert.check(mt2.hasTag(FORALL));
2931 // if both are generic methods, adjust thrown types ahead of intersection computation
2932 thrownTypes2 = subst(thrownTypes2, mt2.getTypeArguments(), mt.getTypeArguments());
2933 }
2934 allThrown = chk.intersect(allThrown, thrownTypes2);
2935 }
2936 }
2937 }
2938 return (allThrown == mt.getThrownTypes()) ?
2939 Optional.of(s) :
2940 Optional.of(new MethodSymbol(
2941 s.flags(),
2942 s.name,
2943 createMethodTypeWithThrown(s.type, allThrown),
2944 s.owner) {
2945 @Override
2946 public Symbol baseSymbol() {
2947 return s;
2948 }
2949 });
2950 }
2951 }
2952 return Optional.empty();
2953 }
2954
2955 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2956 class ImplementationCache {
2957
2958 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<>();
2959
2960 class Entry {
2961 final MethodSymbol cachedImpl;
2962 final Predicate<Symbol> implFilter;
2963 final boolean checkResult;
2964 final int prevMark;
2965
2966 public Entry(MethodSymbol cachedImpl,
2967 Predicate<Symbol> scopeFilter,
2968 boolean checkResult,
2969 int prevMark) {
2970 this.cachedImpl = cachedImpl;
2971 this.implFilter = scopeFilter;
2972 this.checkResult = checkResult;
2973 this.prevMark = prevMark;
2974 }
2975
2976 boolean matches(Predicate<Symbol> scopeFilter, boolean checkResult, int mark) {
2977 return this.implFilter == scopeFilter &&
2978 this.checkResult == checkResult &&
2979 this.prevMark == mark;
2980 }
2981 }
2982
2983 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
2984 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2985 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2986 if (cache == null) {
2987 cache = new HashMap<>();
2988 _map.put(ms, new SoftReference<>(cache));
2989 }
2990 Entry e = cache.get(origin);
2991 CompoundScope members = membersClosure(origin.type, true);
2992 if (e == null ||
2993 !e.matches(implFilter, checkResult, members.getMark())) {
2994 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2995 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2996 return impl;
2997 }
2998 else {
2999 return e.cachedImpl;
3000 }
3001 }
3002
3003 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
3004 for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
3005 t = skipTypeVars(t, false);
3006 TypeSymbol c = t.tsym;
3007 Symbol bestSoFar = null;
3008 for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) {
3009 if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) {
3010 bestSoFar = sym;
3011 if ((sym.flags() & ABSTRACT) == 0) {
3012 //if concrete impl is found, exit immediately
3013 break;
3014 }
3015 }
3016 }
3017 if (bestSoFar != null) {
3018 //return either the (only) concrete implementation or the first abstract one
3019 return (MethodSymbol)bestSoFar;
3020 }
3021 }
3022 return null;
3023 }
3024 }
3025
3026 private ImplementationCache implCache = new ImplementationCache();
3027
3028 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
3029 return implCache.get(ms, origin, checkResult, implFilter);
3030 }
3031 // </editor-fold>
3032
3033 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
3034 class MembersClosureCache extends SimpleVisitor<Scope.CompoundScope, Void> {
3035
3036 private Map<TypeSymbol, CompoundScope> _map = new HashMap<>();
3037
3038 Set<TypeSymbol> seenTypes = new HashSet<>();
3039
3040 class MembersScope extends CompoundScope {
3041
3042 CompoundScope scope;
3043
3044 public MembersScope(CompoundScope scope) {
3045 super(scope.owner);
3046 this.scope = scope;
3047 }
3048
3049 Predicate<Symbol> combine(Predicate<Symbol> sf) {
3050 return s -> !s.owner.isInterface() && (sf == null || sf.test(s));
3051 }
3052
3053 @Override
3054 public Iterable<Symbol> getSymbols(Predicate<Symbol> sf, LookupKind lookupKind) {
3055 return scope.getSymbols(combine(sf), lookupKind);
3056 }
3057
3058 @Override
3059 public Iterable<Symbol> getSymbolsByName(Name name, Predicate<Symbol> sf, LookupKind lookupKind) {
3060 return scope.getSymbolsByName(name, combine(sf), lookupKind);
3061 }
3062
3063 @Override
3064 public int getMark() {
3065 return scope.getMark();
3066 }
3067 }
3068
3069 CompoundScope nilScope;
3070
3071 /** members closure visitor methods **/
3072
3073 public CompoundScope visitType(Type t, Void _unused) {
3074 if (nilScope == null) {
3075 nilScope = new CompoundScope(syms.noSymbol);
3076 }
3077 return nilScope;
3078 }
3079
3080 @Override
3081 public CompoundScope visitClassType(ClassType t, Void _unused) {
3082 if (!seenTypes.add(t.tsym)) {
3083 //this is possible when an interface is implemented in multiple
3084 //superclasses, or when a class hierarchy is circular - in such
3085 //cases we don't need to recurse (empty scope is returned)
3086 return new CompoundScope(t.tsym);
3087 }
3088 try {
3089 seenTypes.add(t.tsym);
3090 ClassSymbol csym = (ClassSymbol)t.tsym;
3091 CompoundScope membersClosure = _map.get(csym);
3092 if (membersClosure == null) {
3093 membersClosure = new CompoundScope(csym);
3094 for (Type i : interfaces(t)) {
3095 membersClosure.prependSubScope(visit(i, null));
3096 }
3097 membersClosure.prependSubScope(visit(supertype(t), null));
3098 membersClosure.prependSubScope(csym.members());
3099 _map.put(csym, membersClosure);
3100 }
3101 return membersClosure;
3102 }
3103 finally {
3104 seenTypes.remove(t.tsym);
3105 }
3106 }
3107
3108 @Override
3109 public CompoundScope visitTypeVar(TypeVar t, Void _unused) {
3110 return visit(t.getUpperBound(), null);
3111 }
3112 }
3113
3114 private MembersClosureCache membersCache = new MembersClosureCache();
3115
3116 public CompoundScope membersClosure(Type site, boolean skipInterface) {
3117 CompoundScope cs = membersCache.visit(site, null);
3118 Assert.checkNonNull(cs, () -> "type " + site);
3119 return skipInterface ? membersCache.new MembersScope(cs) : cs;
3120 }
3121 // </editor-fold>
3122
3123
3124 /** Return first abstract member of class `sym'.
3125 */
3126 public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) {
3127 try {
3128 return firstUnimplementedAbstractImpl(sym, sym);
3129 } catch (CompletionFailure ex) {
3130 chk.completionError(enter.getEnv(sym).tree.pos(), ex);
3131 return null;
3132 }
3133 }
3134 //where:
3135 private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) {
3136 MethodSymbol undef = null;
3137 // Do not bother to search in classes that are not abstract,
3138 // since they cannot have abstract members.
3139 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
3140 Scope s = c.members();
3141 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
3142 if (sym.kind == MTH &&
3143 (sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
3144 MethodSymbol absmeth = (MethodSymbol)sym;
3145 MethodSymbol implmeth = absmeth.implementation(impl, this, true);
3146 if (implmeth == null || implmeth == absmeth) {
3147 //look for default implementations
3148 MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head;
3149 if (prov != null && prov.overrides(absmeth, impl, this, true)) {
3150 implmeth = prov;
3151 }
3152 }
3153 if (implmeth == null || implmeth == absmeth) {
3154 undef = absmeth;
3155 break;
3156 }
3157 }
3158 }
3159 if (undef == null) {
3160 Type st = supertype(c.type);
3161 if (st.hasTag(CLASS))
3162 undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym);
3163 }
3164 for (List<Type> l = interfaces(c.type);
3165 undef == null && l.nonEmpty();
3166 l = l.tail) {
3167 undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym);
3168 }
3169 }
3170 return undef;
3171 }
3172
3173 public class CandidatesCache {
3174 public Map<Entry, List<MethodSymbol>> cache = new WeakHashMap<>();
3175
3176 class Entry {
3177 Type site;
3178 MethodSymbol msym;
3179
3180 Entry(Type site, MethodSymbol msym) {
3181 this.site = site;
3182 this.msym = msym;
3183 }
3184
3185 @Override
3186 public boolean equals(Object obj) {
3187 return (obj instanceof Entry entry)
3188 && entry.msym == msym
3189 && isSameType(site, entry.site);
3190 }
3191
3192 @Override
3193 public int hashCode() {
3194 return Types.this.hashCode(site) & ~msym.hashCode();
3195 }
3196 }
3197
3198 public List<MethodSymbol> get(Entry e) {
3199 return cache.get(e);
3200 }
3201
3202 public void put(Entry e, List<MethodSymbol> msymbols) {
3203 cache.put(e, msymbols);
3204 }
3205 }
3206
3207 public CandidatesCache candidatesCache = new CandidatesCache();
3208
3209 //where
3210 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
3211 CandidatesCache.Entry e = candidatesCache.new Entry(site, ms);
3212 List<MethodSymbol> candidates = candidatesCache.get(e);
3213 if (candidates == null) {
3214 Predicate<Symbol> filter = new MethodFilter(ms, site);
3215 List<MethodSymbol> candidates2 = List.nil();
3216 for (Symbol s : membersClosure(site, false).getSymbols(filter)) {
3217 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
3218 return List.of((MethodSymbol)s);
3219 } else if (!candidates2.contains(s)) {
3220 candidates2 = candidates2.prepend((MethodSymbol)s);
3221 }
3222 }
3223 candidates = prune(candidates2);
3224 candidatesCache.put(e, candidates);
3225 }
3226 return candidates;
3227 }
3228
3229 public List<MethodSymbol> prune(List<MethodSymbol> methods) {
3230 ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
3231 for (MethodSymbol m1 : methods) {
3232 boolean isMin_m1 = true;
3233 for (MethodSymbol m2 : methods) {
3234 if (m1 == m2) continue;
3235 if (m2.owner != m1.owner &&
3236 asSuper(m2.owner.type, m1.owner) != null) {
3237 isMin_m1 = false;
3238 break;
3239 }
3240 }
3241 if (isMin_m1)
3242 methodsMin.append(m1);
3243 }
3244 return methodsMin.toList();
3245 }
3246 // where
3247 private class MethodFilter implements Predicate<Symbol> {
3248
3249 Symbol msym;
3250 Type site;
3251
3252 MethodFilter(Symbol msym, Type site) {
3253 this.msym = msym;
3254 this.site = site;
3255 }
3256
3257 @Override
3258 public boolean test(Symbol s) {
3259 return s.kind == MTH &&
3260 s.name == msym.name &&
3261 (s.flags() & SYNTHETIC) == 0 &&
3262 s.isInheritedIn(site.tsym, Types.this) &&
3263 overrideEquivalent(memberType(site, s), memberType(site, msym));
3264 }
3265 }
3266 // </editor-fold>
3267
3268 /**
3269 * Does t have the same arguments as s? It is assumed that both
3270 * types are (possibly polymorphic) method types. Monomorphic
3271 * method types "have the same arguments", if their argument lists
3272 * are equal. Polymorphic method types "have the same arguments",
3273 * if they have the same arguments after renaming all type
3274 * variables of one to corresponding type variables in the other,
3275 * where correspondence is by position in the type parameter list.
3276 */
3277 public boolean hasSameArgs(Type t, Type s) {
3278 return hasSameArgs(t, s, true);
3279 }
3280
3281 public boolean hasSameArgs(Type t, Type s, boolean strict) {
3282 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
3283 }
3284
3285 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
3286 return hasSameArgs.visit(t, s);
3287 }
3288 // where
3289 private class HasSameArgs extends TypeRelation {
3290
3291 boolean strict;
3292
3293 public HasSameArgs(boolean strict) {
3294 this.strict = strict;
3295 }
3296
3297 public Boolean visitType(Type t, Type s) {
3298 throw new AssertionError();
3299 }
3300
3301 @Override
3302 public Boolean visitMethodType(MethodType t, Type s) {
3303 return s.hasTag(METHOD)
3304 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
3305 }
3306
3307 @Override
3308 public Boolean visitForAll(ForAll t, Type s) {
3309 if (!s.hasTag(FORALL))
3310 return strict ? false : visitMethodType(t.asMethodType(), s);
3311
3312 ForAll forAll = (ForAll)s;
3313 return hasSameBounds(t, forAll)
3314 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
3315 }
3316
3317 @Override
3318 public Boolean visitErrorType(ErrorType t, Type s) {
3319 return false;
3320 }
3321 }
3322
3323 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
3324 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
3325
3326 // </editor-fold>
3327
3328 // <editor-fold defaultstate="collapsed" desc="subst">
3329 public List<Type> subst(List<Type> ts,
3330 List<Type> from,
3331 List<Type> to) {
3332 return ts.map(new Subst(from, to));
3333 }
3334
3335 /**
3336 * Substitute all occurrences of a type in `from' with the
3337 * corresponding type in `to' in 't'. Match lists `from' and `to'
3338 * from the right: If lists have different length, discard leading
3339 * elements of the longer list.
3340 */
3341 public Type subst(Type t, List<Type> from, List<Type> to) {
3342 return t.map(new Subst(from, to));
3343 }
3344
3345 /* this class won't substitute all types for example UndetVars are never substituted, this is
3346 * by design as UndetVars are used locally during inference and shouldn't escape from inference routines,
3347 * some specialized applications could need a tailored solution
3348 */
3349 private class Subst extends StructuralTypeMapping<Void> {
3350 List<Type> from;
3351 List<Type> to;
3352
3353 public Subst(List<Type> from, List<Type> to) {
3354 int fromLength = from.length();
3355 int toLength = to.length();
3356 while (fromLength > toLength) {
3357 fromLength--;
3358 from = from.tail;
3359 }
3360 while (fromLength < toLength) {
3361 toLength--;
3362 to = to.tail;
3363 }
3364 this.from = from;
3365 this.to = to;
3366 }
3367
3368 @Override
3369 public Type visitTypeVar(TypeVar t, Void ignored) {
3370 for (List<Type> from = this.from, to = this.to;
3371 from.nonEmpty();
3372 from = from.tail, to = to.tail) {
3373 if (t.equalsIgnoreMetadata(from.head)) {
3374 return to.head.withTypeVar(t);
3375 }
3376 }
3377 return t;
3378 }
3379
3380 @Override
3381 public Type visitClassType(ClassType t, Void ignored) {
3382 if (!t.isCompound()) {
3383 return super.visitClassType(t, ignored);
3384 } else {
3385 Type st = visit(supertype(t));
3386 List<Type> is = visit(interfaces(t), ignored);
3387 if (st == supertype(t) && is == interfaces(t))
3388 return t;
3389 else
3390 return makeIntersectionType(is.prepend(st));
3391 }
3392 }
3393
3394 @Override
3395 public Type visitWildcardType(WildcardType t, Void ignored) {
3396 WildcardType t2 = (WildcardType)super.visitWildcardType(t, ignored);
3397 if (t2 != t && t.isExtendsBound() && t2.type.isExtendsBound()) {
3398 t2.type = wildUpperBound(t2.type);
3399 }
3400 return t2;
3401 }
3402
3403 @Override
3404 public Type visitForAll(ForAll t, Void ignored) {
3405 if (Type.containsAny(to, t.tvars)) {
3406 //perform alpha-renaming of free-variables in 't'
3407 //if 'to' types contain variables that are free in 't'
3408 List<Type> freevars = newInstances(t.tvars);
3409 t = new ForAll(freevars,
3410 Types.this.subst(t.qtype, t.tvars, freevars));
3411 }
3412 List<Type> tvars1 = substBounds(t.tvars, from, to);
3413 Type qtype1 = visit(t.qtype);
3414 if (tvars1 == t.tvars && qtype1 == t.qtype) {
3415 return t;
3416 } else if (tvars1 == t.tvars) {
3417 return new ForAll(tvars1, qtype1) {
3418 @Override
3419 public boolean needsStripping() {
3420 return true;
3421 }
3422 };
3423 } else {
3424 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)) {
3425 @Override
3426 public boolean needsStripping() {
3427 return true;
3428 }
3429 };
3430 }
3431 }
3432 }
3433
3434 public List<Type> substBounds(List<Type> tvars,
3435 List<Type> from,
3436 List<Type> to) {
3437 if (tvars.isEmpty())
3438 return tvars;
3439 ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
3440 boolean changed = false;
3441 // calculate new bounds
3442 for (Type t : tvars) {
3443 TypeVar tv = (TypeVar) t;
3444 Type bound = subst(tv.getUpperBound(), from, to);
3445 if (bound != tv.getUpperBound())
3446 changed = true;
3447 newBoundsBuf.append(bound);
3448 }
3449 if (!changed)
3450 return tvars;
3451 ListBuffer<Type> newTvars = new ListBuffer<>();
3452 // create new type variables without bounds
3453 for (Type t : tvars) {
3454 newTvars.append(new TypeVar(t.tsym, null, syms.botType,
3455 t.getMetadata()));
3456 }
3457 // the new bounds should use the new type variables in place
3458 // of the old
3459 List<Type> newBounds = newBoundsBuf.toList();
3460 from = tvars;
3461 to = newTvars.toList();
3462 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
3463 newBounds.head = subst(newBounds.head, from, to);
3464 }
3465 newBounds = newBoundsBuf.toList();
3466 // set the bounds of new type variables to the new bounds
3467 for (Type t : newTvars.toList()) {
3468 TypeVar tv = (TypeVar) t;
3469 tv.setUpperBound( newBounds.head );
3470 newBounds = newBounds.tail;
3471 }
3472 return newTvars.toList();
3473 }
3474
3475 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
3476 Type bound1 = subst(t.getUpperBound(), from, to);
3477 if (bound1 == t.getUpperBound())
3478 return t;
3479 else {
3480 // create new type variable without bounds
3481 TypeVar tv = new TypeVar(t.tsym, null, syms.botType,
3482 t.getMetadata());
3483 // the new bound should use the new type variable in place
3484 // of the old
3485 tv.setUpperBound( subst(bound1, List.of(t), List.of(tv)) );
3486 return tv;
3487 }
3488 }
3489 // </editor-fold>
3490
3491 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
3492 /**
3493 * Does t have the same bounds for quantified variables as s?
3494 */
3495 public boolean hasSameBounds(ForAll t, ForAll s) {
3496 List<Type> l1 = t.tvars;
3497 List<Type> l2 = s.tvars;
3498 while (l1.nonEmpty() && l2.nonEmpty() &&
3499 isSameType(l1.head.getUpperBound(),
3500 subst(l2.head.getUpperBound(),
3501 s.tvars,
3502 t.tvars))) {
3503 l1 = l1.tail;
3504 l2 = l2.tail;
3505 }
3506 return l1.isEmpty() && l2.isEmpty();
3507 }
3508 // </editor-fold>
3509
3510 // <editor-fold defaultstate="collapsed" desc="newInstances">
3511 /** Create new vector of type variables from list of variables
3512 * changing all recursive bounds from old to new list.
3513 */
3514 public List<Type> newInstances(List<Type> tvars) {
3515 List<Type> tvars1 = tvars.map(newInstanceFun);
3516 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
3517 TypeVar tv = (TypeVar) l.head;
3518 tv.setUpperBound( subst(tv.getUpperBound(), tvars, tvars1) );
3519 }
3520 return tvars1;
3521 }
3522 private static final TypeMapping<Void> newInstanceFun = new TypeMapping<Void>() {
3523 @Override
3524 public TypeVar visitTypeVar(TypeVar t, Void _unused) {
3525 return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound(), t.getMetadata());
3526 }
3527 };
3528 // </editor-fold>
3529
3530 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
3531 return original.accept(methodWithParameters, newParams);
3532 }
3533 // where
3534 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
3535 public Type visitType(Type t, List<Type> newParams) {
3536 throw new IllegalArgumentException("Not a method type: " + t);
3537 }
3538 public Type visitMethodType(MethodType t, List<Type> newParams) {
3539 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
3540 }
3541 public Type visitForAll(ForAll t, List<Type> newParams) {
3542 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
3543 }
3544 };
3545
3546 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
3547 return original.accept(methodWithThrown, newThrown);
3548 }
3549 // where
3550 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
3551 public Type visitType(Type t, List<Type> newThrown) {
3552 throw new IllegalArgumentException("Not a method type: " + t);
3553 }
3554 public Type visitMethodType(MethodType t, List<Type> newThrown) {
3555 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
3556 }
3557 public Type visitForAll(ForAll t, List<Type> newThrown) {
3558 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
3559 }
3560 };
3561
3562 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
3563 return original.accept(methodWithReturn, newReturn);
3564 }
3565 // where
3566 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3567 public Type visitType(Type t, Type newReturn) {
3568 throw new IllegalArgumentException("Not a method type: " + t);
3569 }
3570 public Type visitMethodType(MethodType t, Type newReturn) {
3571 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym) {
3572 @Override
3573 public Type baseType() {
3574 return t;
3575 }
3576 };
3577 }
3578 public Type visitForAll(ForAll t, Type newReturn) {
3579 return new ForAll(t.tvars, t.qtype.accept(this, newReturn)) {
3580 @Override
3581 public Type baseType() {
3582 return t;
3583 }
3584 };
3585 }
3586 };
3587
3588 // <editor-fold defaultstate="collapsed" desc="createErrorType">
3589 public Type createErrorType(Type originalType) {
3590 return new ErrorType(originalType, syms.errSymbol);
3591 }
3592
3593 public Type createErrorType(ClassSymbol c, Type originalType) {
3594 return new ErrorType(c, originalType);
3595 }
3596
3597 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3598 return new ErrorType(name, container, originalType);
3599 }
3600 // </editor-fold>
3601
3602 // <editor-fold defaultstate="collapsed" desc="rank">
3603 /**
3604 * The rank of a class is the length of the longest path between
3605 * the class and java.lang.Object in the class inheritance
3606 * graph. Undefined for all but reference types.
3607 */
3608 public int rank(Type t) {
3609 switch(t.getTag()) {
3610 case CLASS: {
3611 ClassType cls = (ClassType)t;
3612 if (cls.rank_field < 0) {
3613 Name fullname = cls.tsym.getQualifiedName();
3614 if (fullname == names.java_lang_Object)
3615 cls.rank_field = 0;
3616 else {
3617 int r = rank(supertype(cls));
3618 for (List<Type> l = interfaces(cls);
3619 l.nonEmpty();
3620 l = l.tail) {
3621 if (rank(l.head) > r)
3622 r = rank(l.head);
3623 }
3624 cls.rank_field = r + 1;
3625 }
3626 }
3627 return cls.rank_field;
3628 }
3629 case TYPEVAR: {
3630 TypeVar tvar = (TypeVar)t;
3631 if (tvar.rank_field < 0) {
3632 int r = rank(supertype(tvar));
3633 for (List<Type> l = interfaces(tvar);
3634 l.nonEmpty();
3635 l = l.tail) {
3636 if (rank(l.head) > r) r = rank(l.head);
3637 }
3638 tvar.rank_field = r + 1;
3639 }
3640 return tvar.rank_field;
3641 }
3642 case ERROR:
3643 case NONE:
3644 return 0;
3645 default:
3646 throw new AssertionError();
3647 }
3648 }
3649 // </editor-fold>
3650
3651 /**
3652 * Helper method for generating a string representation of a given type
3653 * accordingly to a given locale
3654 */
3655 public String toString(Type t, Locale locale) {
3656 return Printer.createStandardPrinter(messages).visit(t, locale);
3657 }
3658
3659 /**
3660 * Helper method for generating a string representation of a given type
3661 * accordingly to a given locale
3662 */
3663 public String toString(Symbol t, Locale locale) {
3664 return Printer.createStandardPrinter(messages).visit(t, locale);
3665 }
3666
3667 // <editor-fold defaultstate="collapsed" desc="toString">
3668 /**
3669 * This toString is slightly more descriptive than the one on Type.
3670 *
3671 * @deprecated Types.toString(Type t, Locale l) provides better support
3672 * for localization
3673 */
3674 @Deprecated
3675 public String toString(Type t) {
3676 if (t.hasTag(FORALL)) {
3677 ForAll forAll = (ForAll)t;
3678 return typaramsString(forAll.tvars) + forAll.qtype;
3679 }
3680 return "" + t;
3681 }
3682 // where
3683 private String typaramsString(List<Type> tvars) {
3684 StringBuilder s = new StringBuilder();
3685 s.append('<');
3686 boolean first = true;
3687 for (Type t : tvars) {
3688 if (!first) s.append(", ");
3689 first = false;
3690 appendTyparamString(((TypeVar)t), s);
3691 }
3692 s.append('>');
3693 return s.toString();
3694 }
3695 private void appendTyparamString(TypeVar t, StringBuilder buf) {
3696 buf.append(t);
3697 if (t.getUpperBound() == null ||
3698 t.getUpperBound().tsym.getQualifiedName() == names.java_lang_Object)
3699 return;
3700 buf.append(" extends "); // Java syntax; no need for i18n
3701 Type bound = t.getUpperBound();
3702 if (!bound.isCompound()) {
3703 buf.append(bound);
3704 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3705 buf.append(supertype(t));
3706 for (Type intf : interfaces(t)) {
3707 buf.append('&');
3708 buf.append(intf);
3709 }
3710 } else {
3711 // No superclass was given in bounds.
3712 // In this case, supertype is Object, erasure is first interface.
3713 boolean first = true;
3714 for (Type intf : interfaces(t)) {
3715 if (!first) buf.append('&');
3716 first = false;
3717 buf.append(intf);
3718 }
3719 }
3720 }
3721 // </editor-fold>
3722
3723 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3724 /**
3725 * A cache for closures.
3726 *
3727 * <p>A closure is a list of all the supertypes and interfaces of
3728 * a class or interface type, ordered by ClassSymbol.precedes
3729 * (that is, subclasses come first, arbitrarily but fixed
3730 * otherwise).
3731 */
3732 private Map<Type,List<Type>> closureCache = new HashMap<>();
3733
3734 /**
3735 * Returns the closure of a class or interface type.
3736 */
3737 public List<Type> closure(Type t) {
3738 List<Type> cl = closureCache.get(t);
3739 if (cl == null) {
3740 Type st = supertype(t);
3741 if (!t.isCompound()) {
3742 if (st.hasTag(CLASS)) {
3743 cl = insert(closure(st), t);
3744 } else if (st.hasTag(TYPEVAR)) {
3745 cl = closure(st).prepend(t);
3746 } else {
3747 cl = List.of(t);
3748 }
3749 } else {
3750 cl = closure(supertype(t));
3751 }
3752 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3753 cl = union(cl, closure(l.head));
3754 closureCache.put(t, cl);
3755 }
3756 return cl;
3757 }
3758
3759 /**
3760 * Collect types into a new closure (using a {@code ClosureHolder})
3761 */
3762 public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3763 return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip),
3764 ClosureHolder::add,
3765 ClosureHolder::merge,
3766 ClosureHolder::closure);
3767 }
3768 //where
3769 class ClosureHolder {
3770 List<Type> closure;
3771 final boolean minClosure;
3772 final BiPredicate<Type, Type> shouldSkip;
3773
3774 ClosureHolder(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3775 this.closure = List.nil();
3776 this.minClosure = minClosure;
3777 this.shouldSkip = shouldSkip;
3778 }
3779
3780 void add(Type type) {
3781 closure = insert(closure, type, shouldSkip);
3782 }
3783
3784 ClosureHolder merge(ClosureHolder other) {
3785 closure = union(closure, other.closure, shouldSkip);
3786 return this;
3787 }
3788
3789 List<Type> closure() {
3790 return minClosure ? closureMin(closure) : closure;
3791 }
3792 }
3793
3794 BiPredicate<Type, Type> basicClosureSkip = (t1, t2) -> t1.tsym == t2.tsym;
3795
3796 /**
3797 * Insert a type in a closure
3798 */
3799 public List<Type> insert(List<Type> cl, Type t, BiPredicate<Type, Type> shouldSkip) {
3800 if (cl.isEmpty()) {
3801 return cl.prepend(t);
3802 } else if (shouldSkip.test(t, cl.head)) {
3803 return cl;
3804 } else if (t.tsym.precedes(cl.head.tsym, this)) {
3805 return cl.prepend(t);
3806 } else {
3807 // t comes after head, or the two are unrelated
3808 return insert(cl.tail, t, shouldSkip).prepend(cl.head);
3809 }
3810 }
3811
3812 public List<Type> insert(List<Type> cl, Type t) {
3813 return insert(cl, t, basicClosureSkip);
3814 }
3815
3816 /**
3817 * Form the union of two closures
3818 */
3819 public List<Type> union(List<Type> cl1, List<Type> cl2, BiPredicate<Type, Type> shouldSkip) {
3820 if (cl1.isEmpty()) {
3821 return cl2;
3822 } else if (cl2.isEmpty()) {
3823 return cl1;
3824 } else if (shouldSkip.test(cl1.head, cl2.head)) {
3825 return union(cl1.tail, cl2.tail, shouldSkip).prepend(cl1.head);
3826 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3827 return union(cl1, cl2.tail, shouldSkip).prepend(cl2.head);
3828 } else {
3829 return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
3830 }
3831 }
3832
3833 public List<Type> union(List<Type> cl1, List<Type> cl2) {
3834 return union(cl1, cl2, basicClosureSkip);
3835 }
3836
3837 /**
3838 * Intersect two closures
3839 */
3840 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3841 if (cl1 == cl2)
3842 return cl1;
3843 if (cl1.isEmpty() || cl2.isEmpty())
3844 return List.nil();
3845 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3846 return intersect(cl1.tail, cl2);
3847 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3848 return intersect(cl1, cl2.tail);
3849 if (isSameType(cl1.head, cl2.head))
3850 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3851 if (cl1.head.tsym == cl2.head.tsym &&
3852 cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
3853 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3854 Type merge = merge(cl1.head,cl2.head);
3855 return intersect(cl1.tail, cl2.tail).prepend(merge);
3856 }
3857 if (cl1.head.isRaw() || cl2.head.isRaw())
3858 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3859 }
3860 return intersect(cl1.tail, cl2.tail);
3861 }
3862 // where
3863 class TypePair {
3864 final Type t1;
3865 final Type t2;;
3866
3867 TypePair(Type t1, Type t2) {
3868 this.t1 = t1;
3869 this.t2 = t2;
3870 }
3871 @Override
3872 public int hashCode() {
3873 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3874 }
3875 @Override
3876 public boolean equals(Object obj) {
3877 return (obj instanceof TypePair typePair)
3878 && isSameType(t1, typePair.t1)
3879 && isSameType(t2, typePair.t2);
3880 }
3881 }
3882 Set<TypePair> mergeCache = new HashSet<>();
3883 private Type merge(Type c1, Type c2) {
3884 ClassType class1 = (ClassType) c1;
3885 List<Type> act1 = class1.getTypeArguments();
3886 ClassType class2 = (ClassType) c2;
3887 List<Type> act2 = class2.getTypeArguments();
3888 ListBuffer<Type> merged = new ListBuffer<>();
3889 List<Type> typarams = class1.tsym.type.getTypeArguments();
3890
3891 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3892 if (containsType(act1.head, act2.head)) {
3893 merged.append(act1.head);
3894 } else if (containsType(act2.head, act1.head)) {
3895 merged.append(act2.head);
3896 } else {
3897 TypePair pair = new TypePair(c1, c2);
3898 Type m;
3899 if (mergeCache.add(pair)) {
3900 m = new WildcardType(lub(wildUpperBound(act1.head),
3901 wildUpperBound(act2.head)),
3902 BoundKind.EXTENDS,
3903 syms.boundClass);
3904 mergeCache.remove(pair);
3905 } else {
3906 m = new WildcardType(syms.objectType,
3907 BoundKind.UNBOUND,
3908 syms.boundClass);
3909 }
3910 merged.append(m.withTypeVar(typarams.head));
3911 }
3912 act1 = act1.tail;
3913 act2 = act2.tail;
3914 typarams = typarams.tail;
3915 }
3916 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3917 // There is no spec detailing how type annotations are to
3918 // be inherited. So set it to noAnnotations for now
3919 return new ClassType(class1.getEnclosingType(), merged.toList(),
3920 class1.tsym);
3921 }
3922
3923 /**
3924 * Return the minimum type of a closure, a compound type if no
3925 * unique minimum exists.
3926 */
3927 private Type compoundMin(List<Type> cl) {
3928 if (cl.isEmpty()) return syms.objectType;
3929 List<Type> compound = closureMin(cl);
3930 if (compound.isEmpty())
3931 return null;
3932 else if (compound.tail.isEmpty())
3933 return compound.head;
3934 else
3935 return makeIntersectionType(compound);
3936 }
3937
3938 /**
3939 * Return the minimum types of a closure, suitable for computing
3940 * compoundMin or glb.
3941 */
3942 private List<Type> closureMin(List<Type> cl) {
3943 ListBuffer<Type> classes = new ListBuffer<>();
3944 ListBuffer<Type> interfaces = new ListBuffer<>();
3945 Set<Type> toSkip = new HashSet<>();
3946 while (!cl.isEmpty()) {
3947 Type current = cl.head;
3948 boolean keep = !toSkip.contains(current);
3949 if (keep && current.hasTag(TYPEVAR)) {
3950 // skip lower-bounded variables with a subtype in cl.tail
3951 for (Type t : cl.tail) {
3952 if (isSubtypeNoCapture(t, current)) {
3953 keep = false;
3954 break;
3955 }
3956 }
3957 }
3958 if (keep) {
3959 if (current.isInterface())
3960 interfaces.append(current);
3961 else
3962 classes.append(current);
3963 for (Type t : cl.tail) {
3964 // skip supertypes of 'current' in cl.tail
3965 if (isSubtypeNoCapture(current, t))
3966 toSkip.add(t);
3967 }
3968 }
3969 cl = cl.tail;
3970 }
3971 return classes.appendList(interfaces).toList();
3972 }
3973
3974 /**
3975 * Return the least upper bound of list of types. if the lub does
3976 * not exist return null.
3977 */
3978 public Type lub(List<Type> ts) {
3979 return lub(ts.toArray(new Type[ts.length()]));
3980 }
3981
3982 /**
3983 * Return the least upper bound (lub) of set of types. If the lub
3984 * does not exist return the type of null (bottom).
3985 */
3986 public Type lub(Type... ts) {
3987 final int UNKNOWN_BOUND = 0;
3988 final int ARRAY_BOUND = 1;
3989 final int CLASS_BOUND = 2;
3990
3991 int[] kinds = new int[ts.length];
3992
3993 int boundkind = UNKNOWN_BOUND;
3994 for (int i = 0 ; i < ts.length ; i++) {
3995 Type t = ts[i];
3996 switch (t.getTag()) {
3997 case CLASS:
3998 boundkind |= kinds[i] = CLASS_BOUND;
3999 break;
4000 case ARRAY:
4001 boundkind |= kinds[i] = ARRAY_BOUND;
4002 break;
4003 case TYPEVAR:
4004 do {
4005 t = t.getUpperBound();
4006 } while (t.hasTag(TYPEVAR));
4007 if (t.hasTag(ARRAY)) {
4008 boundkind |= kinds[i] = ARRAY_BOUND;
4009 } else {
4010 boundkind |= kinds[i] = CLASS_BOUND;
4011 }
4012 break;
4013 default:
4014 kinds[i] = UNKNOWN_BOUND;
4015 if (t.isPrimitive())
4016 return syms.errType;
4017 }
4018 }
4019 switch (boundkind) {
4020 case 0:
4021 return syms.botType;
4022
4023 case ARRAY_BOUND:
4024 // calculate lub(A[], B[])
4025 Type[] elements = new Type[ts.length];
4026 for (int i = 0 ; i < ts.length ; i++) {
4027 Type elem = elements[i] = elemTypeFun.apply(ts[i]);
4028 if (elem.isPrimitive()) {
4029 // if a primitive type is found, then return
4030 // arraySuperType unless all the types are the
4031 // same
4032 Type first = ts[0];
4033 for (int j = 1 ; j < ts.length ; j++) {
4034 if (!isSameType(first, ts[j])) {
4035 // lub(int[], B[]) is Cloneable & Serializable
4036 return arraySuperType();
4037 }
4038 }
4039 // all the array types are the same, return one
4040 // lub(int[], int[]) is int[]
4041 return first;
4042 }
4043 }
4044 // lub(A[], B[]) is lub(A, B)[]
4045 return new ArrayType(lub(elements), syms.arrayClass);
4046
4047 case CLASS_BOUND:
4048 // calculate lub(A, B)
4049 int startIdx = 0;
4050 for (int i = 0; i < ts.length ; i++) {
4051 Type t = ts[i];
4052 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) {
4053 break;
4054 } else {
4055 startIdx++;
4056 }
4057 }
4058 Assert.check(startIdx < ts.length);
4059 //step 1 - compute erased candidate set (EC)
4060 List<Type> cl = erasedSupertypes(ts[startIdx]);
4061 for (int i = startIdx + 1 ; i < ts.length ; i++) {
4062 Type t = ts[i];
4063 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
4064 cl = intersect(cl, erasedSupertypes(t));
4065 }
4066 //step 2 - compute minimal erased candidate set (MEC)
4067 List<Type> mec = closureMin(cl);
4068 //step 3 - for each element G in MEC, compute lci(Inv(G))
4069 List<Type> candidates = List.nil();
4070 for (Type erasedSupertype : mec) {
4071 List<Type> lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym));
4072 for (int i = startIdx + 1 ; i < ts.length ; i++) {
4073 Type superType = asSuper(ts[i], erasedSupertype.tsym);
4074 lci = intersect(lci, superType != null ? List.of(superType) : List.nil());
4075 }
4076 candidates = candidates.appendList(lci);
4077 }
4078 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
4079 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
4080 return compoundMin(candidates);
4081
4082 default:
4083 // calculate lub(A, B[])
4084 List<Type> classes = List.of(arraySuperType());
4085 for (int i = 0 ; i < ts.length ; i++) {
4086 if (kinds[i] != ARRAY_BOUND) // Filter out any arrays
4087 classes = classes.prepend(ts[i]);
4088 }
4089 // lub(A, B[]) is lub(A, arraySuperType)
4090 return lub(classes);
4091 }
4092 }
4093 // where
4094 List<Type> erasedSupertypes(Type t) {
4095 ListBuffer<Type> buf = new ListBuffer<>();
4096 for (Type sup : closure(t)) {
4097 if (sup.hasTag(TYPEVAR)) {
4098 buf.append(sup);
4099 } else {
4100 buf.append(erasure(sup));
4101 }
4102 }
4103 return buf.toList();
4104 }
4105
4106 private Type arraySuperType;
4107 private Type arraySuperType() {
4108 // initialized lazily to avoid problems during compiler startup
4109 if (arraySuperType == null) {
4110 // JLS 10.8: all arrays implement Cloneable and Serializable.
4111 arraySuperType = makeIntersectionType(List.of(syms.serializableType,
4112 syms.cloneableType), true);
4113 }
4114 return arraySuperType;
4115 }
4116 // </editor-fold>
4117
4118 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
4119 public Type glb(List<Type> ts) {
4120 Type t1 = ts.head;
4121 for (Type t2 : ts.tail) {
4122 if (t1.isErroneous())
4123 return t1;
4124 t1 = glb(t1, t2);
4125 }
4126 return t1;
4127 }
4128 //where
4129 public Type glb(Type t, Type s) {
4130 if (s == null)
4131 return t;
4132 else if (t.isPrimitive() || s.isPrimitive())
4133 return syms.errType;
4134 else if (isSubtypeNoCapture(t, s))
4135 return t;
4136 else if (isSubtypeNoCapture(s, t))
4137 return s;
4138
4139 List<Type> closure = union(closure(t), closure(s));
4140 return glbFlattened(closure, t);
4141 }
4142 //where
4143 /**
4144 * Perform glb for a list of non-primitive, non-error, non-compound types;
4145 * redundant elements are removed. Bounds should be ordered according to
4146 * {@link Symbol#precedes(TypeSymbol,Types)}.
4147 *
4148 * @param flatBounds List of type to glb
4149 * @param errT Original type to use if the result is an error type
4150 */
4151 private Type glbFlattened(List<Type> flatBounds, Type errT) {
4152 List<Type> bounds = closureMin(flatBounds);
4153
4154 if (bounds.isEmpty()) { // length == 0
4155 return syms.objectType;
4156 } else if (bounds.tail.isEmpty()) { // length == 1
4157 return bounds.head;
4158 } else { // length > 1
4159 int classCount = 0;
4160 List<Type> cvars = List.nil();
4161 List<Type> lowers = List.nil();
4162 for (Type bound : bounds) {
4163 if (!bound.isInterface()) {
4164 classCount++;
4165 Type lower = cvarLowerBound(bound);
4166 if (bound != lower && !lower.hasTag(BOT)) {
4167 cvars = cvars.append(bound);
4168 lowers = lowers.append(lower);
4169 }
4170 }
4171 }
4172 if (classCount > 1) {
4173 if (lowers.isEmpty()) {
4174 return createErrorType(errT);
4175 } else {
4176 // try again with lower bounds included instead of capture variables
4177 List<Type> newBounds = bounds.diff(cvars).appendList(lowers);
4178 return glb(newBounds);
4179 }
4180 }
4181 }
4182 return makeIntersectionType(bounds);
4183 }
4184 // </editor-fold>
4185
4186 // <editor-fold defaultstate="collapsed" desc="hashCode">
4187 /**
4188 * Compute a hash code on a type.
4189 */
4190 public int hashCode(Type t) {
4191 return hashCode(t, false);
4192 }
4193
4194 public int hashCode(Type t, boolean strict) {
4195 return strict ?
4196 hashCodeStrictVisitor.visit(t) :
4197 hashCodeVisitor.visit(t);
4198 }
4199 // where
4200 private static final HashCodeVisitor hashCodeVisitor = new HashCodeVisitor();
4201 private static final HashCodeVisitor hashCodeStrictVisitor = new HashCodeVisitor() {
4202 @Override
4203 public Integer visitTypeVar(TypeVar t, Void ignored) {
4204 return System.identityHashCode(t);
4205 }
4206 };
4207
4208 private static class HashCodeVisitor extends UnaryVisitor<Integer> {
4209 public Integer visitType(Type t, Void ignored) {
4210 return t.getTag().ordinal();
4211 }
4212
4213 @Override
4214 public Integer visitClassType(ClassType t, Void ignored) {
4215 int result = visit(t.getEnclosingType());
4216 result *= 127;
4217 result += t.tsym.flatName().hashCode();
4218 for (Type s : t.getTypeArguments()) {
4219 result *= 127;
4220 result += visit(s);
4221 }
4222 return result;
4223 }
4224
4225 @Override
4226 public Integer visitMethodType(MethodType t, Void ignored) {
4227 int h = METHOD.ordinal();
4228 for (List<Type> thisargs = t.argtypes;
4229 thisargs.tail != null;
4230 thisargs = thisargs.tail)
4231 h = (h << 5) + visit(thisargs.head);
4232 return (h << 5) + visit(t.restype);
4233 }
4234
4235 @Override
4236 public Integer visitWildcardType(WildcardType t, Void ignored) {
4237 int result = t.kind.hashCode();
4238 if (t.type != null) {
4239 result *= 127;
4240 result += visit(t.type);
4241 }
4242 return result;
4243 }
4244
4245 @Override
4246 public Integer visitArrayType(ArrayType t, Void ignored) {
4247 return visit(t.elemtype) + 12;
4248 }
4249
4250 @Override
4251 public Integer visitTypeVar(TypeVar t, Void ignored) {
4252 return System.identityHashCode(t);
4253 }
4254
4255 @Override
4256 public Integer visitUndetVar(UndetVar t, Void ignored) {
4257 return System.identityHashCode(t);
4258 }
4259
4260 @Override
4261 public Integer visitErrorType(ErrorType t, Void ignored) {
4262 return 0;
4263 }
4264 }
4265 // </editor-fold>
4266
4267 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
4268 /**
4269 * Does t have a result that is a subtype of the result type of s,
4270 * suitable for covariant returns? It is assumed that both types
4271 * are (possibly polymorphic) method types. Monomorphic method
4272 * types are handled in the obvious way. Polymorphic method types
4273 * require renaming all type variables of one to corresponding
4274 * type variables in the other, where correspondence is by
4275 * position in the type parameter list. */
4276 public boolean resultSubtype(Type t, Type s, Warner warner) {
4277 List<Type> tvars = t.getTypeArguments();
4278 List<Type> svars = s.getTypeArguments();
4279 Type tres = t.getReturnType();
4280 Type sres = subst(s.getReturnType(), svars, tvars);
4281 return covariantReturnType(tres, sres, warner);
4282 }
4283
4284 /**
4285 * Return-Type-Substitutable.
4286 * @jls 8.4.5 Method Result
4287 */
4288 public boolean returnTypeSubstitutable(Type r1, Type r2) {
4289 if (hasSameArgs(r1, r2))
4290 return resultSubtype(r1, r2, noWarnings);
4291 else
4292 return covariantReturnType(r1.getReturnType(),
4293 erasure(r2.getReturnType()),
4294 noWarnings);
4295 }
4296
4297 public boolean returnTypeSubstitutable(Type r1,
4298 Type r2, Type r2res,
4299 Warner warner) {
4300 if (isSameType(r1.getReturnType(), r2res))
4301 return true;
4302 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
4303 return false;
4304
4305 if (hasSameArgs(r1, r2))
4306 return covariantReturnType(r1.getReturnType(), r2res, warner);
4307 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
4308 return true;
4309 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
4310 return false;
4311 warner.warn(LintCategory.UNCHECKED);
4312 return true;
4313 }
4314
4315 /**
4316 * Is t an appropriate return type in an overrider for a
4317 * method that returns s?
4318 */
4319 public boolean covariantReturnType(Type t, Type s, Warner warner) {
4320 return
4321 isSameType(t, s) ||
4322 !t.isPrimitive() &&
4323 !s.isPrimitive() &&
4324 isAssignable(t, s, warner);
4325 }
4326 // </editor-fold>
4327
4328 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
4329 /**
4330 * Return the class that boxes the given primitive.
4331 */
4332 public ClassSymbol boxedClass(Type t) {
4333 return syms.enterClass(syms.java_base, syms.boxedName[t.getTag().ordinal()]);
4334 }
4335
4336 /**
4337 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
4338 */
4339 public Type boxedTypeOrType(Type t) {
4340 return t.isPrimitive() ?
4341 boxedClass(t).type :
4342 t;
4343 }
4344
4345 /**
4346 * Return the primitive type corresponding to a boxed type.
4347 */
4348 public Type unboxedType(Type t) {
4349 if (t.hasTag(ERROR))
4350 return Type.noType;
4351 for (int i=0; i<syms.boxedName.length; i++) {
4352 Name box = syms.boxedName[i];
4353 if (box != null &&
4354 asSuper(t, syms.enterClass(syms.java_base, box)) != null)
4355 return syms.typeOfTag[i];
4356 }
4357 return Type.noType;
4358 }
4359
4360 /**
4361 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
4362 */
4363 public Type unboxedTypeOrType(Type t) {
4364 Type unboxedType = unboxedType(t);
4365 return unboxedType.hasTag(NONE) ? t : unboxedType;
4366 }
4367 // </editor-fold>
4368
4369 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
4370 /*
4371 * JLS 5.1.10 Capture Conversion:
4372 *
4373 * Let G name a generic type declaration with n formal type
4374 * parameters A1 ... An with corresponding bounds U1 ... Un. There
4375 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
4376 * where, for 1 <= i <= n:
4377 *
4378 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
4379 * Si is a fresh type variable whose upper bound is
4380 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
4381 * type.
4382 *
4383 * + If Ti is a wildcard type argument of the form ? extends Bi,
4384 * then Si is a fresh type variable whose upper bound is
4385 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
4386 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
4387 * a compile-time error if for any two classes (not interfaces)
4388 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
4389 *
4390 * + If Ti is a wildcard type argument of the form ? super Bi,
4391 * then Si is a fresh type variable whose upper bound is
4392 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
4393 *
4394 * + Otherwise, Si = Ti.
4395 *
4396 * Capture conversion on any type other than a parameterized type
4397 * (4.5) acts as an identity conversion (5.1.1). Capture
4398 * conversions never require a special action at run time and
4399 * therefore never throw an exception at run time.
4400 *
4401 * Capture conversion is not applied recursively.
4402 */
4403 /**
4404 * Capture conversion as specified by the JLS.
4405 */
4406
4407 public List<Type> capture(List<Type> ts) {
4408 List<Type> buf = List.nil();
4409 for (Type t : ts) {
4410 buf = buf.prepend(capture(t));
4411 }
4412 return buf.reverse();
4413 }
4414
4415 public Type capture(Type t) {
4416 if (!t.hasTag(CLASS)) {
4417 return t;
4418 }
4419 if (t.getEnclosingType() != Type.noType) {
4420 Type capturedEncl = capture(t.getEnclosingType());
4421 if (capturedEncl != t.getEnclosingType()) {
4422 Type type1 = memberType(capturedEncl, t.tsym);
4423 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
4424 }
4425 }
4426 ClassType cls = (ClassType)t;
4427 if (cls.isRaw() || !cls.isParameterized())
4428 return cls;
4429
4430 ClassType G = (ClassType)cls.asElement().asType();
4431 List<Type> A = G.getTypeArguments();
4432 List<Type> T = cls.getTypeArguments();
4433 List<Type> S = freshTypeVariables(T);
4434
4435 List<Type> currentA = A;
4436 List<Type> currentT = T;
4437 List<Type> currentS = S;
4438 boolean captured = false;
4439 while (!currentA.isEmpty() &&
4440 !currentT.isEmpty() &&
4441 !currentS.isEmpty()) {
4442 if (currentS.head != currentT.head) {
4443 captured = true;
4444 WildcardType Ti = (WildcardType)currentT.head;
4445 Type Ui = currentA.head.getUpperBound();
4446 CapturedType Si = (CapturedType)currentS.head;
4447 if (Ui == null)
4448 Ui = syms.objectType;
4449 switch (Ti.kind) {
4450 case UNBOUND:
4451 Si.setUpperBound( subst(Ui, A, S) );
4452 Si.lower = syms.botType;
4453 break;
4454 case EXTENDS:
4455 Si.setUpperBound( glb(Ti.getExtendsBound(), subst(Ui, A, S)) );
4456 Si.lower = syms.botType;
4457 break;
4458 case SUPER:
4459 Si.setUpperBound( subst(Ui, A, S) );
4460 Si.lower = Ti.getSuperBound();
4461 break;
4462 }
4463 Type tmpBound = Si.getUpperBound().hasTag(UNDETVAR) ? ((UndetVar)Si.getUpperBound()).qtype : Si.getUpperBound();
4464 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
4465 if (!Si.getUpperBound().hasTag(ERROR) &&
4466 !Si.lower.hasTag(ERROR) &&
4467 isSameType(tmpBound, tmpLower)) {
4468 currentS.head = Si.getUpperBound();
4469 }
4470 }
4471 currentA = currentA.tail;
4472 currentT = currentT.tail;
4473 currentS = currentS.tail;
4474 }
4475 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
4476 return erasure(t); // some "rare" type involved
4477
4478 if (captured)
4479 return new ClassType(cls.getEnclosingType(), S, cls.tsym,
4480 cls.getMetadata());
4481 else
4482 return t;
4483 }
4484 // where
4485 public List<Type> freshTypeVariables(List<Type> types) {
4486 ListBuffer<Type> result = new ListBuffer<>();
4487 for (Type t : types) {
4488 if (t.hasTag(WILDCARD)) {
4489 Type bound = ((WildcardType)t).getExtendsBound();
4490 if (bound == null)
4491 bound = syms.objectType;
4492 result.append(new CapturedType(capturedName,
4493 syms.noSymbol,
4494 bound,
4495 syms.botType,
4496 (WildcardType)t));
4497 } else {
4498 result.append(t);
4499 }
4500 }
4501 return result.toList();
4502 }
4503 // </editor-fold>
4504
4505 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
4506 private boolean sideCast(Type from, Type to, Warner warn) {
4507 // We are casting from type $from$ to type $to$, which are
4508 // non-final unrelated types. This method
4509 // tries to reject a cast by transferring type parameters
4510 // from $to$ to $from$ by common superinterfaces.
4511 boolean reverse = false;
4512 Type target = to;
4513 if ((to.tsym.flags() & INTERFACE) == 0) {
4514 Assert.check((from.tsym.flags() & INTERFACE) != 0);
4515 reverse = true;
4516 to = from;
4517 from = target;
4518 }
4519 List<Type> commonSupers = supertypeClosure(to, erasure(from));
4520 boolean giveWarning = commonSupers.isEmpty();
4521 // The arguments to the supers could be unified here to
4522 // get a more accurate analysis
4523 while (commonSupers.nonEmpty()) {
4524 Type t1 = asSuper(from, commonSupers.head.tsym);
4525 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
4526 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4527 return false;
4528 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
4529 commonSupers = commonSupers.tail;
4530 }
4531 if (giveWarning && !isReifiable(reverse ? from : to))
4532 warn.warn(LintCategory.UNCHECKED);
4533 return true;
4534 }
4535
4536 private boolean sideCastFinal(Type from, Type to, Warner warn) {
4537 // We are casting from type $from$ to type $to$, which are
4538 // unrelated types one of which is final and the other of
4539 // which is an interface. This method
4540 // tries to reject a cast by transferring type parameters
4541 // from the final class to the interface.
4542 boolean reverse = false;
4543 Type target = to;
4544 if ((to.tsym.flags() & INTERFACE) == 0) {
4545 Assert.check((from.tsym.flags() & INTERFACE) != 0);
4546 reverse = true;
4547 to = from;
4548 from = target;
4549 }
4550 Assert.check((from.tsym.flags() & FINAL) != 0);
4551 Type t1 = asSuper(from, to.tsym);
4552 if (t1 == null) return false;
4553 Type t2 = to;
4554 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4555 return false;
4556 if (!isReifiable(target) &&
4557 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
4558 warn.warn(LintCategory.UNCHECKED);
4559 return true;
4560 }
4561
4562 private boolean giveWarning(Type from, Type to) {
4563 List<Type> bounds = to.isCompound() ?
4564 directSupertypes(to) : List.of(to);
4565 for (Type b : bounds) {
4566 Type subFrom = asSub(from, b.tsym);
4567 if (b.isParameterized() &&
4568 (!(isUnbounded(b) ||
4569 isSubtype(from, b) ||
4570 ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
4571 return true;
4572 }
4573 }
4574 return false;
4575 }
4576
4577 private List<Type> supertypeClosure(Type t, Type s) {
4578 List<Type> cl = List.nil();
4579 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
4580 if (isSubtype(s, erasure(l.head))) {
4581 cl = insert(cl, l.head);
4582 } else {
4583 cl = union(cl, supertypeClosure(l.head, s));
4584 }
4585 }
4586 return cl;
4587 }
4588
4589 private boolean containsTypeEquivalent(Type t, Type s) {
4590 return isSameType(t, s) || // shortcut
4591 containsType(t, s) && containsType(s, t);
4592 }
4593
4594 // <editor-fold defaultstate="collapsed" desc="adapt">
4595 /**
4596 * Adapt a type by computing a substitution which maps a source
4597 * type to a target type.
4598 *
4599 * @param source the source type
4600 * @param target the target type
4601 * @param from the type variables of the computed substitution
4602 * @param to the types of the computed substitution.
4603 */
4604 public void adapt(Type source,
4605 Type target,
4606 ListBuffer<Type> from,
4607 ListBuffer<Type> to) throws AdaptFailure {
4608 new Adapter(from, to).adapt(source, target);
4609 }
4610
4611 class Adapter extends SimpleVisitor<Void, Type> {
4612
4613 ListBuffer<Type> from;
4614 ListBuffer<Type> to;
4615 Map<Symbol,Type> mapping;
4616
4617 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
4618 this.from = from;
4619 this.to = to;
4620 mapping = new HashMap<>();
4621 }
4622
4623 public void adapt(Type source, Type target) throws AdaptFailure {
4624 visit(source, target);
4625 List<Type> fromList = from.toList();
4626 List<Type> toList = to.toList();
4627 while (!fromList.isEmpty()) {
4628 Type val = mapping.get(fromList.head.tsym);
4629 if (toList.head != val)
4630 toList.head = val;
4631 fromList = fromList.tail;
4632 toList = toList.tail;
4633 }
4634 }
4635
4636 @Override
4637 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
4638 if (target.hasTag(CLASS))
4639 adaptRecursive(source.allparams(), target.allparams());
4640 return null;
4641 }
4642
4643 @Override
4644 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
4645 if (target.hasTag(ARRAY))
4646 adaptRecursive(elemtype(source), elemtype(target));
4647 return null;
4648 }
4649
4650 @Override
4651 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
4652 if (source.isExtendsBound())
4653 adaptRecursive(wildUpperBound(source), wildUpperBound(target));
4654 else if (source.isSuperBound())
4655 adaptRecursive(wildLowerBound(source), wildLowerBound(target));
4656 return null;
4657 }
4658
4659 @Override
4660 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
4661 // Check to see if there is
4662 // already a mapping for $source$, in which case
4663 // the old mapping will be merged with the new
4664 Type val = mapping.get(source.tsym);
4665 if (val != null) {
4666 if (val.isSuperBound() && target.isSuperBound()) {
4667 val = isSubtype(wildLowerBound(val), wildLowerBound(target))
4668 ? target : val;
4669 } else if (val.isExtendsBound() && target.isExtendsBound()) {
4670 val = isSubtype(wildUpperBound(val), wildUpperBound(target))
4671 ? val : target;
4672 } else if (!isSameType(val, target)) {
4673 throw new AdaptFailure();
4674 }
4675 } else {
4676 val = target;
4677 from.append(source);
4678 to.append(target);
4679 }
4680 mapping.put(source.tsym, val);
4681 return null;
4682 }
4683
4684 @Override
4685 public Void visitType(Type source, Type target) {
4686 return null;
4687 }
4688
4689 private Set<TypePair> cache = new HashSet<>();
4690
4691 private void adaptRecursive(Type source, Type target) {
4692 TypePair pair = new TypePair(source, target);
4693 if (cache.add(pair)) {
4694 try {
4695 visit(source, target);
4696 } finally {
4697 cache.remove(pair);
4698 }
4699 }
4700 }
4701
4702 private void adaptRecursive(List<Type> source, List<Type> target) {
4703 if (source.length() == target.length()) {
4704 while (source.nonEmpty()) {
4705 adaptRecursive(source.head, target.head);
4706 source = source.tail;
4707 target = target.tail;
4708 }
4709 }
4710 }
4711 }
4712
4713 public static class AdaptFailure extends RuntimeException {
4714 static final long serialVersionUID = -7490231548272701566L;
4715 }
4716
4717 private void adaptSelf(Type t,
4718 ListBuffer<Type> from,
4719 ListBuffer<Type> to) {
4720 try {
4721 //if (t.tsym.type != t)
4722 adapt(t.tsym.type, t, from, to);
4723 } catch (AdaptFailure ex) {
4724 // Adapt should never fail calculating a mapping from
4725 // t.tsym.type to t as there can be no merge problem.
4726 throw new AssertionError(ex);
4727 }
4728 }
4729 // </editor-fold>
4730
4731 /**
4732 * Rewrite all type variables (universal quantifiers) in the given
4733 * type to wildcards (existential quantifiers). This is used to
4734 * determine if a cast is allowed. For example, if high is true
4735 * and {@code T <: Number}, then {@code List<T>} is rewritten to
4736 * {@code List<? extends Number>}. Since {@code List<Integer> <:
4737 * List<? extends Number>} a {@code List<T>} can be cast to {@code
4738 * List<Integer>} with a warning.
4739 * @param t a type
4740 * @param high if true return an upper bound; otherwise a lower
4741 * bound
4742 * @param rewriteTypeVars only rewrite captured wildcards if false;
4743 * otherwise rewrite all type variables
4744 * @return the type rewritten with wildcards (existential
4745 * quantifiers) only
4746 */
4747 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4748 return new Rewriter(high, rewriteTypeVars).visit(t);
4749 }
4750
4751 class Rewriter extends UnaryVisitor<Type> {
4752
4753 boolean high;
4754 boolean rewriteTypeVars;
4755 // map to avoid visiting same type argument twice, like in Foo<T>.Bar<T>
4756 Map<Type, Type> argMap = new HashMap<>();
4757 // cycle detection within an argument, see JDK-8324809
4758 Set<Type> seen = new HashSet<>();
4759
4760 Rewriter(boolean high, boolean rewriteTypeVars) {
4761 this.high = high;
4762 this.rewriteTypeVars = rewriteTypeVars;
4763 }
4764
4765 @Override
4766 public Type visitClassType(ClassType t, Void s) {
4767 ListBuffer<Type> rewritten = new ListBuffer<>();
4768 boolean changed = false;
4769 for (Type arg : t.allparams()) {
4770 Type bound = argMap.get(arg);
4771 if (bound == null) {
4772 argMap.put(arg, bound = visit(arg));
4773 }
4774 if (arg != bound) {
4775 changed = true;
4776 }
4777 rewritten.append(bound);
4778 }
4779 if (changed)
4780 return subst(t.tsym.type,
4781 t.tsym.type.allparams(),
4782 rewritten.toList());
4783 else
4784 return t;
4785 }
4786
4787 public Type visitType(Type t, Void s) {
4788 return t;
4789 }
4790
4791 @Override
4792 public Type visitCapturedType(CapturedType t, Void s) {
4793 Type w_bound = t.wildcard.type;
4794 Type bound = w_bound.contains(t) ?
4795 erasure(w_bound) :
4796 visit(w_bound);
4797 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4798 }
4799
4800 @Override
4801 public Type visitTypeVar(TypeVar t, Void s) {
4802 if (seen.add(t)) {
4803 if (rewriteTypeVars) {
4804 Type bound = t.getUpperBound().contains(t) ?
4805 erasure(t.getUpperBound()) :
4806 visit(t.getUpperBound());
4807 return rewriteAsWildcardType(bound, t, EXTENDS);
4808 } else {
4809 return t;
4810 }
4811 } else {
4812 return rewriteTypeVars ? makeExtendsWildcard(syms.objectType, t) : t;
4813 }
4814 }
4815
4816 @Override
4817 public Type visitWildcardType(WildcardType t, Void s) {
4818 Type bound2 = visit(t.type);
4819 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4820 }
4821
4822 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4823 switch (bk) {
4824 case EXTENDS: return high ?
4825 makeExtendsWildcard(B(bound), formal) :
4826 makeExtendsWildcard(syms.objectType, formal);
4827 case SUPER: return high ?
4828 makeSuperWildcard(syms.botType, formal) :
4829 makeSuperWildcard(B(bound), formal);
4830 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4831 default:
4832 Assert.error("Invalid bound kind " + bk);
4833 return null;
4834 }
4835 }
4836
4837 Type B(Type t) {
4838 while (t.hasTag(WILDCARD)) {
4839 WildcardType w = (WildcardType)t;
4840 t = high ?
4841 w.getExtendsBound() :
4842 w.getSuperBound();
4843 if (t == null) {
4844 t = high ? syms.objectType : syms.botType;
4845 }
4846 }
4847 return t;
4848 }
4849 }
4850
4851
4852 /**
4853 * Create a wildcard with the given upper (extends) bound; create
4854 * an unbounded wildcard if bound is Object.
4855 *
4856 * @param bound the upper bound
4857 * @param formal the formal type parameter that will be
4858 * substituted by the wildcard
4859 */
4860 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4861 if (bound == syms.objectType) {
4862 return new WildcardType(syms.objectType,
4863 BoundKind.UNBOUND,
4864 syms.boundClass,
4865 formal);
4866 } else {
4867 return new WildcardType(bound,
4868 BoundKind.EXTENDS,
4869 syms.boundClass,
4870 formal);
4871 }
4872 }
4873
4874 /**
4875 * Create a wildcard with the given lower (super) bound; create an
4876 * unbounded wildcard if bound is bottom (type of {@code null}).
4877 *
4878 * @param bound the lower bound
4879 * @param formal the formal type parameter that will be
4880 * substituted by the wildcard
4881 */
4882 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4883 if (bound.hasTag(BOT)) {
4884 return new WildcardType(syms.objectType,
4885 BoundKind.UNBOUND,
4886 syms.boundClass,
4887 formal);
4888 } else {
4889 return new WildcardType(bound,
4890 BoundKind.SUPER,
4891 syms.boundClass,
4892 formal);
4893 }
4894 }
4895
4896 /**
4897 * A wrapper for a type that allows use in sets.
4898 */
4899 public static class UniqueType {
4900 public final Type type;
4901 final Types types;
4902
4903 public UniqueType(Type type, Types types) {
4904 this.type = type;
4905 this.types = types;
4906 }
4907
4908 public int hashCode() {
4909 return types.hashCode(type);
4910 }
4911
4912 public boolean equals(Object obj) {
4913 return (obj instanceof UniqueType uniqueType) &&
4914 types.isSameType(type, uniqueType.type);
4915 }
4916
4917 public String toString() {
4918 return type.toString();
4919 }
4920
4921 }
4922 // </editor-fold>
4923
4924 // <editor-fold defaultstate="collapsed" desc="Visitors">
4925 /**
4926 * A default visitor for types. All visitor methods except
4927 * visitType are implemented by delegating to visitType. Concrete
4928 * subclasses must provide an implementation of visitType and can
4929 * override other methods as needed.
4930 *
4931 * @param <R> the return type of the operation implemented by this
4932 * visitor; use Void if no return type is needed.
4933 * @param <S> the type of the second argument (the first being the
4934 * type itself) of the operation implemented by this visitor; use
4935 * Void if a second argument is not needed.
4936 */
4937 public abstract static class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4938 public final R visit(Type t, S s) { return t.accept(this, s); }
4939 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
4940 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4941 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
4942 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
4943 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
4944 public R visitModuleType(ModuleType t, S s) { return visitType(t, s); }
4945 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
4946 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4947 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
4948 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
4949 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
4950 }
4951
4952 /**
4953 * A default visitor for symbols. All visitor methods except
4954 * visitSymbol are implemented by delegating to visitSymbol. Concrete
4955 * subclasses must provide an implementation of visitSymbol and can
4956 * override other methods as needed.
4957 *
4958 * @param <R> the return type of the operation implemented by this
4959 * visitor; use Void if no return type is needed.
4960 * @param <S> the type of the second argument (the first being the
4961 * symbol itself) of the operation implemented by this visitor; use
4962 * Void if a second argument is not needed.
4963 */
4964 public abstract static class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4965 public final R visit(Symbol s, S arg) { return s.accept(this, arg); }
4966 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
4967 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
4968 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
4969 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
4970 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
4971 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
4972 }
4973
4974 /**
4975 * A <em>simple</em> visitor for types. This visitor is simple as
4976 * captured wildcards, for-all types (generic methods), and
4977 * undetermined type variables (part of inference) are hidden.
4978 * Captured wildcards are hidden by treating them as type
4979 * variables and the rest are hidden by visiting their qtypes.
4980 *
4981 * @param <R> the return type of the operation implemented by this
4982 * visitor; use Void if no return type is needed.
4983 * @param <S> the type of the second argument (the first being the
4984 * type itself) of the operation implemented by this visitor; use
4985 * Void if a second argument is not needed.
4986 */
4987 public abstract static class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4988 @Override
4989 public R visitCapturedType(CapturedType t, S s) {
4990 return visitTypeVar(t, s);
4991 }
4992 @Override
4993 public R visitForAll(ForAll t, S s) {
4994 return visit(t.qtype, s);
4995 }
4996 @Override
4997 public R visitUndetVar(UndetVar t, S s) {
4998 return visit(t.qtype, s);
4999 }
5000 }
5001
5002 /**
5003 * A plain relation on types. That is a 2-ary function on the
5004 * form Type × Type → Boolean.
5005 * <!-- In plain text: Type x Type -> Boolean -->
5006 */
5007 public abstract static class TypeRelation extends SimpleVisitor<Boolean,Type> {}
5008
5009 /**
5010 * A convenience visitor for implementing operations that only
5011 * require one argument (the type itself), that is, unary
5012 * operations.
5013 *
5014 * @param <R> the return type of the operation implemented by this
5015 * visitor; use Void if no return type is needed.
5016 */
5017 public abstract static class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
5018 public final R visit(Type t) { return t.accept(this, null); }
5019 }
5020
5021 /**
5022 * A visitor for implementing a mapping from types to types. The
5023 * default behavior of this class is to implement the identity
5024 * mapping (mapping a type to itself). This can be overridden in
5025 * subclasses.
5026 *
5027 * @param <S> the type of the second argument (the first being the
5028 * type itself) of this mapping; use Void if a second argument is
5029 * not needed.
5030 */
5031 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
5032 public final Type visit(Type t) { return t.accept(this, null); }
5033 public Type visitType(Type t, S s) { return t; }
5034 }
5035
5036 /**
5037 * An abstract class for mappings from types to types (see {@link Type#map(TypeMapping)}.
5038 * This class implements the functional interface {@code Function}, that allows it to be used
5039 * fluently in stream-like processing.
5040 */
5041 public static class TypeMapping<S> extends MapVisitor<S> implements Function<Type, Type> {
5042 @Override
5043 public Type apply(Type type) { return visit(type); }
5044
5045 List<Type> visit(List<Type> ts, S s) {
5046 return ts.map(t -> visit(t, s));
5047 }
5048
5049 @Override
5050 public Type visitCapturedType(CapturedType t, S s) {
5051 return visitTypeVar(t, s);
5052 }
5053 }
5054 // </editor-fold>
5055
5056 // <editor-fold defaultstate="collapsed" desc="Unconditionality">
5057 /** Check unconditionality between any combination of reference or primitive types.
5058 *
5059 * Rules:
5060 * an identity conversion
5061 * a widening reference conversion
5062 * a widening primitive conversion (delegates to `checkUnconditionallyExactPrimitives`)
5063 * a boxing conversion
5064 * a boxing conversion followed by a widening reference conversion
5065 *
5066 * @param source Source primitive or reference type
5067 * @param target Target primitive or reference type
5068 */
5069 public boolean isUnconditionallyExact(Type source, Type target) {
5070 if (isSameType(source, target)) {
5071 return true;
5072 }
5073
5074 return target.isPrimitive()
5075 ? isUnconditionallyExactPrimitives(source, target)
5076 : isSubtype(boxedTypeOrType(erasure(source)), target);
5077 }
5078
5079 /** Check unconditionality between primitive types.
5080 *
5081 * - widening from one integral type to another,
5082 * - widening from one floating point type to another,
5083 * - widening from byte, short, or char to a floating point type,
5084 * - widening from int to double.
5085 *
5086 * @param selectorType Type of selector
5087 * @param targetType Target type
5088 */
5089 public boolean isUnconditionallyExactPrimitives(Type selectorType, Type targetType) {
5090 return isSameType(selectorType, targetType) ||
5091 (selectorType.isPrimitive() && targetType.isPrimitive()) &&
5092 ((selectorType.getTag().isStrictSubRangeOf(targetType.getTag())) &&
5093 !((selectorType.hasTag(BYTE) && targetType.hasTag(CHAR)) ||
5094 (selectorType.hasTag(INT) && targetType.hasTag(FLOAT)) ||
5095 (selectorType.hasTag(LONG) && (targetType.hasTag(DOUBLE) || targetType.hasTag(FLOAT)))));
5096 }
5097 // </editor-fold>
5098
5099 // <editor-fold defaultstate="collapsed" desc="Annotation support">
5100
5101 public RetentionPolicy getRetention(Attribute.Compound a) {
5102 return getRetention(a.type.tsym);
5103 }
5104
5105 public RetentionPolicy getRetention(TypeSymbol sym) {
5106 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
5107 Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
5108 if (c != null) {
5109 Attribute value = c.member(names.value);
5110 if (value != null && value instanceof Attribute.Enum attributeEnum) {
5111 Name levelName = attributeEnum.value.name;
5112 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
5113 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
5114 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
5115 else ;// /* fail soft */ throw new AssertionError(levelName);
5116 }
5117 }
5118 return vis;
5119 }
5120 // </editor-fold>
5121
5122 // <editor-fold defaultstate="collapsed" desc="Signature Generation">
5123
5124 public abstract class SignatureGenerator {
5125
5126 public class InvalidSignatureException extends CompilerInternalException {
5127 private static final long serialVersionUID = 0;
5128
5129 private final transient Type type;
5130
5131 InvalidSignatureException(Type type, boolean dumpStackTraceOnError) {
5132 super(dumpStackTraceOnError);
5133 this.type = type;
5134 }
5135
5136 public Type type() {
5137 return type;
5138 }
5139 }
5140
5141 protected abstract void append(char ch);
5142 protected abstract void append(byte[] ba);
5143 protected abstract void append(Name name);
5144 protected void classReference(ClassSymbol c) { /* by default: no-op */ }
5145
5146 protected void reportIllegalSignature(Type t) {
5147 throw new InvalidSignatureException(t, Types.this.dumpStacktraceOnError);
5148 }
5149
5150 /**
5151 * Assemble signature of given type in string buffer.
5152 */
5153 public void assembleSig(Type type) {
5154 switch (type.getTag()) {
5155 case BYTE:
5156 append('B');
5157 break;
5158 case SHORT:
5159 append('S');
5160 break;
5161 case CHAR:
5162 append('C');
5163 break;
5164 case INT:
5165 append('I');
5166 break;
5167 case LONG:
5168 append('J');
5169 break;
5170 case FLOAT:
5171 append('F');
5172 break;
5173 case DOUBLE:
5174 append('D');
5175 break;
5176 case BOOLEAN:
5177 append('Z');
5178 break;
5179 case VOID:
5180 append('V');
5181 break;
5182 case CLASS:
5183 if (type.isCompound()) {
5184 reportIllegalSignature(type);
5185 }
5186 append('L');
5187 assembleClassSig(type);
5188 append(';');
5189 break;
5190 case ARRAY:
5191 ArrayType at = (ArrayType) type;
5192 append('[');
5193 assembleSig(at.elemtype);
5194 break;
5195 case METHOD:
5196 MethodType mt = (MethodType) type;
5197 append('(');
5198 assembleSig(mt.argtypes);
5199 append(')');
5200 assembleSig(mt.restype);
5201 if (hasTypeVar(mt.thrown)) {
5202 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
5203 append('^');
5204 assembleSig(l.head);
5205 }
5206 }
5207 break;
5208 case WILDCARD: {
5209 Type.WildcardType ta = (Type.WildcardType) type;
5210 switch (ta.kind) {
5211 case SUPER:
5212 append('-');
5213 assembleSig(ta.type);
5214 break;
5215 case EXTENDS:
5216 append('+');
5217 assembleSig(ta.type);
5218 break;
5219 case UNBOUND:
5220 append('*');
5221 break;
5222 default:
5223 throw new AssertionError(ta.kind);
5224 }
5225 break;
5226 }
5227 case TYPEVAR:
5228 if (((TypeVar)type).isCaptured()) {
5229 reportIllegalSignature(type);
5230 }
5231 append('T');
5232 append(type.tsym.name);
5233 append(';');
5234 break;
5235 case FORALL:
5236 Type.ForAll ft = (Type.ForAll) type;
5237 assembleParamsSig(ft.tvars);
5238 assembleSig(ft.qtype);
5239 break;
5240 default:
5241 throw new AssertionError("typeSig " + type.getTag());
5242 }
5243 }
5244
5245 public boolean hasTypeVar(List<Type> l) {
5246 while (l.nonEmpty()) {
5247 if (l.head.hasTag(TypeTag.TYPEVAR)) {
5248 return true;
5249 }
5250 l = l.tail;
5251 }
5252 return false;
5253 }
5254
5255 public void assembleClassSig(Type type) {
5256 ClassType ct = (ClassType) type;
5257 ClassSymbol c = (ClassSymbol) ct.tsym;
5258 classReference(c);
5259 Type outer = ct.getEnclosingType();
5260 if (outer.allparams().nonEmpty()) {
5261 boolean rawOuter =
5262 c.owner.kind == MTH || // either a local class
5263 c.name == Types.this.names.empty; // or anonymous
5264 assembleClassSig(rawOuter
5265 ? Types.this.erasure(outer)
5266 : outer);
5267 append(rawOuter ? '$' : '.');
5268 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
5269 append(rawOuter
5270 ? c.flatname.subName(c.owner.enclClass().flatname.length() + 1)
5271 : c.name);
5272 } else {
5273 append(externalize(c.flatname));
5274 }
5275 if (ct.getTypeArguments().nonEmpty()) {
5276 append('<');
5277 assembleSig(ct.getTypeArguments());
5278 append('>');
5279 }
5280 }
5281
5282 public void assembleParamsSig(List<Type> typarams) {
5283 append('<');
5284 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
5285 Type.TypeVar tvar = (Type.TypeVar) ts.head;
5286 append(tvar.tsym.name);
5287 List<Type> bounds = Types.this.getBounds(tvar);
5288 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
5289 append(':');
5290 }
5291 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
5292 append(':');
5293 assembleSig(l.head);
5294 }
5295 }
5296 append('>');
5297 }
5298
5299 public void assembleSig(List<Type> types) {
5300 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
5301 assembleSig(ts.head);
5302 }
5303 }
5304 }
5305
5306 public Type constantType(LoadableConstant c) {
5307 switch (c.poolTag()) {
5308 case ClassFile.CONSTANT_Class:
5309 return syms.classType;
5310 case ClassFile.CONSTANT_String:
5311 return syms.stringType;
5312 case ClassFile.CONSTANT_Integer:
5313 return syms.intType;
5314 case ClassFile.CONSTANT_Float:
5315 return syms.floatType;
5316 case ClassFile.CONSTANT_Long:
5317 return syms.longType;
5318 case ClassFile.CONSTANT_Double:
5319 return syms.doubleType;
5320 case ClassFile.CONSTANT_MethodHandle:
5321 return syms.methodHandleType;
5322 case ClassFile.CONSTANT_MethodType:
5323 return syms.methodTypeType;
5324 case ClassFile.CONSTANT_Dynamic:
5325 return ((DynamicVarSymbol)c).type;
5326 default:
5327 throw new AssertionError("Not a loadable constant: " + c.poolTag());
5328 }
5329 }
5330 // </editor-fold>
5331
5332 public void newRound() {
5333 descCache._map.clear();
5334 isDerivedRawCache.clear();
5335 implCache._map.clear();
5336 membersCache._map.clear();
5337 closureCache.clear();
5338 }
5339 }
--- EOF ---