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