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