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