1 /* 2 * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.comp; 27 28 import com.sun.tools.javac.api.Formattable.LocalizedString; 29 import com.sun.tools.javac.code.*; 30 import com.sun.tools.javac.code.Scope.WriteableScope; 31 import com.sun.tools.javac.code.Source.Feature; 32 import com.sun.tools.javac.code.Symbol.*; 33 import com.sun.tools.javac.code.Type.*; 34 import com.sun.tools.javac.comp.Attr.ResultInfo; 35 import com.sun.tools.javac.comp.Check.CheckContext; 36 import com.sun.tools.javac.comp.DeferredAttr.AttrMode; 37 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext; 38 import com.sun.tools.javac.comp.DeferredAttr.DeferredType; 39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate; 40 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template; 41 import com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind; 42 import com.sun.tools.javac.jvm.*; 43 import com.sun.tools.javac.main.Option; 44 import com.sun.tools.javac.resources.CompilerProperties.Errors; 45 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 46 import com.sun.tools.javac.resources.CompilerProperties.Warnings; 47 import com.sun.tools.javac.tree.*; 48 import com.sun.tools.javac.tree.JCTree.*; 49 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind; 50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 51 import com.sun.tools.javac.util.*; 52 import com.sun.tools.javac.util.DefinedBy.Api; 53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType; 56 57 import java.util.Arrays; 58 import java.util.Collection; 59 import java.util.EnumSet; 60 import java.util.HashSet; 61 import java.util.Iterator; 62 import java.util.LinkedHashMap; 63 import java.util.Map; 64 import java.util.Set; 65 import java.util.function.BiFunction; 66 import java.util.function.BiPredicate; 67 import java.util.function.Function; 68 import java.util.function.Predicate; 69 import java.util.function.UnaryOperator; 70 import java.util.stream.Stream; 71 import java.util.stream.StreamSupport; 72 73 import javax.lang.model.element.ElementVisitor; 74 75 import static com.sun.tools.javac.code.Flags.*; 76 import static com.sun.tools.javac.code.Flags.BLOCK; 77 import static com.sun.tools.javac.code.Flags.STATIC; 78 import static com.sun.tools.javac.code.Kinds.*; 79 import static com.sun.tools.javac.code.Kinds.Kind.*; 80 import static com.sun.tools.javac.code.TypeTag.*; 81 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*; 82 import static com.sun.tools.javac.tree.JCTree.Tag.*; 83 import static com.sun.tools.javac.util.Iterators.createCompoundIterator; 84 85 /** Helper class for name resolution, used mostly by the attribution phase. 86 * 87 * <p><b>This is NOT part of any supported API. 88 * If you write code that depends on this, you do so at your own risk. 89 * This code and its internal interfaces are subject to change or 90 * deletion without notice.</b> 91 */ 92 public class Resolve { 93 protected static final Context.Key<Resolve> resolveKey = new Context.Key<>(); 94 95 Names names; 96 Log log; 97 Symtab syms; 98 Attr attr; 99 AttrRecover attrRecover; 100 DeferredAttr deferredAttr; 101 Check chk; 102 Infer infer; 103 ClassFinder finder; 104 ModuleFinder moduleFinder; 105 Types types; 106 JCDiagnostic.Factory diags; 107 public final boolean allowModules; 108 public final boolean allowRecords; 109 private final boolean compactMethodDiags; 110 private final boolean allowLocalVariableTypeInference; 111 private final boolean allowYieldStatement; 112 final EnumSet<VerboseResolutionMode> verboseResolutionMode; 113 final boolean dumpMethodReferenceSearchResults; 114 115 WriteableScope polymorphicSignatureScope; 116 117 @SuppressWarnings("this-escape") 118 protected Resolve(Context context) { 119 context.put(resolveKey, this); 120 syms = Symtab.instance(context); 121 122 varNotFound = new SymbolNotFoundError(ABSENT_VAR); 123 methodNotFound = new SymbolNotFoundError(ABSENT_MTH); 124 typeNotFound = new SymbolNotFoundError(ABSENT_TYP); 125 referenceNotFound = ReferenceLookupResult.error(methodNotFound); 126 127 names = Names.instance(context); 128 log = Log.instance(context); 129 attr = Attr.instance(context); 130 attrRecover = AttrRecover.instance(context); 131 deferredAttr = DeferredAttr.instance(context); 132 chk = Check.instance(context); 133 infer = Infer.instance(context); 134 finder = ClassFinder.instance(context); 135 moduleFinder = ModuleFinder.instance(context); 136 types = Types.instance(context); 137 diags = JCDiagnostic.Factory.instance(context); 138 Preview preview = Preview.instance(context); 139 Source source = Source.instance(context); 140 Options options = Options.instance(context); 141 compactMethodDiags = options.isSet(Option.XDIAGS, "compact") || 142 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics"); 143 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options); 144 Target target = Target.instance(context); 145 allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source); 146 allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source); 147 polymorphicSignatureScope = WriteableScope.create(syms.noSymbol); 148 allowModules = Feature.MODULES.allowedInSource(source); 149 allowRecords = Feature.RECORDS.allowedInSource(source); 150 dumpMethodReferenceSearchResults = options.isSet("debug.dumpMethodReferenceSearchResults"); 151 } 152 153 /** error symbols, which are returned when resolution fails 154 */ 155 private final SymbolNotFoundError varNotFound; 156 private final SymbolNotFoundError methodNotFound; 157 private final SymbolNotFoundError typeNotFound; 158 159 /** empty reference lookup result */ 160 private final ReferenceLookupResult referenceNotFound; 161 162 public static Resolve instance(Context context) { 163 Resolve instance = context.get(resolveKey); 164 if (instance == null) 165 instance = new Resolve(context); 166 return instance; 167 } 168 169 private static Symbol bestOf(Symbol s1, 170 Symbol s2) { 171 return s1.kind.betterThan(s2.kind) ? s1 : s2; 172 } 173 174 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support"> 175 enum VerboseResolutionMode { 176 SUCCESS("success"), 177 FAILURE("failure"), 178 APPLICABLE("applicable"), 179 INAPPLICABLE("inapplicable"), 180 DEFERRED_INST("deferred-inference"), 181 PREDEF("predef"), 182 OBJECT_INIT("object-init"), 183 INTERNAL("internal"); 184 185 final String opt; 186 187 private VerboseResolutionMode(String opt) { 188 this.opt = opt; 189 } 190 191 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) { 192 String s = opts.get("debug.verboseResolution"); 193 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class); 194 if (s == null) return res; 195 if (s.contains("all")) { 196 res = EnumSet.allOf(VerboseResolutionMode.class); 197 } 198 Collection<String> args = Arrays.asList(s.split(",")); 199 for (VerboseResolutionMode mode : values()) { 200 if (args.contains(mode.opt)) { 201 res.add(mode); 202 } else if (args.contains("-" + mode.opt)) { 203 res.remove(mode); 204 } 205 } 206 return res; 207 } 208 } 209 210 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site, 211 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) { 212 boolean success = !bestSoFar.kind.isResolutionError(); 213 214 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) { 215 return; 216 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) { 217 return; 218 } 219 220 if (bestSoFar.name == names.init && 221 bestSoFar.owner == syms.objectType.tsym && 222 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) { 223 return; //skip diags for Object constructor resolution 224 } else if (site == syms.predefClass.type && 225 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) { 226 return; //skip spurious diags for predef symbols (i.e. operators) 227 } else if (currentResolutionContext.internalResolution && 228 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) { 229 return; 230 } 231 232 int pos = 0; 233 int mostSpecificPos = -1; 234 ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>(); 235 for (Candidate c : currentResolutionContext.candidates) { 236 if (currentResolutionContext.step != c.step || 237 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) || 238 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) { 239 continue; 240 } else { 241 subDiags.append(c.isApplicable() ? 242 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) : 243 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details)); 244 if (c.sym == bestSoFar) 245 mostSpecificPos = pos; 246 pos++; 247 } 248 } 249 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1"; 250 List<Type> argtypes2 = argtypes.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step)); 251 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name, 252 site.tsym, mostSpecificPos, currentResolutionContext.step, 253 methodArguments(argtypes2), 254 methodArguments(typeargtypes)); 255 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList()); 256 log.report(d); 257 } 258 259 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) { 260 JCDiagnostic subDiag = null; 261 if (sym.type.hasTag(FORALL)) { 262 subDiag = diags.fragment(Fragments.PartialInstSig(inst)); 263 } 264 265 String key = subDiag == null ? 266 "applicable.method.found" : 267 "applicable.method.found.1"; 268 269 return diags.fragment(key, pos, sym, subDiag); 270 } 271 272 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) { 273 return diags.fragment(Fragments.NotApplicableMethodFound(pos, sym, subDiag)); 274 } 275 // </editor-fold> 276 277 /* ************************************************************************ 278 * Identifier resolution 279 *************************************************************************/ 280 281 /** An environment is "static" if its static level is greater than 282 * the one of its outer environment 283 */ 284 protected static boolean isStatic(Env<AttrContext> env) { 285 return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel; 286 } 287 288 /** An environment is an "initializer" if it is a constructor or 289 * an instance initializer. 290 */ 291 static boolean isInitializer(Env<AttrContext> env) { 292 Symbol owner = env.info.scope.owner; 293 return owner.isConstructor() || 294 owner.owner.kind == TYP && 295 (owner.kind == VAR || 296 owner.kind == MTH && (owner.flags() & BLOCK) != 0) && 297 (owner.flags() & STATIC) == 0; 298 } 299 300 /** Is class accessible in given environment? 301 * @param env The current environment. 302 * @param c The class whose accessibility is checked. 303 */ 304 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) { 305 return isAccessible(env, c, false); 306 } 307 308 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) { 309 310 /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor 311 to refer to an inaccessible type 312 */ 313 if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0) 314 return true; 315 316 if (env.info.visitingServiceImplementation && 317 env.toplevel.modle == c.packge().modle) { 318 return true; 319 } 320 321 boolean isAccessible = false; 322 switch ((short)(c.flags() & AccessFlags)) { 323 case PRIVATE: 324 isAccessible = 325 env.enclClass.sym.outermostClass() == 326 c.owner.outermostClass(); 327 break; 328 case 0: 329 isAccessible = 330 env.toplevel.packge == c.owner // fast special case 331 || 332 env.toplevel.packge == c.packge(); 333 break; 334 default: // error recovery 335 isAccessible = true; 336 break; 337 case PUBLIC: 338 if (allowModules) { 339 ModuleSymbol currModule = env.toplevel.modle; 340 currModule.complete(); 341 PackageSymbol p = c.packge(); 342 isAccessible = 343 currModule == p.modle || 344 currModule.visiblePackages.get(p.fullname) == p || 345 p == syms.rootPackage || 346 (p.modle == syms.unnamedModule && currModule.readModules.contains(p.modle)); 347 } else { 348 isAccessible = true; 349 } 350 break; 351 case PROTECTED: 352 isAccessible = 353 env.toplevel.packge == c.owner // fast special case 354 || 355 env.toplevel.packge == c.packge() 356 || 357 isInnerSubClass(env.enclClass.sym, c.owner) 358 || 359 env.info.allowProtectedAccess; 360 break; 361 } 362 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ? 363 isAccessible : 364 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner); 365 } 366 //where 367 /** Is given class a subclass of given base class, or an inner class 368 * of a subclass? 369 * Return null if no such class exists. 370 * @param c The class which is the subclass or is contained in it. 371 * @param base The base class 372 */ 373 private boolean isInnerSubClass(ClassSymbol c, Symbol base) { 374 while (c != null && !c.isSubClass(base, types)) { 375 c = c.owner.enclClass(); 376 } 377 return c != null; 378 } 379 380 boolean isAccessible(Env<AttrContext> env, Type t) { 381 return isAccessible(env, t, false); 382 } 383 384 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) { 385 if (t.hasTag(ARRAY)) { 386 return isAccessible(env, types.cvarUpperBound(types.elemtype(t))); 387 } else if (t.isUnion()) { 388 return StreamSupport.stream(((UnionClassType) t).getAlternativeTypes().spliterator(), false) 389 .allMatch(alternative -> isAccessible(env, alternative.tsym, checkInner)); 390 } else { 391 return isAccessible(env, t.tsym, checkInner); 392 } 393 } 394 395 /** Is symbol accessible as a member of given type in given environment? 396 * @param env The current environment. 397 * @param site The type of which the tested symbol is regarded 398 * as a member. 399 * @param sym The symbol. 400 */ 401 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) { 402 return isAccessible(env, site, sym, false); 403 } 404 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) { 405 if (sym.name == names.init && sym.owner != site.tsym) return false; 406 407 /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor 408 to refer to an inaccessible type 409 */ 410 if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0) 411 return true; 412 413 if (env.info.visitingServiceImplementation && 414 env.toplevel.modle == sym.packge().modle) { 415 return true; 416 } 417 418 switch ((short)(sym.flags() & AccessFlags)) { 419 case PRIVATE: 420 return 421 (env.enclClass.sym == sym.owner // fast special case 422 || 423 env.enclClass.sym.outermostClass() == 424 sym.owner.outermostClass()) 425 && 426 sym.isInheritedIn(site.tsym, types); 427 case 0: 428 return 429 (env.toplevel.packge == sym.owner.owner // fast special case 430 || 431 env.toplevel.packge == sym.packge()) 432 && 433 isAccessible(env, site, checkInner) 434 && 435 sym.isInheritedIn(site.tsym, types) 436 && 437 notOverriddenIn(site, sym); 438 case PROTECTED: 439 return 440 (env.toplevel.packge == sym.owner.owner // fast special case 441 || 442 env.toplevel.packge == sym.packge() 443 || 444 isProtectedAccessible(sym, env.enclClass.sym, site) 445 || 446 // OK to select instance method or field from 'super' or type name 447 // (but type names should be disallowed elsewhere!) 448 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP) 449 && 450 isAccessible(env, site, checkInner) 451 && 452 notOverriddenIn(site, sym); 453 default: // this case includes erroneous combinations as well 454 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym); 455 } 456 } 457 //where 458 /* `sym' is accessible only if not overridden by 459 * another symbol which is a member of `site' 460 * (because, if it is overridden, `sym' is not strictly 461 * speaking a member of `site'). A polymorphic signature method 462 * cannot be overridden (e.g. MH.invokeExact(Object[])). 463 */ 464 private boolean notOverriddenIn(Type site, Symbol sym) { 465 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic()) 466 return true; 467 else { 468 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true); 469 return (s2 == null || s2 == sym || sym.owner == s2.owner || (sym.owner.isInterface() && s2.owner == syms.objectType.tsym) || 470 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym))); 471 } 472 } 473 //where 474 /** Is given protected symbol accessible if it is selected from given site 475 * and the selection takes place in given class? 476 * @param sym The symbol with protected access 477 * @param c The class where the access takes place 478 * @param site The type of the qualifier 479 */ 480 private 481 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) { 482 Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site; 483 while (c != null && 484 !(c.isSubClass(sym.owner, types) && 485 (c.flags() & INTERFACE) == 0 && 486 // In JLS 2e 6.6.2.1, the subclass restriction applies 487 // only to instance fields and methods -- types are excluded 488 // regardless of whether they are declared 'static' or not. 489 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types)))) 490 c = c.owner.enclClass(); 491 return c != null; 492 } 493 494 /** 495 * Performs a recursive scan of a type looking for accessibility problems 496 * from current attribution environment 497 */ 498 void checkAccessibleType(Env<AttrContext> env, Type t) { 499 accessibilityChecker.visit(t, env); 500 } 501 502 /** 503 * Accessibility type-visitor 504 */ 505 Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker = 506 new Types.SimpleVisitor<Void, Env<AttrContext>>() { 507 508 void visit(List<Type> ts, Env<AttrContext> env) { 509 for (Type t : ts) { 510 visit(t, env); 511 } 512 } 513 514 public Void visitType(Type t, Env<AttrContext> env) { 515 return null; 516 } 517 518 @Override 519 public Void visitArrayType(ArrayType t, Env<AttrContext> env) { 520 visit(t.elemtype, env); 521 return null; 522 } 523 524 @Override 525 public Void visitClassType(ClassType t, Env<AttrContext> env) { 526 visit(t.getTypeArguments(), env); 527 if (!isAccessible(env, t, true)) { 528 accessBase(new AccessError(env, null, t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true); 529 } 530 return null; 531 } 532 533 @Override 534 public Void visitWildcardType(WildcardType t, Env<AttrContext> env) { 535 visit(t.type, env); 536 return null; 537 } 538 539 @Override 540 public Void visitMethodType(MethodType t, Env<AttrContext> env) { 541 visit(t.getParameterTypes(), env); 542 visit(t.getReturnType(), env); 543 visit(t.getThrownTypes(), env); 544 return null; 545 } 546 }; 547 548 /** Try to instantiate the type of a method so that it fits 549 * given type arguments and argument types. If successful, return 550 * the method's instantiated type, else return null. 551 * The instantiation will take into account an additional leading 552 * formal parameter if the method is an instance method seen as a member 553 * of an under determined site. In this case, we treat site as an additional 554 * parameter and the parameters of the class containing the method as 555 * additional type variables that get instantiated. 556 * 557 * @param env The current environment 558 * @param site The type of which the method is a member. 559 * @param m The method symbol. 560 * @param argtypes The invocation's given value arguments. 561 * @param typeargtypes The invocation's given type arguments. 562 * @param allowBoxing Allow boxing conversions of arguments. 563 * @param useVarargs Box trailing arguments into an array for varargs. 564 */ 565 Type rawInstantiate(Env<AttrContext> env, 566 Type site, 567 Symbol m, 568 ResultInfo resultInfo, 569 List<Type> argtypes, 570 List<Type> typeargtypes, 571 boolean allowBoxing, 572 boolean useVarargs, 573 Warner warn) throws Infer.InferenceException { 574 Type mt = types.memberType(site, m); 575 // tvars is the list of formal type variables for which type arguments 576 // need to inferred. 577 List<Type> tvars = List.nil(); 578 if (typeargtypes == null) typeargtypes = List.nil(); 579 if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) { 580 // This is not a polymorphic method, but typeargs are supplied 581 // which is fine, see JLS 15.12.2.1 582 } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) { 583 ForAll pmt = (ForAll) mt; 584 if (typeargtypes.length() != pmt.tvars.length()) 585 // not enough args 586 throw new InapplicableMethodException(diags.fragment(Fragments.WrongNumberTypeArgs(Integer.toString(pmt.tvars.length())))); 587 // Check type arguments are within bounds 588 List<Type> formals = pmt.tvars; 589 List<Type> actuals = typeargtypes; 590 while (formals.nonEmpty() && actuals.nonEmpty()) { 591 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head), 592 pmt.tvars, typeargtypes); 593 for (; bounds.nonEmpty(); bounds = bounds.tail) { 594 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn)) { 595 throw new InapplicableMethodException(diags.fragment(Fragments.ExplicitParamDoNotConformToBounds(actuals.head, bounds))); 596 } 597 } 598 formals = formals.tail; 599 actuals = actuals.tail; 600 } 601 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes); 602 } else if (mt.hasTag(FORALL)) { 603 ForAll pmt = (ForAll) mt; 604 List<Type> tvars1 = types.newInstances(pmt.tvars); 605 tvars = tvars.appendList(tvars1); 606 mt = types.subst(pmt.qtype, pmt.tvars, tvars1); 607 } 608 609 // find out whether we need to go the slow route via infer 610 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/ 611 for (List<Type> l = argtypes; 612 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded; 613 l = l.tail) { 614 if (l.head.hasTag(FORALL)) instNeeded = true; 615 } 616 617 if (instNeeded) { 618 return infer.instantiateMethod(env, 619 tvars, 620 (MethodType)mt, 621 resultInfo, 622 (MethodSymbol)m, 623 argtypes, 624 allowBoxing, 625 useVarargs, 626 currentResolutionContext, 627 warn); 628 } 629 630 DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn); 631 currentResolutionContext.methodCheck.argumentsAcceptable(env, dc, 632 argtypes, mt.getParameterTypes(), warn); 633 dc.complete(); 634 return mt; 635 } 636 637 Type checkMethod(Env<AttrContext> env, 638 Type site, 639 Symbol m, 640 ResultInfo resultInfo, 641 List<Type> argtypes, 642 List<Type> typeargtypes, 643 Warner warn) { 644 MethodResolutionContext prevContext = currentResolutionContext; 645 try { 646 currentResolutionContext = new MethodResolutionContext(); 647 currentResolutionContext.attrMode = (resultInfo.pt == Infer.anyPoly) ? 648 AttrMode.SPECULATIVE : DeferredAttr.AttrMode.CHECK; 649 if (env.tree.hasTag(JCTree.Tag.REFERENCE)) { 650 //method/constructor references need special check class 651 //to handle inference variables in 'argtypes' (might happen 652 //during an unsticking round) 653 currentResolutionContext.methodCheck = 654 new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); 655 } 656 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase; 657 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes, 658 step.isBoxingRequired(), step.isVarargsRequired(), warn); 659 } 660 finally { 661 currentResolutionContext = prevContext; 662 } 663 } 664 665 /** Same but returns null instead throwing a NoInstanceException 666 */ 667 Type instantiate(Env<AttrContext> env, 668 Type site, 669 Symbol m, 670 ResultInfo resultInfo, 671 List<Type> argtypes, 672 List<Type> typeargtypes, 673 boolean allowBoxing, 674 boolean useVarargs, 675 Warner warn) { 676 try { 677 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes, 678 allowBoxing, useVarargs, warn); 679 } catch (InapplicableMethodException ex) { 680 return null; 681 } 682 } 683 684 /** 685 * This interface defines an entry point that should be used to perform a 686 * method check. A method check usually consist in determining as to whether 687 * a set of types (actuals) is compatible with another set of types (formals). 688 * Since the notion of compatibility can vary depending on the circumstances, 689 * this interfaces allows to easily add new pluggable method check routines. 690 */ 691 interface MethodCheck { 692 /** 693 * Main method check routine. A method check usually consist in determining 694 * as to whether a set of types (actuals) is compatible with another set of 695 * types (formals). If an incompatibility is found, an unchecked exception 696 * is assumed to be thrown. 697 */ 698 void argumentsAcceptable(Env<AttrContext> env, 699 DeferredAttrContext deferredAttrContext, 700 List<Type> argtypes, 701 List<Type> formals, 702 Warner warn); 703 704 /** 705 * Retrieve the method check object that will be used during a 706 * most specific check. 707 */ 708 MethodCheck mostSpecificCheck(List<Type> actuals); 709 } 710 711 /** 712 * Helper enum defining all method check diagnostics (used by resolveMethodCheck). 713 */ 714 enum MethodCheckDiag { 715 /** 716 * Actuals and formals differs in length. 717 */ 718 ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"), 719 /** 720 * An actual is incompatible with a formal. 721 */ 722 ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"), 723 /** 724 * An actual is incompatible with the varargs element type. 725 */ 726 VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"), 727 /** 728 * The varargs element type is inaccessible. 729 */ 730 INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type"); 731 732 final String basicKey; 733 final String inferKey; 734 735 MethodCheckDiag(String basicKey, String inferKey) { 736 this.basicKey = basicKey; 737 this.inferKey = inferKey; 738 } 739 740 String regex() { 741 return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey); 742 } 743 } 744 745 /** 746 * Dummy method check object. All methods are deemed applicable, regardless 747 * of their formal parameter types. 748 */ 749 MethodCheck nilMethodCheck = new MethodCheck() { 750 public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) { 751 //do nothing - method always applicable regardless of actuals 752 } 753 754 public MethodCheck mostSpecificCheck(List<Type> actuals) { 755 return this; 756 } 757 }; 758 759 /** 760 * Base class for 'real' method checks. The class defines the logic for 761 * iterating through formals and actuals and provides and entry point 762 * that can be used by subclasses in order to define the actual check logic. 763 */ 764 abstract class AbstractMethodCheck implements MethodCheck { 765 @Override 766 public void argumentsAcceptable(final Env<AttrContext> env, 767 DeferredAttrContext deferredAttrContext, 768 List<Type> argtypes, 769 List<Type> formals, 770 Warner warn) { 771 //should we expand formals? 772 boolean useVarargs = deferredAttrContext.phase.isVarargsRequired(); 773 JCTree callTree = treeForDiagnostics(env); 774 List<JCExpression> trees = TreeInfo.args(callTree); 775 776 //inference context used during this method check 777 InferenceContext inferenceContext = deferredAttrContext.inferenceContext; 778 779 Type varargsFormal = useVarargs ? formals.last() : null; 780 781 if (varargsFormal == null && 782 argtypes.size() != formals.size()) { 783 reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args 784 } 785 786 while (argtypes.nonEmpty() && formals.head != varargsFormal) { 787 DiagnosticPosition pos = trees != null ? trees.head : null; 788 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn); 789 argtypes = argtypes.tail; 790 formals = formals.tail; 791 trees = trees != null ? trees.tail : trees; 792 } 793 794 if (formals.head != varargsFormal) { 795 reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args 796 } 797 798 if (useVarargs) { 799 //note: if applicability check is triggered by most specific test, 800 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5) 801 final Type elt = types.elemtype(varargsFormal); 802 while (argtypes.nonEmpty()) { 803 DiagnosticPosition pos = trees != null ? trees.head : null; 804 checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn); 805 argtypes = argtypes.tail; 806 trees = trees != null ? trees.tail : trees; 807 } 808 } 809 } 810 811 // where 812 private JCTree treeForDiagnostics(Env<AttrContext> env) { 813 return env.info.preferredTreeForDiagnostics != null ? env.info.preferredTreeForDiagnostics : env.tree; 814 } 815 816 /** 817 * Does the actual argument conforms to the corresponding formal? 818 */ 819 abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn); 820 821 protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) { 822 boolean inferDiag = inferenceContext != infer.emptyContext; 823 if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) { 824 Object[] args2 = new Object[args.length + 1]; 825 System.arraycopy(args, 0, args2, 1, args.length); 826 args2[0] = inferenceContext.inferenceVars(); 827 args = args2; 828 } 829 String key = inferDiag ? diag.inferKey : diag.basicKey; 830 throw inferDiag ? 831 infer.error(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args)) : 832 methodCheckFailure.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args)); 833 } 834 835 /** 836 * To eliminate the overhead associated with allocating an exception object in such an 837 * hot execution path, we use flyweight pattern - and share the same exception instance 838 * across multiple method check failures. 839 */ 840 class SharedInapplicableMethodException extends InapplicableMethodException { 841 private static final long serialVersionUID = 0; 842 843 SharedInapplicableMethodException() { 844 super(null); 845 } 846 847 SharedInapplicableMethodException setMessage(JCDiagnostic details) { 848 this.diagnostic = details; 849 return this; 850 } 851 } 852 853 SharedInapplicableMethodException methodCheckFailure = new SharedInapplicableMethodException(); 854 855 public MethodCheck mostSpecificCheck(List<Type> actuals) { 856 return nilMethodCheck; 857 } 858 859 } 860 861 /** 862 * Arity-based method check. A method is applicable if the number of actuals 863 * supplied conforms to the method signature. 864 */ 865 MethodCheck arityMethodCheck = new AbstractMethodCheck() { 866 @Override 867 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) { 868 //do nothing - actual always compatible to formals 869 } 870 871 @Override 872 public String toString() { 873 return "arityMethodCheck"; 874 } 875 }; 876 877 /** 878 * Main method applicability routine. Given a list of actual types A, 879 * a list of formal types F, determines whether the types in A are 880 * compatible (by method invocation conversion) with the types in F. 881 * 882 * Since this routine is shared between overload resolution and method 883 * type-inference, a (possibly empty) inference context is used to convert 884 * formal types to the corresponding 'undet' form ahead of a compatibility 885 * check so that constraints can be propagated and collected. 886 * 887 * Moreover, if one or more types in A is a deferred type, this routine uses 888 * DeferredAttr in order to perform deferred attribution. If one or more actual 889 * deferred types are stuck, they are placed in a queue and revisited later 890 * after the remainder of the arguments have been seen. If this is not sufficient 891 * to 'unstuck' the argument, a cyclic inference error is called out. 892 * 893 * A method check handler (see above) is used in order to report errors. 894 */ 895 MethodCheck resolveMethodCheck = new AbstractMethodCheck() { 896 897 @Override 898 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) { 899 ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn); 900 mresult.check(pos, actual); 901 } 902 903 @Override 904 public void argumentsAcceptable(final Env<AttrContext> env, 905 DeferredAttrContext deferredAttrContext, 906 List<Type> argtypes, 907 List<Type> formals, 908 Warner warn) { 909 super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn); 910 // should we check varargs element type accessibility? 911 if (deferredAttrContext.phase.isVarargsRequired()) { 912 if (deferredAttrContext.mode == AttrMode.CHECK) { 913 varargsAccessible(env, types.elemtype(formals.last()), deferredAttrContext.inferenceContext); 914 } 915 } 916 } 917 918 /** 919 * Test that the runtime array element type corresponding to 't' is accessible. 't' should be the 920 * varargs element type of either the method invocation type signature (after inference completes) 921 * or the method declaration signature (before inference completes). 922 */ 923 private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) { 924 if (inferenceContext.free(t)) { 925 inferenceContext.addFreeTypeListener(List.of(t), 926 solvedContext -> varargsAccessible(env, solvedContext.asInstType(t), solvedContext)); 927 } else { 928 if (!isAccessible(env, types.erasure(t))) { 929 Symbol location = env.enclClass.sym; 930 reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location); 931 } 932 } 933 } 934 935 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to, 936 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) { 937 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) { 938 MethodCheckDiag methodDiag = varargsCheck ? 939 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH; 940 941 @Override 942 public void report(DiagnosticPosition pos, JCDiagnostic details) { 943 reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details); 944 } 945 }; 946 return new MethodResultInfo(to, checkContext); 947 } 948 949 @Override 950 public MethodCheck mostSpecificCheck(List<Type> actuals) { 951 return new MostSpecificCheck(actuals); 952 } 953 954 @Override 955 public String toString() { 956 return "resolveMethodCheck"; 957 } 958 }; 959 960 /** 961 * This class handles method reference applicability checks; since during 962 * these checks it's sometime possible to have inference variables on 963 * the actual argument types list, the method applicability check must be 964 * extended so that inference variables are 'opened' as needed. 965 */ 966 class MethodReferenceCheck extends AbstractMethodCheck { 967 968 InferenceContext pendingInferenceContext; 969 970 MethodReferenceCheck(InferenceContext pendingInferenceContext) { 971 this.pendingInferenceContext = pendingInferenceContext; 972 } 973 974 @Override 975 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) { 976 ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn); 977 mresult.check(pos, actual); 978 } 979 980 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to, 981 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) { 982 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) { 983 MethodCheckDiag methodDiag = varargsCheck ? 984 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH; 985 986 @Override 987 public boolean compatible(Type found, Type req, Warner warn) { 988 found = pendingInferenceContext.asUndetVar(found); 989 if (found.hasTag(UNDETVAR) && req.isPrimitive()) { 990 req = types.boxedClass(req).type; 991 } 992 return super.compatible(found, req, warn); 993 } 994 995 @Override 996 public void report(DiagnosticPosition pos, JCDiagnostic details) { 997 reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details); 998 } 999 }; 1000 return new MethodResultInfo(to, checkContext); 1001 } 1002 1003 @Override 1004 public MethodCheck mostSpecificCheck(List<Type> actuals) { 1005 return new MostSpecificCheck(actuals); 1006 } 1007 1008 @Override 1009 public String toString() { 1010 return "MethodReferenceCheck"; 1011 } 1012 } 1013 1014 /** 1015 * Check context to be used during method applicability checks. A method check 1016 * context might contain inference variables. 1017 */ 1018 abstract class MethodCheckContext implements CheckContext { 1019 1020 boolean strict; 1021 DeferredAttrContext deferredAttrContext; 1022 Warner rsWarner; 1023 1024 public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) { 1025 this.strict = strict; 1026 this.deferredAttrContext = deferredAttrContext; 1027 this.rsWarner = rsWarner; 1028 } 1029 1030 public boolean compatible(Type found, Type req, Warner warn) { 1031 InferenceContext inferenceContext = deferredAttrContext.inferenceContext; 1032 return strict ? 1033 types.isSubtypeUnchecked(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn) : 1034 types.isConvertible(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn); 1035 } 1036 1037 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1038 throw new InapplicableMethodException(details); 1039 } 1040 1041 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) { 1042 return rsWarner; 1043 } 1044 1045 public InferenceContext inferenceContext() { 1046 return deferredAttrContext.inferenceContext; 1047 } 1048 1049 public DeferredAttrContext deferredAttrContext() { 1050 return deferredAttrContext; 1051 } 1052 1053 @Override 1054 public String toString() { 1055 return "MethodCheckContext"; 1056 } 1057 } 1058 1059 /** 1060 * ResultInfo class to be used during method applicability checks. Check 1061 * for deferred types goes through special path. 1062 */ 1063 class MethodResultInfo extends ResultInfo { 1064 1065 public MethodResultInfo(Type pt, CheckContext checkContext) { 1066 attr.super(KindSelector.VAL, pt, checkContext); 1067 } 1068 1069 @Override 1070 protected Type check(DiagnosticPosition pos, Type found) { 1071 if (found.hasTag(DEFERRED)) { 1072 DeferredType dt = (DeferredType)found; 1073 return dt.check(this); 1074 } else { 1075 Type uResult = U(found); 1076 Type capturedType = pos == null || pos.getTree() == null ? 1077 types.capture(uResult) : 1078 checkContext.inferenceContext() 1079 .cachedCapture(pos.getTree(), uResult, true); 1080 return super.check(pos, chk.checkNonVoid(pos, capturedType)); 1081 } 1082 } 1083 1084 /** 1085 * javac has a long-standing 'simplification' (see 6391995): 1086 * given an actual argument type, the method check is performed 1087 * on its upper bound. This leads to inconsistencies when an 1088 * argument type is checked against itself. For example, given 1089 * a type-variable T, it is not true that {@code U(T) <: T}, 1090 * so we need to guard against that. 1091 */ 1092 private Type U(Type found) { 1093 return found == pt ? 1094 found : types.cvarUpperBound(found); 1095 } 1096 1097 @Override 1098 protected MethodResultInfo dup(Type newPt) { 1099 return new MethodResultInfo(newPt, checkContext); 1100 } 1101 1102 @Override 1103 protected ResultInfo dup(CheckContext newContext) { 1104 return new MethodResultInfo(pt, newContext); 1105 } 1106 1107 @Override 1108 protected ResultInfo dup(Type newPt, CheckContext newContext) { 1109 return new MethodResultInfo(newPt, newContext); 1110 } 1111 } 1112 1113 /** 1114 * Most specific method applicability routine. Given a list of actual types A, 1115 * a list of formal types F1, and a list of formal types F2, the routine determines 1116 * as to whether the types in F1 can be considered more specific than those in F2 w.r.t. 1117 * argument types A. 1118 */ 1119 class MostSpecificCheck implements MethodCheck { 1120 1121 List<Type> actuals; 1122 1123 MostSpecificCheck(List<Type> actuals) { 1124 this.actuals = actuals; 1125 } 1126 1127 @Override 1128 public void argumentsAcceptable(final Env<AttrContext> env, 1129 DeferredAttrContext deferredAttrContext, 1130 List<Type> formals1, 1131 List<Type> formals2, 1132 Warner warn) { 1133 formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired()); 1134 while (formals2.nonEmpty()) { 1135 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head); 1136 mresult.check(null, formals1.head); 1137 formals1 = formals1.tail; 1138 formals2 = formals2.tail; 1139 actuals = actuals.isEmpty() ? actuals : actuals.tail; 1140 } 1141 } 1142 1143 /** 1144 * Create a method check context to be used during the most specific applicability check 1145 */ 1146 ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext, 1147 Warner rsWarner, Type actual) { 1148 return attr.new ResultInfo(KindSelector.VAL, to, 1149 new MostSpecificCheckContext(deferredAttrContext, rsWarner, actual)); 1150 } 1151 1152 /** 1153 * Subclass of method check context class that implements most specific 1154 * method conversion. If the actual type under analysis is a deferred type 1155 * a full blown structural analysis is carried out. 1156 */ 1157 class MostSpecificCheckContext extends MethodCheckContext { 1158 1159 Type actual; 1160 1161 public MostSpecificCheckContext(DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) { 1162 super(true, deferredAttrContext, rsWarner); 1163 this.actual = actual; 1164 } 1165 1166 public boolean compatible(Type found, Type req, Warner warn) { 1167 if (unrelatedFunctionalInterfaces(found, req) && 1168 (actual != null && actual.getTag() == DEFERRED)) { 1169 DeferredType dt = (DeferredType) actual; 1170 JCTree speculativeTree = dt.speculativeTree(deferredAttrContext); 1171 if (speculativeTree != deferredAttr.stuckTree) { 1172 return functionalInterfaceMostSpecific(found, req, speculativeTree); 1173 } 1174 } 1175 return compatibleBySubtyping(found, req); 1176 } 1177 1178 private boolean compatibleBySubtyping(Type found, Type req) { 1179 if (!strict && found.isPrimitive() != req.isPrimitive()) { 1180 found = found.isPrimitive() ? types.boxedClass(found).type : types.unboxedType(found); 1181 } 1182 return types.isSubtypeNoCapture(found, deferredAttrContext.inferenceContext.asUndetVar(req)); 1183 } 1184 1185 /** Whether {@code t} and {@code s} are unrelated functional interface types. */ 1186 private boolean unrelatedFunctionalInterfaces(Type t, Type s) { 1187 return types.isFunctionalInterface(t.tsym) && 1188 types.isFunctionalInterface(s.tsym) && 1189 unrelatedInterfaces(t, s); 1190 } 1191 1192 /** Whether {@code t} and {@code s} are unrelated interface types; recurs on intersections. **/ 1193 private boolean unrelatedInterfaces(Type t, Type s) { 1194 if (t.isCompound()) { 1195 for (Type ti : types.interfaces(t)) { 1196 if (!unrelatedInterfaces(ti, s)) { 1197 return false; 1198 } 1199 } 1200 return true; 1201 } else if (s.isCompound()) { 1202 for (Type si : types.interfaces(s)) { 1203 if (!unrelatedInterfaces(t, si)) { 1204 return false; 1205 } 1206 } 1207 return true; 1208 } else { 1209 return types.asSuper(t, s.tsym) == null && types.asSuper(s, t.tsym) == null; 1210 } 1211 } 1212 1213 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */ 1214 private boolean functionalInterfaceMostSpecific(Type t, Type s, JCTree tree) { 1215 Type tDesc = types.findDescriptorType(types.capture(t)); 1216 Type tDescNoCapture = types.findDescriptorType(t); 1217 Type sDesc = types.findDescriptorType(s); 1218 final List<Type> tTypeParams = tDesc.getTypeArguments(); 1219 final List<Type> tTypeParamsNoCapture = tDescNoCapture.getTypeArguments(); 1220 final List<Type> sTypeParams = sDesc.getTypeArguments(); 1221 1222 // compare type parameters 1223 if (tDesc.hasTag(FORALL) && !types.hasSameBounds((ForAll) tDesc, (ForAll) tDescNoCapture)) { 1224 return false; 1225 } 1226 // can't use Types.hasSameBounds on sDesc because bounds may have ivars 1227 List<Type> tIter = tTypeParams; 1228 List<Type> sIter = sTypeParams; 1229 while (tIter.nonEmpty() && sIter.nonEmpty()) { 1230 Type tBound = tIter.head.getUpperBound(); 1231 Type sBound = types.subst(sIter.head.getUpperBound(), sTypeParams, tTypeParams); 1232 if (tBound.containsAny(tTypeParams) && inferenceContext().free(sBound)) { 1233 return false; 1234 } 1235 if (!types.isSameType(tBound, inferenceContext().asUndetVar(sBound))) { 1236 return false; 1237 } 1238 tIter = tIter.tail; 1239 sIter = sIter.tail; 1240 } 1241 if (!tIter.isEmpty() || !sIter.isEmpty()) { 1242 return false; 1243 } 1244 1245 // compare parameters 1246 List<Type> tParams = tDesc.getParameterTypes(); 1247 List<Type> tParamsNoCapture = tDescNoCapture.getParameterTypes(); 1248 List<Type> sParams = sDesc.getParameterTypes(); 1249 while (tParams.nonEmpty() && tParamsNoCapture.nonEmpty() && sParams.nonEmpty()) { 1250 Type tParam = tParams.head; 1251 Type tParamNoCapture = types.subst(tParamsNoCapture.head, tTypeParamsNoCapture, tTypeParams); 1252 Type sParam = types.subst(sParams.head, sTypeParams, tTypeParams); 1253 if (tParam.containsAny(tTypeParams) && inferenceContext().free(sParam)) { 1254 return false; 1255 } 1256 if (!types.isSubtype(inferenceContext().asUndetVar(sParam), tParam)) { 1257 return false; 1258 } 1259 if (!types.isSameType(tParamNoCapture, inferenceContext().asUndetVar(sParam))) { 1260 return false; 1261 } 1262 tParams = tParams.tail; 1263 tParamsNoCapture = tParamsNoCapture.tail; 1264 sParams = sParams.tail; 1265 } 1266 if (!tParams.isEmpty() || !tParamsNoCapture.isEmpty() || !sParams.isEmpty()) { 1267 return false; 1268 } 1269 1270 // compare returns 1271 Type tRet = tDesc.getReturnType(); 1272 Type sRet = types.subst(sDesc.getReturnType(), sTypeParams, tTypeParams); 1273 if (tRet.containsAny(tTypeParams) && inferenceContext().free(sRet)) { 1274 return false; 1275 } 1276 MostSpecificFunctionReturnChecker msc = new MostSpecificFunctionReturnChecker(tRet, sRet); 1277 msc.scan(tree); 1278 return msc.result; 1279 } 1280 1281 /** 1282 * Tests whether one functional interface type can be considered more specific 1283 * than another unrelated functional interface type for the scanned expression. 1284 */ 1285 class MostSpecificFunctionReturnChecker extends DeferredAttr.PolyScanner { 1286 1287 final Type tRet; 1288 final Type sRet; 1289 boolean result; 1290 1291 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */ 1292 MostSpecificFunctionReturnChecker(Type tRet, Type sRet) { 1293 this.tRet = tRet; 1294 this.sRet = sRet; 1295 result = true; 1296 } 1297 1298 @Override 1299 void skip(JCTree tree) { 1300 result = false; 1301 } 1302 1303 @Override 1304 public void visitConditional(JCConditional tree) { 1305 scan(asExpr(tree.truepart)); 1306 scan(asExpr(tree.falsepart)); 1307 } 1308 1309 @Override 1310 public void visitReference(JCMemberReference tree) { 1311 if (sRet.hasTag(VOID)) { 1312 // do nothing 1313 } else if (tRet.hasTag(VOID)) { 1314 result = false; 1315 } else if (tRet.isPrimitive() != sRet.isPrimitive()) { 1316 boolean retValIsPrimitive = 1317 tree.refPolyKind == PolyKind.STANDALONE && 1318 tree.sym.type.getReturnType().isPrimitive(); 1319 result &= (retValIsPrimitive == tRet.isPrimitive()) && 1320 (retValIsPrimitive != sRet.isPrimitive()); 1321 } else { 1322 result &= compatibleBySubtyping(tRet, sRet); 1323 } 1324 } 1325 1326 @Override 1327 public void visitParens(JCParens tree) { 1328 scan(asExpr(tree.expr)); 1329 } 1330 1331 @Override 1332 public void visitLambda(JCLambda tree) { 1333 if (sRet.hasTag(VOID)) { 1334 // do nothing 1335 } else if (tRet.hasTag(VOID)) { 1336 result = false; 1337 } else { 1338 List<JCExpression> lambdaResults = lambdaResults(tree); 1339 if (!lambdaResults.isEmpty() && unrelatedFunctionalInterfaces(tRet, sRet)) { 1340 for (JCExpression expr : lambdaResults) { 1341 result &= functionalInterfaceMostSpecific(tRet, sRet, expr); 1342 } 1343 } else if (!lambdaResults.isEmpty() && tRet.isPrimitive() != sRet.isPrimitive()) { 1344 for (JCExpression expr : lambdaResults) { 1345 boolean retValIsPrimitive = expr.isStandalone() && expr.type.isPrimitive(); 1346 result &= (retValIsPrimitive == tRet.isPrimitive()) && 1347 (retValIsPrimitive != sRet.isPrimitive()); 1348 } 1349 } else { 1350 result &= compatibleBySubtyping(tRet, sRet); 1351 } 1352 } 1353 } 1354 //where 1355 1356 private List<JCExpression> lambdaResults(JCLambda lambda) { 1357 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) { 1358 return List.of(asExpr((JCExpression) lambda.body)); 1359 } else { 1360 final ListBuffer<JCExpression> buffer = new ListBuffer<>(); 1361 DeferredAttr.LambdaReturnScanner lambdaScanner = 1362 new DeferredAttr.LambdaReturnScanner() { 1363 @Override 1364 public void visitReturn(JCReturn tree) { 1365 if (tree.expr != null) { 1366 buffer.append(asExpr(tree.expr)); 1367 } 1368 } 1369 }; 1370 lambdaScanner.scan(lambda.body); 1371 return buffer.toList(); 1372 } 1373 } 1374 1375 private JCExpression asExpr(JCExpression expr) { 1376 if (expr.type.hasTag(DEFERRED)) { 1377 JCTree speculativeTree = ((DeferredType)expr.type).speculativeTree(deferredAttrContext); 1378 if (speculativeTree != deferredAttr.stuckTree) { 1379 expr = (JCExpression)speculativeTree; 1380 } 1381 } 1382 return expr; 1383 } 1384 } 1385 1386 } 1387 1388 public MethodCheck mostSpecificCheck(List<Type> actuals) { 1389 Assert.error("Cannot get here!"); 1390 return null; 1391 } 1392 } 1393 1394 public static class InapplicableMethodException extends RuntimeException { 1395 private static final long serialVersionUID = 0; 1396 1397 transient JCDiagnostic diagnostic; 1398 1399 InapplicableMethodException(JCDiagnostic diag) { 1400 this.diagnostic = diag; 1401 } 1402 1403 public JCDiagnostic getDiagnostic() { 1404 return diagnostic; 1405 } 1406 1407 @Override 1408 public Throwable fillInStackTrace() { 1409 // This is an internal exception; the stack trace is irrelevant. 1410 return this; 1411 } 1412 } 1413 1414 /* *************************************************************************** 1415 * Symbol lookup 1416 * the following naming conventions for arguments are used 1417 * 1418 * env is the environment where the symbol was mentioned 1419 * site is the type of which the symbol is a member 1420 * name is the symbol's name 1421 * if no arguments are given 1422 * argtypes are the value arguments, if we search for a method 1423 * 1424 * If no symbol was found, a ResolveError detailing the problem is returned. 1425 ****************************************************************************/ 1426 1427 /** Find field. Synthetic fields are always skipped. 1428 * @param env The current environment. 1429 * @param site The original type from where the selection takes place. 1430 * @param name The name of the field. 1431 * @param c The class to search for the field. This is always 1432 * a superclass or implemented interface of site's class. 1433 */ 1434 Symbol findField(Env<AttrContext> env, 1435 Type site, 1436 Name name, 1437 TypeSymbol c) { 1438 while (c.type.hasTag(TYPEVAR)) 1439 c = c.type.getUpperBound().tsym; 1440 Symbol bestSoFar = varNotFound; 1441 Symbol sym; 1442 for (Symbol s : c.members().getSymbolsByName(name)) { 1443 if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) { 1444 return isAccessible(env, site, s) 1445 ? s : new AccessError(env, site, s); 1446 } 1447 } 1448 Type st = types.supertype(c.type); 1449 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) { 1450 sym = findField(env, site, name, st.tsym); 1451 bestSoFar = bestOf(bestSoFar, sym); 1452 } 1453 for (List<Type> l = types.interfaces(c.type); 1454 bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); 1455 l = l.tail) { 1456 sym = findField(env, site, name, l.head.tsym); 1457 if (bestSoFar.exists() && sym.exists() && 1458 sym.owner != bestSoFar.owner) 1459 bestSoFar = new AmbiguityError(bestSoFar, sym); 1460 else 1461 bestSoFar = bestOf(bestSoFar, sym); 1462 } 1463 return bestSoFar; 1464 } 1465 1466 /** Resolve a field identifier, throw a fatal error if not found. 1467 * @param pos The position to use for error reporting. 1468 * @param env The environment current at the method invocation. 1469 * @param site The type of the qualifying expression, in which 1470 * identifier is searched. 1471 * @param name The identifier's name. 1472 */ 1473 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env, 1474 Type site, Name name) { 1475 Symbol sym = findField(env, site, name, site.tsym); 1476 if (sym.kind == VAR) return (VarSymbol)sym; 1477 else throw new FatalError( 1478 diags.fragment(Fragments.FatalErrCantLocateField(name))); 1479 } 1480 1481 /** Find unqualified variable or field with given name. 1482 * Synthetic fields always skipped. 1483 * @param env The current environment. 1484 * @param name The name of the variable or field. 1485 */ 1486 Symbol findVar(Env<AttrContext> env, Name name) { 1487 Symbol bestSoFar = varNotFound; 1488 Env<AttrContext> env1 = env; 1489 boolean staticOnly = false; 1490 while (env1.outer != null) { 1491 Symbol sym = null; 1492 for (Symbol s : env1.info.scope.getSymbolsByName(name)) { 1493 if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) { 1494 sym = s; 1495 if (staticOnly) { 1496 return new StaticError(sym); 1497 } 1498 break; 1499 } 1500 } 1501 if (isStatic(env1)) staticOnly = true; 1502 if (sym == null) { 1503 sym = findField(env1, env1.enclClass.sym.type, name, env1.enclClass.sym); 1504 } 1505 if (sym.exists()) { 1506 if (staticOnly && 1507 sym.kind == VAR && 1508 sym.owner.kind == TYP && 1509 (sym.flags() & STATIC) == 0) 1510 return new StaticError(sym); 1511 else 1512 return sym; 1513 } else { 1514 bestSoFar = bestOf(bestSoFar, sym); 1515 } 1516 1517 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 1518 env1 = env1.outer; 1519 } 1520 1521 Symbol sym = findField(env, syms.predefClass.type, name, syms.predefClass); 1522 if (sym.exists()) 1523 return sym; 1524 if (bestSoFar.exists()) 1525 return bestSoFar; 1526 1527 Symbol origin = null; 1528 for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) { 1529 for (Symbol currentSymbol : sc.getSymbolsByName(name)) { 1530 if (currentSymbol.kind != VAR) 1531 continue; 1532 // invariant: sym.kind == Symbol.Kind.VAR 1533 if (!bestSoFar.kind.isResolutionError() && 1534 currentSymbol.owner != bestSoFar.owner) 1535 return new AmbiguityError(bestSoFar, currentSymbol); 1536 else if (!bestSoFar.kind.betterThan(VAR)) { 1537 origin = sc.getOrigin(currentSymbol).owner; 1538 bestSoFar = isAccessible(env, origin.type, currentSymbol) 1539 ? currentSymbol : new AccessError(env, origin.type, currentSymbol); 1540 } 1541 } 1542 if (bestSoFar.exists()) break; 1543 } 1544 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type) 1545 return bestSoFar.clone(origin); 1546 else 1547 return bestSoFar; 1548 } 1549 1550 Warner noteWarner = new Warner(); 1551 1552 /** Select the best method for a call site among two choices. 1553 * @param env The current environment. 1554 * @param site The original type from where the 1555 * selection takes place. 1556 * @param argtypes The invocation's value arguments, 1557 * @param typeargtypes The invocation's type arguments, 1558 * @param sym Proposed new best match. 1559 * @param bestSoFar Previously found best match. 1560 * @param allowBoxing Allow boxing conversions of arguments. 1561 * @param useVarargs Box trailing arguments into an array for varargs. 1562 */ 1563 @SuppressWarnings("fallthrough") 1564 Symbol selectBest(Env<AttrContext> env, 1565 Type site, 1566 List<Type> argtypes, 1567 List<Type> typeargtypes, 1568 Symbol sym, 1569 Symbol bestSoFar, 1570 boolean allowBoxing, 1571 boolean useVarargs) { 1572 if (sym.kind == ERR || 1573 (site.tsym != sym.owner && !sym.isInheritedIn(site.tsym, types)) || 1574 !notOverriddenIn(site, sym)) { 1575 return bestSoFar; 1576 } else if (useVarargs && (sym.flags() & VARARGS) == 0) { 1577 return bestSoFar.kind.isResolutionError() ? 1578 new BadVarargsMethod((ResolveError)bestSoFar.baseSymbol()) : 1579 bestSoFar; 1580 } 1581 Assert.check(!sym.kind.isResolutionError()); 1582 try { 1583 types.noWarnings.clear(); 1584 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes, 1585 allowBoxing, useVarargs, types.noWarnings); 1586 currentResolutionContext.addApplicableCandidate(sym, mt); 1587 } catch (InapplicableMethodException ex) { 1588 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic()); 1589 // Currently, an InapplicableMethodException occurs. 1590 // If bestSoFar.kind was ABSENT_MTH, return an InapplicableSymbolError(kind is WRONG_MTH). 1591 // If bestSoFar.kind was HIDDEN(AccessError)/WRONG_MTH/WRONG_MTHS, return an InapplicableSymbolsError(kind is WRONG_MTHS). 1592 // See JDK-8255968 for more information. 1593 switch (bestSoFar.kind) { 1594 case ABSENT_MTH: 1595 return new InapplicableSymbolError(currentResolutionContext); 1596 case HIDDEN: 1597 if (bestSoFar instanceof AccessError accessError) { 1598 // Add the JCDiagnostic of previous AccessError to the currentResolutionContext 1599 // and construct InapplicableSymbolsError. 1600 // Intentionally fallthrough. 1601 currentResolutionContext.addInapplicableCandidate(accessError.sym, 1602 accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes)); 1603 } else { 1604 return bestSoFar; 1605 } 1606 case WRONG_MTH: 1607 bestSoFar = new InapplicableSymbolsError(currentResolutionContext); 1608 default: 1609 return bestSoFar; 1610 } 1611 } 1612 if (!isAccessible(env, site, sym)) { 1613 AccessError curAccessError = new AccessError(env, site, sym); 1614 JCDiagnostic curDiagnostic = curAccessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes); 1615 // Currently, an AccessError occurs. 1616 // If bestSoFar.kind was ABSENT_MTH, return an AccessError(kind is HIDDEN). 1617 // If bestSoFar.kind was HIDDEN(AccessError), WRONG_MTH, WRONG_MTHS, return an InapplicableSymbolsError(kind is WRONG_MTHS). 1618 // See JDK-8255968 for more information. 1619 if (bestSoFar.kind == ABSENT_MTH) { 1620 bestSoFar = curAccessError; 1621 } else if (bestSoFar.kind == WRONG_MTH) { 1622 // Add the JCDiagnostic of current AccessError to the currentResolutionContext 1623 // and construct InapplicableSymbolsError. 1624 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic); 1625 bestSoFar = new InapplicableSymbolsError(currentResolutionContext); 1626 } else if (bestSoFar.kind == WRONG_MTHS) { 1627 // Add the JCDiagnostic of current AccessError to the currentResolutionContext 1628 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic); 1629 } else if (bestSoFar.kind == HIDDEN && bestSoFar instanceof AccessError accessError) { 1630 // Add the JCDiagnostics of previous and current AccessError to the currentResolutionContext 1631 // and construct InapplicableSymbolsError. 1632 currentResolutionContext.addInapplicableCandidate(accessError.sym, 1633 accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes)); 1634 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic); 1635 bestSoFar = new InapplicableSymbolsError(currentResolutionContext); 1636 } 1637 return bestSoFar; 1638 } 1639 return (bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS) 1640 ? sym 1641 : mostSpecific(argtypes, sym, bestSoFar, env, site, useVarargs); 1642 } 1643 1644 /* Return the most specific of the two methods for a call, 1645 * given that both are accessible and applicable. 1646 * @param m1 A new candidate for most specific. 1647 * @param m2 The previous most specific candidate. 1648 * @param env The current environment. 1649 * @param site The original type from where the selection 1650 * takes place. 1651 * @param allowBoxing Allow boxing conversions of arguments. 1652 * @param useVarargs Box trailing arguments into an array for varargs. 1653 */ 1654 Symbol mostSpecific(List<Type> argtypes, Symbol m1, 1655 Symbol m2, 1656 Env<AttrContext> env, 1657 final Type site, 1658 boolean useVarargs) { 1659 switch (m2.kind) { 1660 case MTH: 1661 if (m1 == m2) return m1; 1662 boolean m1SignatureMoreSpecific = 1663 signatureMoreSpecific(argtypes, env, site, m1, m2, useVarargs); 1664 boolean m2SignatureMoreSpecific = 1665 signatureMoreSpecific(argtypes, env, site, m2, m1, useVarargs); 1666 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) { 1667 Type mt1 = types.memberType(site, m1); 1668 Type mt2 = types.memberType(site, m2); 1669 if (!types.overrideEquivalent(mt1, mt2)) 1670 return ambiguityError(m1, m2); 1671 1672 // same signature; select (a) the non-bridge method, or 1673 // (b) the one that overrides the other, or (c) the concrete 1674 // one, or (d) merge both abstract signatures 1675 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) 1676 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1; 1677 1678 if (m1.baseSymbol() == m2.baseSymbol()) { 1679 // this is the same imported symbol which has been cloned twice. 1680 // Return the first one (either will do). 1681 return m1; 1682 } 1683 1684 // if one overrides or hides the other, use it 1685 TypeSymbol m1Owner = (TypeSymbol)m1.owner; 1686 TypeSymbol m2Owner = (TypeSymbol)m2.owner; 1687 // the two owners can never be the same if the target methods are compiled from source, 1688 // but we need to protect against cases where the methods are defined in some classfile 1689 // and make sure we issue an ambiguity error accordingly (by skipping the logic below). 1690 if (m1Owner != m2Owner) { 1691 if (types.asSuper(m1Owner.type, m2Owner) != null && 1692 ((m1.owner.flags_field & INTERFACE) == 0 || 1693 (m2.owner.flags_field & INTERFACE) != 0) && 1694 m1.overrides(m2, m1Owner, types, false)) 1695 return m1; 1696 if (types.asSuper(m2Owner.type, m1Owner) != null && 1697 ((m2.owner.flags_field & INTERFACE) == 0 || 1698 (m1.owner.flags_field & INTERFACE) != 0) && 1699 m2.overrides(m1, m2Owner, types, false)) 1700 return m2; 1701 } 1702 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0; 1703 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0; 1704 if (m1Abstract && !m2Abstract) return m2; 1705 if (m2Abstract && !m1Abstract) return m1; 1706 // both abstract or both concrete 1707 return ambiguityError(m1, m2); 1708 } 1709 if (m1SignatureMoreSpecific) return m1; 1710 if (m2SignatureMoreSpecific) return m2; 1711 return ambiguityError(m1, m2); 1712 case AMBIGUOUS: 1713 //compare m1 to ambiguous methods in m2 1714 AmbiguityError e = (AmbiguityError)m2.baseSymbol(); 1715 boolean m1MoreSpecificThanAnyAmbiguous = true; 1716 boolean allAmbiguousMoreSpecificThanM1 = true; 1717 for (Symbol s : e.ambiguousSyms) { 1718 Symbol moreSpecific = mostSpecific(argtypes, m1, s, env, site, useVarargs); 1719 m1MoreSpecificThanAnyAmbiguous &= moreSpecific == m1; 1720 allAmbiguousMoreSpecificThanM1 &= moreSpecific == s; 1721 } 1722 if (m1MoreSpecificThanAnyAmbiguous) 1723 return m1; 1724 //if m1 is more specific than some ambiguous methods, but other ambiguous methods are 1725 //more specific than m1, add it as a new ambiguous method: 1726 if (!allAmbiguousMoreSpecificThanM1) 1727 e.addAmbiguousSymbol(m1); 1728 return e; 1729 default: 1730 throw new AssertionError(); 1731 } 1732 } 1733 //where 1734 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean useVarargs) { 1735 noteWarner.clear(); 1736 int maxLength = Math.max( 1737 Math.max(m1.type.getParameterTypes().length(), actuals.length()), 1738 m2.type.getParameterTypes().length()); 1739 MethodResolutionContext prevResolutionContext = currentResolutionContext; 1740 try { 1741 currentResolutionContext = new MethodResolutionContext(); 1742 currentResolutionContext.step = prevResolutionContext.step; 1743 currentResolutionContext.methodCheck = 1744 prevResolutionContext.methodCheck.mostSpecificCheck(actuals); 1745 Type mst = instantiate(env, site, m2, null, 1746 adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null, 1747 false, useVarargs, noteWarner); 1748 return mst != null && 1749 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED); 1750 } finally { 1751 currentResolutionContext = prevResolutionContext; 1752 } 1753 } 1754 1755 List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) { 1756 if ((msym.flags() & VARARGS) != 0 && allowVarargs) { 1757 Type varargsElem = types.elemtype(args.last()); 1758 if (varargsElem == null) { 1759 Assert.error("Bad varargs = " + args.last() + " " + msym); 1760 } 1761 List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse(); 1762 while (newArgs.length() < length) { 1763 newArgs = newArgs.append(newArgs.last()); 1764 } 1765 return newArgs; 1766 } else { 1767 return args; 1768 } 1769 } 1770 //where 1771 Symbol ambiguityError(Symbol m1, Symbol m2) { 1772 if (((m1.flags() | m2.flags()) & CLASH) != 0) { 1773 return (m1.flags() & CLASH) == 0 ? m1 : m2; 1774 } else { 1775 return new AmbiguityError(m1, m2); 1776 } 1777 } 1778 1779 Symbol findMethodInScope(Env<AttrContext> env, 1780 Type site, 1781 Name name, 1782 List<Type> argtypes, 1783 List<Type> typeargtypes, 1784 Scope sc, 1785 Symbol bestSoFar, 1786 boolean allowBoxing, 1787 boolean useVarargs, 1788 boolean abstractok) { 1789 for (Symbol s : sc.getSymbolsByName(name, new LookupFilter(abstractok))) { 1790 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s, 1791 bestSoFar, allowBoxing, useVarargs); 1792 } 1793 return bestSoFar; 1794 } 1795 //where 1796 class LookupFilter implements Predicate<Symbol> { 1797 1798 boolean abstractOk; 1799 1800 LookupFilter(boolean abstractOk) { 1801 this.abstractOk = abstractOk; 1802 } 1803 1804 @Override 1805 public boolean test(Symbol s) { 1806 long flags = s.flags(); 1807 return s.kind == MTH && 1808 (flags & SYNTHETIC) == 0 && 1809 (abstractOk || 1810 (flags & DEFAULT) != 0 || 1811 (flags & ABSTRACT) == 0); 1812 } 1813 } 1814 1815 /** Find best qualified method matching given name, type and value 1816 * arguments. 1817 * @param env The current environment. 1818 * @param site The original type from where the selection 1819 * takes place. 1820 * @param name The method's name. 1821 * @param argtypes The method's value arguments. 1822 * @param typeargtypes The method's type arguments 1823 * @param allowBoxing Allow boxing conversions of arguments. 1824 * @param useVarargs Box trailing arguments into an array for varargs. 1825 */ 1826 Symbol findMethod(Env<AttrContext> env, 1827 Type site, 1828 Name name, 1829 List<Type> argtypes, 1830 List<Type> typeargtypes, 1831 boolean allowBoxing, 1832 boolean useVarargs) { 1833 Symbol bestSoFar = methodNotFound; 1834 bestSoFar = findMethod(env, 1835 site, 1836 name, 1837 argtypes, 1838 typeargtypes, 1839 site.tsym.type, 1840 bestSoFar, 1841 allowBoxing, 1842 useVarargs); 1843 return bestSoFar; 1844 } 1845 // where 1846 private Symbol findMethod(Env<AttrContext> env, 1847 Type site, 1848 Name name, 1849 List<Type> argtypes, 1850 List<Type> typeargtypes, 1851 Type intype, 1852 Symbol bestSoFar, 1853 boolean allowBoxing, 1854 boolean useVarargs) { 1855 @SuppressWarnings({"unchecked","rawtypes"}) 1856 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() }; 1857 1858 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK; 1859 boolean isInterface = site.tsym.isInterface(); 1860 for (TypeSymbol s : isInterface ? List.of(intype.tsym) : superclasses(intype)) { 1861 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes, 1862 s.members(), bestSoFar, allowBoxing, useVarargs, true); 1863 if (name == names.init) return bestSoFar; 1864 iphase = (iphase == null) ? null : iphase.update(s, this); 1865 if (iphase != null) { 1866 for (Type itype : types.interfaces(s.type)) { 1867 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]); 1868 } 1869 } 1870 } 1871 1872 Symbol concrete = bestSoFar.kind.isValid() && 1873 (bestSoFar.flags() & ABSTRACT) == 0 ? 1874 bestSoFar : methodNotFound; 1875 1876 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) { 1877 //keep searching for abstract methods 1878 for (Type itype : itypes[iphase2.ordinal()]) { 1879 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure()) 1880 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && 1881 (itype.tsym.flags() & DEFAULT) == 0) continue; 1882 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes, 1883 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, true); 1884 if (concrete != bestSoFar && 1885 concrete.kind.isValid() && 1886 bestSoFar.kind.isValid() && 1887 types.isSubSignature(concrete.type, bestSoFar.type)) { 1888 //this is an hack - as javac does not do full membership checks 1889 //most specific ends up comparing abstract methods that might have 1890 //been implemented by some concrete method in a subclass and, 1891 //because of raw override, it is possible for an abstract method 1892 //to be more specific than the concrete method - so we need 1893 //to explicitly call that out (see CR 6178365) 1894 bestSoFar = concrete; 1895 } 1896 } 1897 } 1898 if (isInterface && bestSoFar.kind.isResolutionError()) { 1899 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes, 1900 syms.objectType.tsym.members(), bestSoFar, allowBoxing, useVarargs, true); 1901 if (bestSoFar.kind.isValid()) { 1902 Symbol baseSymbol = bestSoFar; 1903 bestSoFar = new MethodSymbol(bestSoFar.flags_field, bestSoFar.name, bestSoFar.type, intype.tsym) { 1904 @Override 1905 public Symbol baseSymbol() { 1906 return baseSymbol; 1907 } 1908 }; 1909 } 1910 } 1911 return bestSoFar; 1912 } 1913 1914 enum InterfaceLookupPhase { 1915 ABSTRACT_OK() { 1916 @Override 1917 InterfaceLookupPhase update(Symbol s, Resolve rs) { 1918 //We should not look for abstract methods if receiver is a concrete class 1919 //(as concrete classes are expected to implement all abstracts coming 1920 //from superinterfaces) 1921 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) { 1922 return this; 1923 } else { 1924 return DEFAULT_OK; 1925 } 1926 } 1927 }, 1928 DEFAULT_OK() { 1929 @Override 1930 InterfaceLookupPhase update(Symbol s, Resolve rs) { 1931 return this; 1932 } 1933 }; 1934 1935 abstract InterfaceLookupPhase update(Symbol s, Resolve rs); 1936 } 1937 1938 /** 1939 * Return an Iterable object to scan the superclasses of a given type. 1940 * It's crucial that the scan is done lazily, as we don't want to accidentally 1941 * access more supertypes than strictly needed (as this could trigger completion 1942 * errors if some of the not-needed supertypes are missing/ill-formed). 1943 */ 1944 Iterable<TypeSymbol> superclasses(final Type intype) { 1945 return () -> new Iterator<TypeSymbol>() { 1946 1947 List<TypeSymbol> seen = List.nil(); 1948 TypeSymbol currentSym = symbolFor(intype); 1949 TypeSymbol prevSym = null; 1950 1951 public boolean hasNext() { 1952 if (currentSym == syms.noSymbol) { 1953 currentSym = symbolFor(types.supertype(prevSym.type)); 1954 } 1955 return currentSym != null; 1956 } 1957 1958 public TypeSymbol next() { 1959 prevSym = currentSym; 1960 currentSym = syms.noSymbol; 1961 Assert.check(prevSym != null || prevSym != syms.noSymbol); 1962 return prevSym; 1963 } 1964 1965 public void remove() { 1966 throw new UnsupportedOperationException(); 1967 } 1968 1969 TypeSymbol symbolFor(Type t) { 1970 if (!t.hasTag(CLASS) && 1971 !t.hasTag(TYPEVAR)) { 1972 return null; 1973 } 1974 t = types.skipTypeVars(t, false); 1975 if (seen.contains(t.tsym)) { 1976 //degenerate case in which we have a circular 1977 //class hierarchy - because of ill-formed classfiles 1978 return null; 1979 } 1980 seen = seen.prepend(t.tsym); 1981 return t.tsym; 1982 } 1983 }; 1984 } 1985 1986 /** Find unqualified method matching given name, type and value arguments. 1987 * @param env The current environment. 1988 * @param name The method's name. 1989 * @param argtypes The method's value arguments. 1990 * @param typeargtypes The method's type arguments. 1991 * @param allowBoxing Allow boxing conversions of arguments. 1992 * @param useVarargs Box trailing arguments into an array for varargs. 1993 */ 1994 Symbol findFun(Env<AttrContext> env, Name name, 1995 List<Type> argtypes, List<Type> typeargtypes, 1996 boolean allowBoxing, boolean useVarargs) { 1997 Symbol bestSoFar = methodNotFound; 1998 Env<AttrContext> env1 = env; 1999 boolean staticOnly = false; 2000 while (env1.outer != null) { 2001 if (isStatic(env1)) staticOnly = true; 2002 Assert.check(env1.info.preferredTreeForDiagnostics == null); 2003 env1.info.preferredTreeForDiagnostics = env.tree; 2004 try { 2005 Symbol sym = findMethod( 2006 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes, 2007 allowBoxing, useVarargs); 2008 if (sym.exists()) { 2009 if (staticOnly && 2010 sym.kind == MTH && 2011 sym.owner.kind == TYP && 2012 (sym.flags() & STATIC) == 0) return new StaticError(sym); 2013 else return sym; 2014 } else { 2015 bestSoFar = bestOf(bestSoFar, sym); 2016 } 2017 } finally { 2018 env1.info.preferredTreeForDiagnostics = null; 2019 } 2020 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 2021 env1 = env1.outer; 2022 } 2023 2024 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes, 2025 typeargtypes, allowBoxing, useVarargs); 2026 if (sym.exists()) 2027 return sym; 2028 2029 for (Symbol currentSym : env.toplevel.namedImportScope.getSymbolsByName(name)) { 2030 Symbol origin = env.toplevel.namedImportScope.getOrigin(currentSym).owner; 2031 if (currentSym.kind == MTH) { 2032 if (currentSym.owner.type != origin.type) 2033 currentSym = currentSym.clone(origin); 2034 if (!isAccessible(env, origin.type, currentSym)) 2035 currentSym = new AccessError(env, origin.type, currentSym); 2036 bestSoFar = selectBest(env, origin.type, 2037 argtypes, typeargtypes, 2038 currentSym, bestSoFar, 2039 allowBoxing, useVarargs); 2040 } 2041 } 2042 if (bestSoFar.exists()) 2043 return bestSoFar; 2044 2045 for (Symbol currentSym : env.toplevel.starImportScope.getSymbolsByName(name)) { 2046 Symbol origin = env.toplevel.starImportScope.getOrigin(currentSym).owner; 2047 if (currentSym.kind == MTH) { 2048 if (currentSym.owner.type != origin.type) 2049 currentSym = currentSym.clone(origin); 2050 if (!isAccessible(env, origin.type, currentSym)) 2051 currentSym = new AccessError(env, origin.type, currentSym); 2052 bestSoFar = selectBest(env, origin.type, 2053 argtypes, typeargtypes, 2054 currentSym, bestSoFar, 2055 allowBoxing, useVarargs); 2056 } 2057 } 2058 return bestSoFar; 2059 } 2060 2061 /** Load toplevel or member class with given fully qualified name and 2062 * verify that it is accessible. 2063 * @param env The current environment. 2064 * @param name The fully qualified name of the class to be loaded. 2065 */ 2066 Symbol loadClass(Env<AttrContext> env, Name name, RecoveryLoadClass recoveryLoadClass) { 2067 try { 2068 ClassSymbol c = finder.loadClass(env.toplevel.modle, name); 2069 return isAccessible(env, c) ? c : new AccessError(env, null, c); 2070 } catch (ClassFinder.BadClassFile err) { 2071 return new BadClassFileError(err); 2072 } catch (CompletionFailure ex) { 2073 Symbol candidate = recoveryLoadClass.loadClass(env, name); 2074 2075 if (candidate != null) { 2076 return candidate; 2077 } 2078 2079 return typeNotFound; 2080 } 2081 } 2082 2083 public interface RecoveryLoadClass { 2084 Symbol loadClass(Env<AttrContext> env, Name name); 2085 } 2086 2087 private final RecoveryLoadClass noRecovery = (env, name) -> null; 2088 2089 private final RecoveryLoadClass doRecoveryLoadClass = new RecoveryLoadClass() { 2090 @Override public Symbol loadClass(Env<AttrContext> env, Name name) { 2091 List<Name> candidates = Convert.classCandidates(name); 2092 return lookupInvisibleSymbol(env, name, 2093 n -> () -> createCompoundIterator(candidates, 2094 c -> syms.getClassesForName(c) 2095 .iterator()), 2096 (ms, n) -> { 2097 for (Name candidate : candidates) { 2098 try { 2099 return finder.loadClass(ms, candidate); 2100 } catch (CompletionFailure cf) { 2101 //ignore 2102 } 2103 } 2104 return null; 2105 }, sym -> sym.kind == Kind.TYP, typeNotFound); 2106 } 2107 }; 2108 2109 private final RecoveryLoadClass namedImportScopeRecovery = (env, name) -> { 2110 Scope importScope = env.toplevel.namedImportScope; 2111 Symbol existing = importScope.findFirst(Convert.shortName(name), 2112 sym -> sym.kind == TYP && sym.flatName() == name); 2113 2114 if (existing != null) { 2115 return new InvisibleSymbolError(env, true, existing); 2116 } 2117 return null; 2118 }; 2119 2120 private final RecoveryLoadClass starImportScopeRecovery = (env, name) -> { 2121 Scope importScope = env.toplevel.starImportScope; 2122 Symbol existing = importScope.findFirst(Convert.shortName(name), 2123 sym -> sym.kind == TYP && sym.flatName() == name); 2124 2125 if (existing != null) { 2126 try { 2127 existing = finder.loadClass(existing.packge().modle, name); 2128 2129 return new InvisibleSymbolError(env, true, existing); 2130 } catch (CompletionFailure cf) { 2131 //ignore 2132 } 2133 } 2134 2135 return null; 2136 }; 2137 2138 Symbol lookupPackage(Env<AttrContext> env, Name name) { 2139 PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, name); 2140 2141 if (allowModules && isImportOnDemand(env, name)) { 2142 if (pack.members().isEmpty()) { 2143 return lookupInvisibleSymbol(env, name, syms::getPackagesForName, syms::enterPackage, sym -> { 2144 sym.complete(); 2145 return !sym.members().isEmpty(); 2146 }, pack); 2147 } 2148 } 2149 2150 return pack; 2151 } 2152 2153 private boolean isImportOnDemand(Env<AttrContext> env, Name name) { 2154 if (!env.tree.hasTag(IMPORT)) 2155 return false; 2156 2157 JCTree qualid = ((JCImport) env.tree).qualid; 2158 2159 if (!qualid.hasTag(SELECT)) 2160 return false; 2161 2162 if (TreeInfo.name(qualid) != names.asterisk) 2163 return false; 2164 2165 return TreeInfo.fullName(((JCFieldAccess) qualid).selected) == name; 2166 } 2167 2168 private <S extends Symbol> Symbol lookupInvisibleSymbol(Env<AttrContext> env, 2169 Name name, 2170 Function<Name, Iterable<S>> get, 2171 BiFunction<ModuleSymbol, Name, S> load, 2172 Predicate<S> validate, 2173 Symbol defaultResult) { 2174 //even if a class/package cannot be found in the current module and among packages in modules 2175 //it depends on that are exported for any or this module, the class/package may exist internally 2176 //in some of these modules, or may exist in a module on which this module does not depend. 2177 //Provide better diagnostic in such cases by looking for the class in any module: 2178 Iterable<? extends S> candidates = get.apply(name); 2179 2180 for (S sym : candidates) { 2181 if (validate.test(sym)) 2182 return createInvisibleSymbolError(env, sym); 2183 } 2184 2185 Set<ModuleSymbol> recoverableModules = new HashSet<>(syms.getAllModules()); 2186 2187 recoverableModules.add(syms.unnamedModule); 2188 recoverableModules.remove(env.toplevel.modle); 2189 2190 for (ModuleSymbol ms : recoverableModules) { 2191 //avoid overly eager completing classes from source-based modules, as those 2192 //may not be completable with the current compiler settings: 2193 if (ms.sourceLocation == null) { 2194 if (ms.classLocation == null) { 2195 ms = moduleFinder.findModule(ms); 2196 } 2197 2198 if (ms.kind != ERR) { 2199 S sym = load.apply(ms, name); 2200 2201 if (sym != null && validate.test(sym)) { 2202 return createInvisibleSymbolError(env, sym); 2203 } 2204 } 2205 } 2206 } 2207 2208 return defaultResult; 2209 } 2210 2211 private Symbol createInvisibleSymbolError(Env<AttrContext> env, Symbol sym) { 2212 if (symbolPackageVisible(env, sym)) { 2213 return new AccessError(env, null, sym); 2214 } else { 2215 return new InvisibleSymbolError(env, false, sym); 2216 } 2217 } 2218 2219 private boolean symbolPackageVisible(Env<AttrContext> env, Symbol sym) { 2220 ModuleSymbol envMod = env.toplevel.modle; 2221 PackageSymbol symPack = sym.packge(); 2222 return envMod == symPack.modle || 2223 envMod.visiblePackages.containsKey(symPack.fullname); 2224 } 2225 2226 /** 2227 * Find a type declared in a scope (not inherited). Return null 2228 * if none is found. 2229 * @param env The current environment. 2230 * @param site The original type from where the selection takes 2231 * place. 2232 * @param name The type's name. 2233 * @param c The class to search for the member type. This is 2234 * always a superclass or implemented interface of 2235 * site's class. 2236 */ 2237 Symbol findImmediateMemberType(Env<AttrContext> env, 2238 Type site, 2239 Name name, 2240 TypeSymbol c) { 2241 for (Symbol sym : c.members().getSymbolsByName(name)) { 2242 if (sym.kind == TYP) { 2243 return isAccessible(env, site, sym) 2244 ? sym 2245 : new AccessError(env, site, sym); 2246 } 2247 } 2248 return typeNotFound; 2249 } 2250 2251 /** Find a member type inherited from a superclass or interface. 2252 * @param env The current environment. 2253 * @param site The original type from where the selection takes 2254 * place. 2255 * @param name The type's name. 2256 * @param c The class to search for the member type. This is 2257 * always a superclass or implemented interface of 2258 * site's class. 2259 */ 2260 Symbol findInheritedMemberType(Env<AttrContext> env, 2261 Type site, 2262 Name name, 2263 TypeSymbol c) { 2264 Symbol bestSoFar = typeNotFound; 2265 Symbol sym; 2266 Type st = types.supertype(c.type); 2267 if (st != null && st.hasTag(CLASS)) { 2268 sym = findMemberType(env, site, name, st.tsym); 2269 bestSoFar = bestOf(bestSoFar, sym); 2270 } 2271 for (List<Type> l = types.interfaces(c.type); 2272 bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); 2273 l = l.tail) { 2274 sym = findMemberType(env, site, name, l.head.tsym); 2275 if (!bestSoFar.kind.isResolutionError() && 2276 !sym.kind.isResolutionError() && 2277 sym.owner != bestSoFar.owner) 2278 bestSoFar = new AmbiguityError(bestSoFar, sym); 2279 else 2280 bestSoFar = bestOf(bestSoFar, sym); 2281 } 2282 return bestSoFar; 2283 } 2284 2285 /** Find qualified member type. 2286 * @param env The current environment. 2287 * @param site The original type from where the selection takes 2288 * place. 2289 * @param name The type's name. 2290 * @param c The class to search for the member type. This is 2291 * always a superclass or implemented interface of 2292 * site's class. 2293 */ 2294 Symbol findMemberType(Env<AttrContext> env, 2295 Type site, 2296 Name name, 2297 TypeSymbol c) { 2298 Symbol sym = findImmediateMemberType(env, site, name, c); 2299 2300 if (sym != typeNotFound) 2301 return sym; 2302 2303 return findInheritedMemberType(env, site, name, c); 2304 2305 } 2306 2307 /** Find a global type in given scope and load corresponding class. 2308 * @param env The current environment. 2309 * @param scope The scope in which to look for the type. 2310 * @param name The type's name. 2311 */ 2312 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name, RecoveryLoadClass recoveryLoadClass) { 2313 Symbol bestSoFar = typeNotFound; 2314 for (Symbol s : scope.getSymbolsByName(name)) { 2315 Symbol sym = loadClass(env, s.flatName(), recoveryLoadClass); 2316 if (bestSoFar.kind == TYP && sym.kind == TYP && 2317 bestSoFar != sym) 2318 return new AmbiguityError(bestSoFar, sym); 2319 else 2320 bestSoFar = bestOf(bestSoFar, sym); 2321 } 2322 return bestSoFar; 2323 } 2324 2325 Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) { 2326 for (Symbol sym : env.info.scope.getSymbolsByName(name)) { 2327 if (sym.kind == TYP) { 2328 if (sym.type.hasTag(TYPEVAR) && 2329 (staticOnly || (isStatic(env) && sym.owner.kind == TYP))) 2330 // if staticOnly is set, it means that we have recursed through a static declaration, 2331 // so type variable symbols should not be accessible. If staticOnly is unset, but 2332 // we are in a static declaration (field or method), we should not allow type-variables 2333 // defined in the enclosing class to "leak" into this context. 2334 return new StaticError(sym); 2335 return sym; 2336 } 2337 } 2338 return typeNotFound; 2339 } 2340 2341 /** Find an unqualified type symbol. 2342 * @param env The current environment. 2343 * @param name The type's name. 2344 */ 2345 Symbol findType(Env<AttrContext> env, Name name) { 2346 if (name == names.empty) 2347 return typeNotFound; // do not allow inadvertent "lookup" of anonymous types 2348 Symbol bestSoFar = typeNotFound; 2349 Symbol sym; 2350 boolean staticOnly = false; 2351 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) { 2352 // First, look for a type variable and the first member type 2353 final Symbol tyvar = findTypeVar(env1, name, staticOnly); 2354 if (isStatic(env1)) staticOnly = true; 2355 sym = findImmediateMemberType(env1, env1.enclClass.sym.type, 2356 name, env1.enclClass.sym); 2357 2358 // Return the type variable if we have it, and have no 2359 // immediate member, OR the type variable is for a method. 2360 if (tyvar != typeNotFound) { 2361 if (env.baseClause || sym == typeNotFound || 2362 (tyvar.kind == TYP && tyvar.exists() && 2363 tyvar.owner.kind == MTH)) { 2364 return tyvar; 2365 } 2366 } 2367 2368 // If the environment is a class def, finish up, 2369 // otherwise, do the entire findMemberType 2370 if (sym == typeNotFound) 2371 sym = findInheritedMemberType(env1, env1.enclClass.sym.type, 2372 name, env1.enclClass.sym); 2373 2374 if (staticOnly && sym.kind == TYP && 2375 sym.type.hasTag(CLASS) && 2376 sym.type.getEnclosingType().hasTag(CLASS) && 2377 env1.enclClass.sym.type.isParameterized() && 2378 sym.type.getEnclosingType().isParameterized()) 2379 return new StaticError(sym); 2380 else if (sym.exists()) return sym; 2381 else bestSoFar = bestOf(bestSoFar, sym); 2382 2383 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass; 2384 if ((encl.sym.flags() & STATIC) != 0) 2385 staticOnly = true; 2386 } 2387 2388 if (!env.tree.hasTag(IMPORT)) { 2389 sym = findGlobalType(env, env.toplevel.namedImportScope, name, namedImportScopeRecovery); 2390 if (sym.exists()) return sym; 2391 else bestSoFar = bestOf(bestSoFar, sym); 2392 2393 sym = findGlobalType(env, env.toplevel.toplevelScope, name, noRecovery); 2394 if (sym.exists()) return sym; 2395 else bestSoFar = bestOf(bestSoFar, sym); 2396 2397 sym = findGlobalType(env, env.toplevel.packge.members(), name, noRecovery); 2398 if (sym.exists()) return sym; 2399 else bestSoFar = bestOf(bestSoFar, sym); 2400 2401 sym = findGlobalType(env, env.toplevel.starImportScope, name, starImportScopeRecovery); 2402 if (sym.exists()) return sym; 2403 else bestSoFar = bestOf(bestSoFar, sym); 2404 } 2405 2406 return bestSoFar; 2407 } 2408 2409 /** Find an unqualified identifier which matches a specified kind set. 2410 * @param pos position on which report warnings, if any; 2411 * null warnings should not be reported 2412 * @param env The current environment. 2413 * @param name The identifier's name. 2414 * @param kind Indicates the possible symbol kinds 2415 * (a subset of VAL, TYP, PCK). 2416 */ 2417 Symbol findIdent(DiagnosticPosition pos, Env<AttrContext> env, Name name, KindSelector kind) { 2418 return checkNonExistentType(checkRestrictedType(pos, findIdentInternal(env, name, kind), name)); 2419 } 2420 2421 Symbol findIdentInternal(Env<AttrContext> env, Name name, KindSelector kind) { 2422 Symbol bestSoFar = typeNotFound; 2423 Symbol sym; 2424 2425 if (kind.contains(KindSelector.VAL)) { 2426 sym = findVar(env, name); 2427 if (sym.exists()) return sym; 2428 else bestSoFar = bestOf(bestSoFar, sym); 2429 } 2430 2431 if (kind.contains(KindSelector.TYP)) { 2432 sym = findType(env, name); 2433 if (sym.exists()) return sym; 2434 else bestSoFar = bestOf(bestSoFar, sym); 2435 } 2436 2437 if (kind.contains(KindSelector.PCK)) 2438 return lookupPackage(env, name); 2439 else return bestSoFar; 2440 } 2441 2442 /** Find an identifier in a package which matches a specified kind set. 2443 * @param pos position on which report warnings, if any; 2444 * null warnings should not be reported 2445 * @param env The current environment. 2446 * @param name The identifier's name. 2447 * @param kind Indicates the possible symbol kinds 2448 * (a nonempty subset of TYP, PCK). 2449 */ 2450 Symbol findIdentInPackage(DiagnosticPosition pos, 2451 Env<AttrContext> env, TypeSymbol pck, 2452 Name name, KindSelector kind) { 2453 return checkNonExistentType(checkRestrictedType(pos, findIdentInPackageInternal(env, pck, name, kind), name)); 2454 } 2455 2456 Symbol findIdentInPackageInternal(Env<AttrContext> env, TypeSymbol pck, 2457 Name name, KindSelector kind) { 2458 Name fullname = TypeSymbol.formFullName(name, pck); 2459 Symbol bestSoFar = typeNotFound; 2460 if (kind.contains(KindSelector.TYP)) { 2461 RecoveryLoadClass recoveryLoadClass = 2462 allowModules && !kind.contains(KindSelector.PCK) && 2463 !pck.exists() && !env.info.attributionMode.isSpeculative ? 2464 doRecoveryLoadClass : noRecovery; 2465 Symbol sym = loadClass(env, fullname, recoveryLoadClass); 2466 if (sym.exists()) { 2467 // don't allow programs to use flatnames 2468 if (name == sym.name) return sym; 2469 } 2470 else bestSoFar = bestOf(bestSoFar, sym); 2471 } 2472 if (kind.contains(KindSelector.PCK)) { 2473 return lookupPackage(env, fullname); 2474 } 2475 return bestSoFar; 2476 } 2477 2478 /** Find an identifier among the members of a given type `site'. 2479 * @param pos position on which report warnings, if any; 2480 * null warnings should not be reported 2481 * @param env The current environment. 2482 * @param site The type containing the symbol to be found. 2483 * @param name The identifier's name. 2484 * @param kind Indicates the possible symbol kinds 2485 * (a subset of VAL, TYP). 2486 */ 2487 Symbol findIdentInType(DiagnosticPosition pos, 2488 Env<AttrContext> env, Type site, 2489 Name name, KindSelector kind) { 2490 return checkNonExistentType(checkRestrictedType(pos, findIdentInTypeInternal(env, site, name, kind), name)); 2491 } 2492 2493 private Symbol checkNonExistentType(Symbol symbol) { 2494 /* Guard against returning a type is not on the class path of the current compilation, 2495 * but *was* on the class path of a separate compilation that produced a class file 2496 * that is on the class path of the current compilation. Such a type will fail completion 2497 * but the completion failure may have been silently swallowed (e.g. missing annotation types) 2498 * with an error stub symbol lingering in the symbol tables. 2499 */ 2500 return symbol instanceof ClassSymbol c && c.type.isErroneous() && c.classfile == null ? typeNotFound : symbol; 2501 } 2502 2503 Symbol findIdentInTypeInternal(Env<AttrContext> env, Type site, 2504 Name name, KindSelector kind) { 2505 Symbol bestSoFar = typeNotFound; 2506 Symbol sym; 2507 if (kind.contains(KindSelector.VAL)) { 2508 sym = findField(env, site, name, site.tsym); 2509 if (sym.exists()) return sym; 2510 else bestSoFar = bestOf(bestSoFar, sym); 2511 } 2512 2513 if (kind.contains(KindSelector.TYP)) { 2514 sym = findMemberType(env, site, name, site.tsym); 2515 if (sym.exists()) return sym; 2516 else bestSoFar = bestOf(bestSoFar, sym); 2517 } 2518 return bestSoFar; 2519 } 2520 2521 private Symbol checkRestrictedType(DiagnosticPosition pos, Symbol bestSoFar, Name name) { 2522 if (bestSoFar.kind == TYP || bestSoFar.kind == ABSENT_TYP) { 2523 if (allowLocalVariableTypeInference && name.equals(names.var)) { 2524 bestSoFar = new BadRestrictedTypeError(names.var); 2525 } else if (name.equals(names.yield)) { 2526 if (allowYieldStatement) { 2527 bestSoFar = new BadRestrictedTypeError(names.yield); 2528 } else if (pos != null) { 2529 log.warning(pos, Warnings.IllegalRefToRestrictedType(names.yield)); 2530 } 2531 } 2532 } 2533 return bestSoFar; 2534 } 2535 2536 /* *************************************************************************** 2537 * Access checking 2538 * The following methods convert ResolveErrors to ErrorSymbols, issuing 2539 * an error message in the process 2540 ****************************************************************************/ 2541 2542 /** If `sym' is a bad symbol: report error and return errSymbol 2543 * else pass through unchanged, 2544 * additional arguments duplicate what has been used in trying to find the 2545 * symbol {@literal (--> flyweight pattern)}. This improves performance since we 2546 * expect misses to happen frequently. 2547 * 2548 * @param sym The symbol that was found, or a ResolveError. 2549 * @param pos The position to use for error reporting. 2550 * @param location The symbol the served as a context for this lookup 2551 * @param site The original type from where the selection took place. 2552 * @param name The symbol's name. 2553 * @param qualified Did we get here through a qualified expression resolution? 2554 * @param argtypes The invocation's value arguments, 2555 * if we looked for a method. 2556 * @param typeargtypes The invocation's type arguments, 2557 * if we looked for a method. 2558 * @param logResolveHelper helper class used to log resolve errors 2559 */ 2560 Symbol accessInternal(Symbol sym, 2561 DiagnosticPosition pos, 2562 Symbol location, 2563 Type site, 2564 Name name, 2565 boolean qualified, 2566 List<Type> argtypes, 2567 List<Type> typeargtypes, 2568 LogResolveHelper logResolveHelper) { 2569 if (sym.kind.isResolutionError()) { 2570 ResolveError errSym = (ResolveError)sym.baseSymbol(); 2571 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol); 2572 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes); 2573 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) { 2574 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes); 2575 } 2576 } 2577 return sym; 2578 } 2579 2580 /** 2581 * Variant of the generalized access routine, to be used for generating method 2582 * resolution diagnostics 2583 */ 2584 Symbol accessMethod(Symbol sym, 2585 DiagnosticPosition pos, 2586 Symbol location, 2587 Type site, 2588 Name name, 2589 boolean qualified, 2590 List<Type> argtypes, 2591 List<Type> typeargtypes) { 2592 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper); 2593 } 2594 2595 /** Same as original accessMethod(), but without location. 2596 */ 2597 Symbol accessMethod(Symbol sym, 2598 DiagnosticPosition pos, 2599 Type site, 2600 Name name, 2601 boolean qualified, 2602 List<Type> argtypes, 2603 List<Type> typeargtypes) { 2604 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes); 2605 } 2606 2607 /** 2608 * Variant of the generalized access routine, to be used for generating variable, 2609 * type resolution diagnostics 2610 */ 2611 Symbol accessBase(Symbol sym, 2612 DiagnosticPosition pos, 2613 Symbol location, 2614 Type site, 2615 Name name, 2616 boolean qualified) { 2617 return accessInternal(sym, pos, location, site, name, qualified, List.nil(), null, basicLogResolveHelper); 2618 } 2619 2620 /** Same as original accessBase(), but without location. 2621 */ 2622 Symbol accessBase(Symbol sym, 2623 DiagnosticPosition pos, 2624 Type site, 2625 Name name, 2626 boolean qualified) { 2627 return accessBase(sym, pos, site.tsym, site, name, qualified); 2628 } 2629 2630 interface LogResolveHelper { 2631 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes); 2632 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes); 2633 } 2634 2635 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() { 2636 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) { 2637 return !site.isErroneous(); 2638 } 2639 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) { 2640 return argtypes; 2641 } 2642 }; 2643 2644 LogResolveHelper silentLogResolveHelper = new LogResolveHelper() { 2645 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) { 2646 return false; 2647 } 2648 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) { 2649 return argtypes; 2650 } 2651 }; 2652 2653 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() { 2654 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) { 2655 return !site.isErroneous() && 2656 !Type.isErroneous(argtypes) && 2657 (typeargtypes == null || !Type.isErroneous(typeargtypes)); 2658 } 2659 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) { 2660 return argtypes.map(new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step)); 2661 } 2662 }; 2663 2664 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap { 2665 2666 public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) { 2667 deferredAttr.super(mode, msym, step); 2668 } 2669 2670 @Override 2671 protected Type typeOf(DeferredType dt, Type pt) { 2672 Type res = super.typeOf(dt, pt); 2673 if (!res.isErroneous()) { 2674 switch (TreeInfo.skipParens(dt.tree).getTag()) { 2675 case LAMBDA: 2676 case REFERENCE: 2677 return dt; 2678 case CONDEXPR: 2679 return res == Type.recoveryType ? 2680 dt : res; 2681 } 2682 } 2683 return res; 2684 } 2685 } 2686 2687 /** Check that sym is not an abstract method. 2688 */ 2689 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) { 2690 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0) 2691 log.error(pos, 2692 Errors.AbstractCantBeAccessedDirectly(kindName(sym),sym, sym.location())); 2693 } 2694 2695 /* *************************************************************************** 2696 * Name resolution 2697 * Naming conventions are as for symbol lookup 2698 * Unlike the find... methods these methods will report access errors 2699 ****************************************************************************/ 2700 2701 /** Resolve an unqualified (non-method) identifier. 2702 * @param pos The position to use for error reporting. 2703 * @param env The environment current at the identifier use. 2704 * @param name The identifier's name. 2705 * @param kind The set of admissible symbol kinds for the identifier. 2706 */ 2707 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env, 2708 Name name, KindSelector kind) { 2709 return accessBase( 2710 findIdent(pos, env, name, kind), 2711 pos, env.enclClass.sym.type, name, false); 2712 } 2713 2714 /** Resolve an unqualified method identifier. 2715 * @param pos The position to use for error reporting. 2716 * @param env The environment current at the method invocation. 2717 * @param name The identifier's name. 2718 * @param argtypes The types of the invocation's value arguments. 2719 * @param typeargtypes The types of the invocation's type arguments. 2720 */ 2721 Symbol resolveMethod(DiagnosticPosition pos, 2722 Env<AttrContext> env, 2723 Name name, 2724 List<Type> argtypes, 2725 List<Type> typeargtypes) { 2726 return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck, 2727 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) { 2728 @Override 2729 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2730 return findFun(env, name, argtypes, typeargtypes, 2731 phase.isBoxingRequired(), 2732 phase.isVarargsRequired()); 2733 }}); 2734 } 2735 2736 /** Resolve a qualified method identifier 2737 * @param pos The position to use for error reporting. 2738 * @param env The environment current at the method invocation. 2739 * @param site The type of the qualifying expression, in which 2740 * identifier is searched. 2741 * @param name The identifier's name. 2742 * @param argtypes The types of the invocation's value arguments. 2743 * @param typeargtypes The types of the invocation's type arguments. 2744 */ 2745 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env, 2746 Type site, Name name, List<Type> argtypes, 2747 List<Type> typeargtypes) { 2748 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes); 2749 } 2750 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env, 2751 Symbol location, Type site, Name name, List<Type> argtypes, 2752 List<Type> typeargtypes) { 2753 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes); 2754 } 2755 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext, 2756 DiagnosticPosition pos, Env<AttrContext> env, 2757 Symbol location, Type site, Name name, List<Type> argtypes, 2758 List<Type> typeargtypes) { 2759 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) { 2760 @Override 2761 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2762 return findMethod(env, site, name, argtypes, typeargtypes, 2763 phase.isBoxingRequired(), 2764 phase.isVarargsRequired()); 2765 } 2766 @Override 2767 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 2768 if (sym.kind.isResolutionError()) { 2769 sym = super.access(env, pos, location, sym); 2770 } else { 2771 MethodSymbol msym = (MethodSymbol)sym; 2772 if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) { 2773 env.info.pendingResolutionPhase = BASIC; 2774 return findPolymorphicSignatureInstance(env, sym, argtypes); 2775 } 2776 } 2777 return sym; 2778 } 2779 }); 2780 } 2781 2782 /** Find or create an implicit method of exactly the given type (after erasure). 2783 * Searches in a side table, not the main scope of the site. 2784 * This emulates the lookup process required by JSR 292 in JVM. 2785 * @param env Attribution environment 2786 * @param spMethod signature polymorphic method - i.e. MH.invokeExact 2787 * @param argtypes The required argument types 2788 */ 2789 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, 2790 final Symbol spMethod, 2791 List<Type> argtypes) { 2792 Type mtype = infer.instantiatePolymorphicSignatureInstance(env, 2793 (MethodSymbol)spMethod, currentResolutionContext, argtypes); 2794 return findPolymorphicSignatureInstance(spMethod, mtype); 2795 } 2796 2797 Symbol findPolymorphicSignatureInstance(final Symbol spMethod, 2798 Type mtype) { 2799 for (Symbol sym : polymorphicSignatureScope.getSymbolsByName(spMethod.name)) { 2800 // Check that there is already a method symbol for the method 2801 // type and owner 2802 if (types.isSameType(mtype, sym.type) && 2803 spMethod.owner == sym.owner) { 2804 return sym; 2805 } 2806 } 2807 2808 Type spReturnType = spMethod.asType().getReturnType(); 2809 if (types.isSameType(spReturnType, syms.objectType)) { 2810 // Polymorphic return, pass through mtype 2811 } else if (!types.isSameType(spReturnType, mtype.getReturnType())) { 2812 // Retain the sig poly method's return type, which differs from that of mtype 2813 // Will result in an incompatible return type error 2814 mtype = new MethodType(mtype.getParameterTypes(), 2815 spReturnType, 2816 mtype.getThrownTypes(), 2817 syms.methodClass); 2818 } 2819 2820 // Create the desired method 2821 // Retain static modifier is to support invocations to 2822 // MethodHandle.linkTo* methods 2823 long flags = ABSTRACT | HYPOTHETICAL | 2824 spMethod.flags() & (Flags.AccessFlags | Flags.STATIC); 2825 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) { 2826 @Override 2827 public Symbol baseSymbol() { 2828 return spMethod; 2829 } 2830 }; 2831 if (!mtype.isErroneous()) { // Cache only if kosher. 2832 polymorphicSignatureScope.enter(msym); 2833 } 2834 return msym; 2835 } 2836 2837 /** Resolve a qualified method identifier, throw a fatal error if not 2838 * found. 2839 * @param pos The position to use for error reporting. 2840 * @param env The environment current at the method invocation. 2841 * @param site The type of the qualifying expression, in which 2842 * identifier is searched. 2843 * @param name The identifier's name. 2844 * @param argtypes The types of the invocation's value arguments. 2845 * @param typeargtypes The types of the invocation's type arguments. 2846 */ 2847 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env, 2848 Type site, Name name, 2849 List<Type> argtypes, 2850 List<Type> typeargtypes) { 2851 MethodResolutionContext resolveContext = new MethodResolutionContext(); 2852 resolveContext.internalResolution = true; 2853 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym, 2854 site, name, argtypes, typeargtypes); 2855 if (sym.kind == MTH) return (MethodSymbol)sym; 2856 else throw new FatalError( 2857 diags.fragment(Fragments.FatalErrCantLocateMeth(name))); 2858 } 2859 2860 /** Resolve constructor. 2861 * @param pos The position to use for error reporting. 2862 * @param env The environment current at the constructor invocation. 2863 * @param site The type of class for which a constructor is searched. 2864 * @param argtypes The types of the constructor invocation's value 2865 * arguments. 2866 * @param typeargtypes The types of the constructor invocation's type 2867 * arguments. 2868 */ 2869 Symbol resolveConstructor(DiagnosticPosition pos, 2870 Env<AttrContext> env, 2871 Type site, 2872 List<Type> argtypes, 2873 List<Type> typeargtypes) { 2874 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes); 2875 } 2876 2877 private Symbol resolveConstructor(MethodResolutionContext resolveContext, 2878 final DiagnosticPosition pos, 2879 Env<AttrContext> env, 2880 Type site, 2881 List<Type> argtypes, 2882 List<Type> typeargtypes) { 2883 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) { 2884 @Override 2885 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2886 return findConstructor(pos, env, site, argtypes, typeargtypes, 2887 phase.isBoxingRequired(), 2888 phase.isVarargsRequired()); 2889 } 2890 }); 2891 } 2892 2893 /** Resolve a constructor, throw a fatal error if not found. 2894 * @param pos The position to use for error reporting. 2895 * @param env The environment current at the method invocation. 2896 * @param site The type to be constructed. 2897 * @param argtypes The types of the invocation's value arguments. 2898 * @param typeargtypes The types of the invocation's type arguments. 2899 */ 2900 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env, 2901 Type site, 2902 List<Type> argtypes, 2903 List<Type> typeargtypes) { 2904 MethodResolutionContext resolveContext = new MethodResolutionContext(); 2905 resolveContext.internalResolution = true; 2906 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes); 2907 if (sym.kind == MTH) return (MethodSymbol)sym; 2908 else throw new FatalError( 2909 diags.fragment(Fragments.FatalErrCantLocateCtor(site))); 2910 } 2911 2912 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env, 2913 Type site, List<Type> argtypes, 2914 List<Type> typeargtypes, 2915 boolean allowBoxing, 2916 boolean useVarargs) { 2917 Symbol sym = findMethod(env, site, 2918 names.init, argtypes, 2919 typeargtypes, allowBoxing, 2920 useVarargs); 2921 chk.checkDeprecated(pos, env.info.scope.owner, sym); 2922 chk.checkPreview(pos, env.info.scope.owner, sym); 2923 return sym; 2924 } 2925 2926 /** Resolve constructor using diamond inference. 2927 * @param pos The position to use for error reporting. 2928 * @param env The environment current at the constructor invocation. 2929 * @param site The type of class for which a constructor is searched. 2930 * The scope of this class has been touched in attribution. 2931 * @param argtypes The types of the constructor invocation's value 2932 * arguments. 2933 * @param typeargtypes The types of the constructor invocation's type 2934 * arguments. 2935 */ 2936 Symbol resolveDiamond(DiagnosticPosition pos, 2937 Env<AttrContext> env, 2938 Type site, 2939 List<Type> argtypes, 2940 List<Type> typeargtypes) { 2941 return lookupMethod(env, pos, site.tsym, resolveMethodCheck, 2942 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) { 2943 @Override 2944 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2945 return findDiamond(pos, env, site, argtypes, typeargtypes, 2946 phase.isBoxingRequired(), 2947 phase.isVarargsRequired()); 2948 } 2949 @Override 2950 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 2951 if (sym.kind.isResolutionError()) { 2952 if (sym.kind != WRONG_MTH && 2953 sym.kind != WRONG_MTHS) { 2954 sym = super.access(env, pos, location, sym); 2955 } else { 2956 sym = new DiamondError(sym, currentResolutionContext); 2957 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes); 2958 env.info.pendingResolutionPhase = currentResolutionContext.step; 2959 } 2960 } 2961 return sym; 2962 }}); 2963 } 2964 2965 /** Find the constructor using diamond inference and do some checks(deprecated and preview). 2966 * @param pos The position to use for error reporting. 2967 * @param env The environment current at the constructor invocation. 2968 * @param site The type of class for which a constructor is searched. 2969 * The scope of this class has been touched in attribution. 2970 * @param argtypes The types of the constructor invocation's value arguments. 2971 * @param typeargtypes The types of the constructor invocation's type arguments. 2972 * @param allowBoxing Allow boxing conversions of arguments. 2973 * @param useVarargs Box trailing arguments into an array for varargs. 2974 */ 2975 private Symbol findDiamond(DiagnosticPosition pos, 2976 Env<AttrContext> env, 2977 Type site, 2978 List<Type> argtypes, 2979 List<Type> typeargtypes, 2980 boolean allowBoxing, 2981 boolean useVarargs) { 2982 Symbol sym = findDiamond(env, site, argtypes, typeargtypes, allowBoxing, useVarargs); 2983 chk.checkDeprecated(pos, env.info.scope.owner, sym); 2984 chk.checkPreview(pos, env.info.scope.owner, sym); 2985 return sym; 2986 } 2987 2988 /** This method scans all the constructor symbol in a given class scope - 2989 * assuming that the original scope contains a constructor of the kind: 2990 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo, 2991 * a method check is executed against the modified constructor type: 2992 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond 2993 * inference. The inferred return type of the synthetic constructor IS 2994 * the inferred type for the diamond operator. 2995 */ 2996 private Symbol findDiamond(Env<AttrContext> env, 2997 Type site, 2998 List<Type> argtypes, 2999 List<Type> typeargtypes, 3000 boolean allowBoxing, 3001 boolean useVarargs) { 3002 Symbol bestSoFar = methodNotFound; 3003 TypeSymbol tsym = site.tsym.isInterface() ? syms.objectType.tsym : site.tsym; 3004 for (final Symbol sym : tsym.members().getSymbolsByName(names.init)) { 3005 //- System.out.println(" e " + e.sym); 3006 if (sym.kind == MTH && 3007 (sym.flags_field & SYNTHETIC) == 0) { 3008 List<Type> oldParams = sym.type.hasTag(FORALL) ? 3009 ((ForAll)sym.type).tvars : 3010 List.nil(); 3011 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams), 3012 types.createMethodTypeWithReturn(sym.type.asMethodType(), site)); 3013 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) { 3014 @Override 3015 public Symbol baseSymbol() { 3016 return sym; 3017 } 3018 }; 3019 bestSoFar = selectBest(env, site, argtypes, typeargtypes, 3020 newConstr, 3021 bestSoFar, 3022 allowBoxing, 3023 useVarargs); 3024 } 3025 } 3026 return bestSoFar; 3027 } 3028 3029 Symbol getMemberReference(DiagnosticPosition pos, 3030 Env<AttrContext> env, 3031 JCMemberReference referenceTree, 3032 Type site, 3033 Name name) { 3034 3035 site = types.capture(site); 3036 3037 ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper( 3038 referenceTree, site, name, List.nil(), null, VARARITY); 3039 3040 Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup()); 3041 Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym, 3042 nilMethodCheck, lookupHelper); 3043 3044 env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase; 3045 3046 return sym; 3047 } 3048 3049 ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree, 3050 Type site, 3051 Name name, 3052 List<Type> argtypes, 3053 List<Type> typeargtypes, 3054 MethodResolutionPhase maxPhase) { 3055 if (!name.equals(names.init)) { 3056 //method reference 3057 return new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase); 3058 } else if (site.hasTag(ARRAY)) { 3059 //array constructor reference 3060 return new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase); 3061 } else { 3062 //class constructor reference 3063 return new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase); 3064 } 3065 } 3066 3067 /** 3068 * Resolution of member references is typically done as a single 3069 * overload resolution step, where the argument types A are inferred from 3070 * the target functional descriptor. 3071 * 3072 * If the member reference is a method reference with a type qualifier, 3073 * a two-step lookup process is performed. The first step uses the 3074 * expected argument list A, while the second step discards the first 3075 * type from A (which is treated as a receiver type). 3076 * 3077 * There are two cases in which inference is performed: (i) if the member 3078 * reference is a constructor reference and the qualifier type is raw - in 3079 * which case diamond inference is used to infer a parameterization for the 3080 * type qualifier; (ii) if the member reference is an unbound reference 3081 * where the type qualifier is raw - in that case, during the unbound lookup 3082 * the receiver argument type is used to infer an instantiation for the raw 3083 * qualifier type. 3084 * 3085 * When a multi-step resolution process is exploited, the process of picking 3086 * the resulting symbol is delegated to an helper class {@link com.sun.tools.javac.comp.Resolve.ReferenceChooser}. 3087 * 3088 * This routine returns a pair (T,S), where S is the member reference symbol, 3089 * and T is the type of the class in which S is defined. This is necessary as 3090 * the type T might be dynamically inferred (i.e. if constructor reference 3091 * has a raw qualifier). 3092 */ 3093 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env, 3094 JCMemberReference referenceTree, 3095 Type site, 3096 Name name, 3097 List<Type> argtypes, 3098 List<Type> typeargtypes, 3099 Type descriptor, 3100 MethodCheck methodCheck, 3101 InferenceContext inferenceContext, 3102 ReferenceChooser referenceChooser) { 3103 3104 //step 1 - bound lookup 3105 ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper( 3106 referenceTree, site, name, argtypes, typeargtypes, VARARITY); 3107 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup()); 3108 MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext(); 3109 boundSearchResolveContext.methodCheck = methodCheck; 3110 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), 3111 site.tsym, boundSearchResolveContext, boundLookupHelper); 3112 boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names); 3113 ReferenceLookupResult boundRes = new ReferenceLookupResult(boundSym, boundSearchResolveContext, isStaticSelector); 3114 if (dumpMethodReferenceSearchResults) { 3115 dumpMethodReferenceSearchResults(referenceTree, boundSearchResolveContext, boundSym, true); 3116 } 3117 3118 //step 2 - unbound lookup 3119 Symbol unboundSym = methodNotFound; 3120 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup()); 3121 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext); 3122 ReferenceLookupResult unboundRes = referenceNotFound; 3123 if (unboundLookupHelper != null) { 3124 MethodResolutionContext unboundSearchResolveContext = 3125 new MethodResolutionContext(); 3126 unboundSearchResolveContext.methodCheck = methodCheck; 3127 unboundSym = lookupMethod(unboundEnv, env.tree.pos(), 3128 site.tsym, unboundSearchResolveContext, unboundLookupHelper); 3129 unboundRes = new ReferenceLookupResult(unboundSym, unboundSearchResolveContext, isStaticSelector); 3130 if (dumpMethodReferenceSearchResults) { 3131 dumpMethodReferenceSearchResults(referenceTree, unboundSearchResolveContext, unboundSym, false); 3132 } 3133 } 3134 3135 //merge results 3136 Pair<Symbol, ReferenceLookupHelper> res; 3137 ReferenceLookupResult bestRes = referenceChooser.result(boundRes, unboundRes); 3138 res = new Pair<>(bestRes.sym, 3139 bestRes == unboundRes ? unboundLookupHelper : boundLookupHelper); 3140 env.info.pendingResolutionPhase = bestRes == unboundRes ? 3141 unboundEnv.info.pendingResolutionPhase : 3142 boundEnv.info.pendingResolutionPhase; 3143 3144 if (!res.fst.kind.isResolutionError()) { 3145 //handle sigpoly method references 3146 MethodSymbol msym = (MethodSymbol)res.fst; 3147 if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) { 3148 env.info.pendingResolutionPhase = BASIC; 3149 res = new Pair<>(findPolymorphicSignatureInstance(msym, descriptor), res.snd); 3150 } 3151 } 3152 3153 return res; 3154 } 3155 3156 private void dumpMethodReferenceSearchResults(JCMemberReference referenceTree, 3157 MethodResolutionContext resolutionContext, 3158 Symbol bestSoFar, 3159 boolean bound) { 3160 ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>(); 3161 int pos = 0; 3162 int mostSpecificPos = -1; 3163 for (Candidate c : resolutionContext.candidates) { 3164 if (resolutionContext.step != c.step || !c.isApplicable()) { 3165 continue; 3166 } else { 3167 JCDiagnostic subDiag = null; 3168 if (c.sym.type.hasTag(FORALL)) { 3169 subDiag = diags.fragment(Fragments.PartialInstSig(c.mtype)); 3170 } 3171 3172 String key = subDiag == null ? 3173 "applicable.method.found.2" : 3174 "applicable.method.found.3"; 3175 subDiags.append(diags.fragment(key, pos, 3176 c.sym.isStatic() ? Fragments.Static : Fragments.NonStatic, c.sym, subDiag)); 3177 if (c.sym == bestSoFar) 3178 mostSpecificPos = pos; 3179 pos++; 3180 } 3181 } 3182 JCDiagnostic main = diags.note( 3183 log.currentSource(), 3184 referenceTree, 3185 "method.ref.search.results.multi", 3186 bound ? Fragments.Bound : Fragments.Unbound, 3187 referenceTree.toString(), mostSpecificPos); 3188 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList()); 3189 log.report(d); 3190 } 3191 3192 /** 3193 * This class is used to represent a method reference lookup result. It keeps track of two 3194 * things: (i) the symbol found during a method reference lookup and (ii) the static kind 3195 * of the lookup (see {@link com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind}). 3196 */ 3197 static class ReferenceLookupResult { 3198 3199 /** 3200 * Static kind associated with a method reference lookup. Erroneous lookups end up with 3201 * the UNDEFINED kind; successful lookups will end up with either STATIC, NON_STATIC, 3202 * depending on whether all applicable candidates are static or non-static methods, 3203 * respectively. If a successful lookup has both static and non-static applicable methods, 3204 * its kind is set to BOTH. 3205 */ 3206 enum StaticKind { 3207 STATIC, 3208 NON_STATIC, 3209 BOTH, 3210 UNDEFINED; 3211 3212 /** 3213 * Retrieve the static kind associated with a given (method) symbol. 3214 */ 3215 static StaticKind from(Symbol s) { 3216 return s.isStatic() ? 3217 STATIC : NON_STATIC; 3218 } 3219 3220 /** 3221 * Merge two static kinds together. 3222 */ 3223 static StaticKind reduce(StaticKind sk1, StaticKind sk2) { 3224 if (sk1 == UNDEFINED) { 3225 return sk2; 3226 } else if (sk2 == UNDEFINED) { 3227 return sk1; 3228 } else { 3229 return sk1 == sk2 ? sk1 : BOTH; 3230 } 3231 } 3232 } 3233 3234 /** The static kind. */ 3235 StaticKind staticKind; 3236 3237 /** The lookup result. */ 3238 Symbol sym; 3239 3240 ReferenceLookupResult(Symbol sym, MethodResolutionContext resolutionContext, boolean isStaticSelector) { 3241 this(sym, staticKind(sym, resolutionContext, isStaticSelector)); 3242 } 3243 3244 private ReferenceLookupResult(Symbol sym, StaticKind staticKind) { 3245 this.staticKind = staticKind; 3246 this.sym = sym; 3247 } 3248 3249 private static StaticKind staticKind(Symbol sym, MethodResolutionContext resolutionContext, boolean isStaticSelector) { 3250 if (sym.kind == MTH && !isStaticSelector) { 3251 return StaticKind.from(sym); 3252 } else if (sym.kind == MTH || sym.kind == AMBIGUOUS) { 3253 return resolutionContext.candidates.stream() 3254 .filter(c -> c.isApplicable() && c.step == resolutionContext.step) 3255 .map(c -> StaticKind.from(c.sym)) 3256 .reduce(StaticKind::reduce) 3257 .orElse(StaticKind.UNDEFINED); 3258 } else { 3259 return StaticKind.UNDEFINED; 3260 } 3261 } 3262 3263 /** 3264 * Does this result corresponds to a successful lookup (i.e. one where a method has been found?) 3265 */ 3266 boolean isSuccess() { 3267 return staticKind != StaticKind.UNDEFINED; 3268 } 3269 3270 /** 3271 * Does this result have given static kind? 3272 */ 3273 boolean hasKind(StaticKind sk) { 3274 return this.staticKind == sk; 3275 } 3276 3277 /** 3278 * Error recovery helper: can this lookup result be ignored (for the purpose of returning 3279 * some 'better' result) ? 3280 */ 3281 boolean canIgnore() { 3282 switch (sym.kind) { 3283 case ABSENT_MTH: 3284 return true; 3285 case WRONG_MTH: 3286 InapplicableSymbolError errSym = 3287 (InapplicableSymbolError)sym.baseSymbol(); 3288 return new Template(MethodCheckDiag.ARITY_MISMATCH.regex()) 3289 .matches(errSym.errCandidate().snd); 3290 case WRONG_MTHS: 3291 InapplicableSymbolsError errSyms = 3292 (InapplicableSymbolsError)sym.baseSymbol(); 3293 return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty(); 3294 default: 3295 return false; 3296 } 3297 } 3298 3299 static ReferenceLookupResult error(Symbol sym) { 3300 return new ReferenceLookupResult(sym, StaticKind.UNDEFINED); 3301 } 3302 } 3303 3304 /** 3305 * This abstract class embodies the logic that converts one (bound lookup) or two (unbound lookup) 3306 * {@code ReferenceLookupResult} objects into a {@code Symbol}, which is then regarded as the 3307 * result of method reference resolution. 3308 */ 3309 abstract class ReferenceChooser { 3310 /** 3311 * Generate a result from a pair of lookup result objects. This method delegates to the 3312 * appropriate result generation routine. 3313 */ 3314 ReferenceLookupResult result(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 3315 return unboundRes != referenceNotFound ? 3316 unboundResult(boundRes, unboundRes) : 3317 boundResult(boundRes); 3318 } 3319 3320 /** 3321 * Generate a symbol from a given bound lookup result. 3322 */ 3323 abstract ReferenceLookupResult boundResult(ReferenceLookupResult boundRes); 3324 3325 /** 3326 * Generate a symbol from a pair of bound/unbound lookup results. 3327 */ 3328 abstract ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes); 3329 } 3330 3331 /** 3332 * This chooser implements the selection strategy used during a full lookup; this logic 3333 * is described in JLS SE 8 (15.3.2). 3334 */ 3335 ReferenceChooser basicReferenceChooser = new ReferenceChooser() { 3336 3337 @Override 3338 ReferenceLookupResult boundResult(ReferenceLookupResult boundRes) { 3339 return !boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC) ? 3340 boundRes : //the search produces a non-static method 3341 ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.sym, false)); 3342 } 3343 3344 @Override 3345 ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 3346 if (boundRes.isSuccess() && boundRes.sym.isStatic() && 3347 (!unboundRes.isSuccess() || unboundRes.hasKind(StaticKind.STATIC))) { 3348 //the first search produces a static method and no non-static method is applicable 3349 //during the second search 3350 return boundRes; 3351 } else if (unboundRes.isSuccess() && !unboundRes.sym.isStatic() && 3352 (!boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC))) { 3353 //the second search produces a non-static method and no static method is applicable 3354 //during the first search 3355 return unboundRes; 3356 } else if (boundRes.isSuccess() && unboundRes.isSuccess()) { 3357 //both searches produce some result; ambiguity (error recovery) 3358 return ReferenceLookupResult.error(ambiguityError(boundRes.sym, unboundRes.sym)); 3359 } else if (boundRes.isSuccess() || unboundRes.isSuccess()) { 3360 //Both searches failed to produce a result with correct staticness (i.e. first search 3361 //produces an non-static method). Alternatively, a given search produced a result 3362 //with the right staticness, but the other search has applicable methods with wrong 3363 //staticness (error recovery) 3364 return ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.isSuccess() ? 3365 boundRes.sym : unboundRes.sym, true)); 3366 } else { 3367 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery) 3368 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ? 3369 unboundRes : boundRes; 3370 } 3371 } 3372 }; 3373 3374 /** 3375 * This chooser implements the selection strategy used during an arity-based lookup; this logic 3376 * is described in JLS SE 8 (15.12.2.1). 3377 */ 3378 ReferenceChooser structuralReferenceChooser = new ReferenceChooser() { 3379 3380 @Override 3381 ReferenceLookupResult boundResult(ReferenceLookupResult boundRes) { 3382 return (!boundRes.isSuccess() || !boundRes.hasKind(StaticKind.STATIC)) ? 3383 boundRes : //the search has at least one applicable non-static method 3384 ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.sym, false)); 3385 } 3386 3387 @Override 3388 ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 3389 if (boundRes.isSuccess() && !boundRes.hasKind(StaticKind.NON_STATIC)) { 3390 //the first search has at least one applicable static method 3391 return boundRes; 3392 } else if (unboundRes.isSuccess() && !unboundRes.hasKind(StaticKind.STATIC)) { 3393 //the second search has at least one applicable non-static method 3394 return unboundRes; 3395 } else if (boundRes.isSuccess() || unboundRes.isSuccess()) { 3396 //either the first search produces a non-static method, or second search produces 3397 //a non-static method (error recovery) 3398 return ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.isSuccess() ? 3399 boundRes.sym : unboundRes.sym, true)); 3400 } else { 3401 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery) 3402 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ? 3403 unboundRes : boundRes; 3404 } 3405 } 3406 }; 3407 3408 /** 3409 * Helper for defining custom method-like lookup logic; a lookup helper 3410 * provides hooks for (i) the actual lookup logic and (ii) accessing the 3411 * lookup result (this step might result in compiler diagnostics to be generated) 3412 */ 3413 abstract class LookupHelper { 3414 3415 /** name of the symbol to lookup */ 3416 Name name; 3417 3418 /** location in which the lookup takes place */ 3419 Type site; 3420 3421 /** actual types used during the lookup */ 3422 List<Type> argtypes; 3423 3424 /** type arguments used during the lookup */ 3425 List<Type> typeargtypes; 3426 3427 /** Max overload resolution phase handled by this helper */ 3428 MethodResolutionPhase maxPhase; 3429 3430 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3431 this.name = name; 3432 this.site = site; 3433 this.argtypes = argtypes; 3434 this.typeargtypes = typeargtypes; 3435 this.maxPhase = maxPhase; 3436 } 3437 3438 /** 3439 * Should lookup stop at given phase with given result 3440 */ 3441 final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) { 3442 return phase.ordinal() > maxPhase.ordinal() || 3443 !sym.kind.isResolutionError() || sym.kind == AMBIGUOUS || sym.kind == STATICERR; 3444 } 3445 3446 /** 3447 * Search for a symbol under a given overload resolution phase - this method 3448 * is usually called several times, once per each overload resolution phase 3449 */ 3450 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase); 3451 3452 /** 3453 * Dump overload resolution info 3454 */ 3455 void debug(DiagnosticPosition pos, Symbol sym) { 3456 //do nothing 3457 } 3458 3459 /** 3460 * Validate the result of the lookup 3461 */ 3462 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym); 3463 } 3464 3465 abstract class BasicLookupHelper extends LookupHelper { 3466 3467 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) { 3468 this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY); 3469 } 3470 3471 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3472 super(name, site, argtypes, typeargtypes, maxPhase); 3473 } 3474 3475 @Override 3476 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3477 Symbol sym = doLookup(env, phase); 3478 if (sym.kind == AMBIGUOUS) { 3479 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol(); 3480 sym = a_err.mergeAbstracts(site); 3481 } 3482 return sym; 3483 } 3484 3485 abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase); 3486 3487 @Override 3488 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 3489 if (sym.kind.isResolutionError()) { 3490 //if nothing is found return the 'first' error 3491 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes); 3492 } 3493 return sym; 3494 } 3495 3496 @Override 3497 void debug(DiagnosticPosition pos, Symbol sym) { 3498 reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym); 3499 } 3500 } 3501 3502 /** 3503 * Helper class for member reference lookup. A reference lookup helper 3504 * defines the basic logic for member reference lookup; a method gives 3505 * access to an 'unbound' helper used to perform an unbound member 3506 * reference lookup. 3507 */ 3508 abstract class ReferenceLookupHelper extends LookupHelper { 3509 3510 /** The member reference tree */ 3511 JCMemberReference referenceTree; 3512 3513 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3514 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3515 super(name, site, argtypes, typeargtypes, maxPhase); 3516 this.referenceTree = referenceTree; 3517 } 3518 3519 /** 3520 * Returns an unbound version of this lookup helper. By default, this 3521 * method returns an dummy lookup helper. 3522 */ 3523 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3524 return null; 3525 } 3526 3527 /** 3528 * Get the kind of the member reference 3529 */ 3530 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym); 3531 3532 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 3533 if (sym.kind == AMBIGUOUS) { 3534 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol(); 3535 sym = a_err.mergeAbstracts(site); 3536 } 3537 //skip error reporting 3538 return sym; 3539 } 3540 } 3541 3542 /** 3543 * Helper class for method reference lookup. The lookup logic is based 3544 * upon Resolve.findMethod; in certain cases, this helper class has a 3545 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper). 3546 * In such cases, non-static lookup results are thrown away. 3547 */ 3548 class MethodReferenceLookupHelper extends ReferenceLookupHelper { 3549 3550 /** The original method reference lookup site. */ 3551 Type originalSite; 3552 3553 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3554 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3555 super(referenceTree, name, types.skipTypeVars(site, true), argtypes, typeargtypes, maxPhase); 3556 this.originalSite = site; 3557 } 3558 3559 @Override 3560 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3561 return findMethod(env, site, name, argtypes, typeargtypes, 3562 phase.isBoxingRequired(), phase.isVarargsRequired()); 3563 } 3564 3565 @Override 3566 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3567 if (TreeInfo.isStaticSelector(referenceTree.expr, names)) { 3568 if (argtypes.nonEmpty() && 3569 (argtypes.head.hasTag(NONE) || 3570 types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), originalSite))) { 3571 return new UnboundMethodReferenceLookupHelper(referenceTree, name, 3572 originalSite, argtypes, typeargtypes, maxPhase); 3573 } else { 3574 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) { 3575 @Override 3576 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3577 return this; 3578 } 3579 3580 @Override 3581 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3582 return methodNotFound; 3583 } 3584 3585 @Override 3586 ReferenceKind referenceKind(Symbol sym) { 3587 Assert.error(); 3588 return null; 3589 } 3590 }; 3591 } 3592 } else { 3593 return super.unboundLookup(inferenceContext); 3594 } 3595 } 3596 3597 @Override 3598 ReferenceKind referenceKind(Symbol sym) { 3599 if (sym.isStatic()) { 3600 return ReferenceKind.STATIC; 3601 } else { 3602 Name selName = TreeInfo.name(referenceTree.getQualifierExpression()); 3603 return selName != null && selName == names._super ? 3604 ReferenceKind.SUPER : 3605 ReferenceKind.BOUND; 3606 } 3607 } 3608 } 3609 3610 /** 3611 * Helper class for unbound method reference lookup. Essentially the same 3612 * as the basic method reference lookup helper; main difference is that static 3613 * lookup results are thrown away. If qualifier type is raw, an attempt to 3614 * infer a parameterized type is made using the first actual argument (that 3615 * would otherwise be ignored during the lookup). 3616 */ 3617 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper { 3618 3619 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3620 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3621 super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase); 3622 if (site.isRaw() && !argtypes.head.hasTag(NONE)) { 3623 Type asSuperSite = types.asSuper(argtypes.head, site.tsym); 3624 this.site = types.skipTypeVars(asSuperSite, true); 3625 } 3626 } 3627 3628 @Override 3629 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3630 return this; 3631 } 3632 3633 @Override 3634 ReferenceKind referenceKind(Symbol sym) { 3635 return ReferenceKind.UNBOUND; 3636 } 3637 } 3638 3639 /** 3640 * Helper class for array constructor lookup; an array constructor lookup 3641 * is simulated by looking up a method that returns the array type specified 3642 * as qualifier, and that accepts a single int parameter (size of the array). 3643 */ 3644 class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper { 3645 3646 ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes, 3647 List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3648 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase); 3649 } 3650 3651 @Override 3652 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3653 WriteableScope sc = WriteableScope.create(syms.arrayClass); 3654 MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym); 3655 arrayConstr.type = new MethodType(List.of(syms.intType), site, List.nil(), syms.methodClass); 3656 sc.enter(arrayConstr); 3657 return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false); 3658 } 3659 3660 @Override 3661 ReferenceKind referenceKind(Symbol sym) { 3662 return ReferenceKind.ARRAY_CTOR; 3663 } 3664 } 3665 3666 /** 3667 * Helper class for constructor reference lookup. The lookup logic is based 3668 * upon either Resolve.findMethod or Resolve.findDiamond - depending on 3669 * whether the constructor reference needs diamond inference (this is the case 3670 * if the qualifier type is raw). A special erroneous symbol is returned 3671 * if the lookup returns the constructor of an inner class and there's no 3672 * enclosing instance in scope. 3673 */ 3674 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper { 3675 3676 boolean needsInference; 3677 3678 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes, 3679 List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3680 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase); 3681 if (site.isRaw()) { 3682 this.site = new ClassType(site.getEnclosingType(), 3683 !(site.tsym.isInner() && site.getEnclosingType().isRaw()) ? 3684 site.tsym.type.getTypeArguments() : List.nil(), site.tsym, site.getMetadata()); 3685 needsInference = true; 3686 } 3687 } 3688 3689 @Override 3690 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3691 Symbol sym = needsInference ? 3692 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) : 3693 findMethod(env, site, name, argtypes, typeargtypes, 3694 phase.isBoxingRequired(), phase.isVarargsRequired()); 3695 return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym; 3696 } 3697 3698 @Override 3699 ReferenceKind referenceKind(Symbol sym) { 3700 return site.getEnclosingType().hasTag(NONE) ? 3701 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER; 3702 } 3703 } 3704 3705 /** 3706 * Main overload resolution routine. On each overload resolution step, a 3707 * lookup helper class is used to perform the method/constructor lookup; 3708 * at the end of the lookup, the helper is used to validate the results 3709 * (this last step might trigger overload resolution diagnostics). 3710 */ 3711 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) { 3712 MethodResolutionContext resolveContext = new MethodResolutionContext(); 3713 resolveContext.methodCheck = methodCheck; 3714 return lookupMethod(env, pos, location, resolveContext, lookupHelper); 3715 } 3716 3717 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, 3718 MethodResolutionContext resolveContext, LookupHelper lookupHelper) { 3719 MethodResolutionContext prevResolutionContext = currentResolutionContext; 3720 try { 3721 Symbol bestSoFar = methodNotFound; 3722 currentResolutionContext = resolveContext; 3723 for (MethodResolutionPhase phase : methodResolutionSteps) { 3724 if (lookupHelper.shouldStop(bestSoFar, phase)) 3725 break; 3726 MethodResolutionPhase prevPhase = currentResolutionContext.step; 3727 Symbol prevBest = bestSoFar; 3728 currentResolutionContext.step = phase; 3729 Symbol sym = lookupHelper.lookup(env, phase); 3730 lookupHelper.debug(pos, sym); 3731 bestSoFar = phase.mergeResults(bestSoFar, sym); 3732 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase; 3733 } 3734 return lookupHelper.access(env, pos, location, bestSoFar); 3735 } finally { 3736 currentResolutionContext = prevResolutionContext; 3737 } 3738 } 3739 3740 /** 3741 * Resolve `c.name' where name == this or name == super. 3742 * @param pos The position to use for error reporting. 3743 * @param env The environment current at the expression. 3744 * @param c The qualifier. 3745 * @param name The identifier's name. 3746 */ 3747 Symbol resolveSelf(DiagnosticPosition pos, 3748 Env<AttrContext> env, 3749 TypeSymbol c, 3750 Name name) { 3751 Env<AttrContext> env1 = env; 3752 boolean staticOnly = false; 3753 while (env1.outer != null) { 3754 if (isStatic(env1)) staticOnly = true; 3755 if (env1.enclClass.sym == c) { 3756 Symbol sym = env1.info.scope.findFirst(name); 3757 if (sym != null) { 3758 if (staticOnly) sym = new StaticError(sym); 3759 return accessBase(sym, pos, env.enclClass.sym.type, 3760 name, true); 3761 } 3762 } 3763 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 3764 env1 = env1.outer; 3765 } 3766 if (c.isInterface() && 3767 name == names._super && !isStatic(env) && 3768 types.isDirectSuperInterface(c, env.enclClass.sym)) { 3769 //this might be a default super call if one of the superinterfaces is 'c' 3770 for (Type t : pruneInterfaces(env.enclClass.type)) { 3771 if (t.tsym == c) { 3772 env.info.defaultSuperCallSite = t; 3773 return new VarSymbol(0, names._super, 3774 types.asSuper(env.enclClass.type, c), env.enclClass.sym); 3775 } 3776 } 3777 //find a direct supertype that is a subtype of 'c' 3778 for (Type i : types.directSupertypes(env.enclClass.type)) { 3779 if (i.tsym.isSubClass(c, types) && i.tsym != c) { 3780 log.error(pos, 3781 Errors.IllegalDefaultSuperCall(c, 3782 Fragments.RedundantSupertype(c, i))); 3783 return syms.errSymbol; 3784 } 3785 } 3786 Assert.error(); 3787 } 3788 log.error(pos, Errors.NotEnclClass(c)); 3789 return syms.errSymbol; 3790 } 3791 //where 3792 private List<Type> pruneInterfaces(Type t) { 3793 ListBuffer<Type> result = new ListBuffer<>(); 3794 for (Type t1 : types.interfaces(t)) { 3795 boolean shouldAdd = true; 3796 for (Type t2 : types.directSupertypes(t)) { 3797 if (t1 != t2 && !t2.hasTag(ERROR) && types.isSubtypeNoCapture(t2, t1)) { 3798 shouldAdd = false; 3799 } 3800 } 3801 if (shouldAdd) { 3802 result.append(t1); 3803 } 3804 } 3805 return result.toList(); 3806 } 3807 3808 3809 /** 3810 * Resolve `c.this' for an enclosing class c that contains the 3811 * named member. 3812 * @param pos The position to use for error reporting. 3813 * @param env The environment current at the expression. 3814 * @param member The member that must be contained in the result. 3815 */ 3816 Symbol resolveSelfContaining(DiagnosticPosition pos, 3817 Env<AttrContext> env, 3818 Symbol member, 3819 boolean isSuperCall) { 3820 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall); 3821 if (sym == null) { 3822 log.error(pos, Errors.EnclClassRequired(member)); 3823 return syms.errSymbol; 3824 } else { 3825 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true); 3826 } 3827 } 3828 3829 boolean enclosingInstanceMissing(Env<AttrContext> env, Type type) { 3830 if (type.hasTag(CLASS) && type.getEnclosingType().hasTag(CLASS)) { 3831 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false); 3832 return encl == null || encl.kind.isResolutionError(); 3833 } 3834 return false; 3835 } 3836 3837 private Symbol resolveSelfContainingInternal(Env<AttrContext> env, 3838 Symbol member, 3839 boolean isSuperCall) { 3840 Name name = names._this; 3841 Env<AttrContext> env1 = isSuperCall ? env.outer : env; 3842 boolean staticOnly = false; 3843 if (env1 != null) { 3844 while (env1 != null && env1.outer != null) { 3845 if (isStatic(env1)) staticOnly = true; 3846 if (env1.enclClass.sym.isSubClass(member.owner.enclClass(), types)) { 3847 Symbol sym = env1.info.scope.findFirst(name); 3848 if (sym != null) { 3849 if (staticOnly) sym = new StaticError(sym); 3850 return sym; 3851 } 3852 } 3853 if ((env1.enclClass.sym.flags() & STATIC) != 0) 3854 staticOnly = true; 3855 env1 = env1.outer; 3856 } 3857 } 3858 return null; 3859 } 3860 3861 /** 3862 * Resolve an appropriate implicit this instance for t's container. 3863 * JLS 8.8.5.1 and 15.9.2 3864 */ 3865 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) { 3866 return resolveImplicitThis(pos, env, t, false); 3867 } 3868 3869 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) { 3870 Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH) 3871 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this) 3872 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type; 3873 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym) { 3874 log.error(pos, Errors.CantRefBeforeCtorCalled("this")); 3875 } 3876 return thisType; 3877 } 3878 3879 /* *************************************************************************** 3880 * ResolveError classes, indicating error situations when accessing symbols 3881 ****************************************************************************/ 3882 3883 //used by TransTypes when checking target type of synthetic cast 3884 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) { 3885 AccessError error = new AccessError(env, env.enclClass.type, type.tsym); 3886 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null); 3887 } 3888 //where 3889 private void logResolveError(ResolveError error, 3890 DiagnosticPosition pos, 3891 Symbol location, 3892 Type site, 3893 Name name, 3894 List<Type> argtypes, 3895 List<Type> typeargtypes) { 3896 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 3897 pos, location, site, name, argtypes, typeargtypes); 3898 if (d != null) { 3899 d.setFlag(DiagnosticFlag.RESOLVE_ERROR); 3900 log.report(d); 3901 } 3902 } 3903 3904 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args"); 3905 3906 public Object methodArguments(List<Type> argtypes) { 3907 if (argtypes == null || argtypes.isEmpty()) { 3908 return noArgs; 3909 } else { 3910 ListBuffer<Object> diagArgs = new ListBuffer<>(); 3911 for (Type t : argtypes) { 3912 if (t.hasTag(DEFERRED)) { 3913 diagArgs.append(((DeferredAttr.DeferredType)t).tree); 3914 } else { 3915 diagArgs.append(t); 3916 } 3917 } 3918 return diagArgs; 3919 } 3920 } 3921 3922 /** check if a type is a subtype of Serializable, if that is available.*/ 3923 boolean isSerializable(Type t) { 3924 try { 3925 syms.serializableType.complete(); 3926 } 3927 catch (CompletionFailure e) { 3928 return false; 3929 } 3930 return types.isSubtype(t, syms.serializableType); 3931 } 3932 3933 /** 3934 * Root class for resolution errors. Subclass of ResolveError 3935 * represent a different kinds of resolution error - as such they must 3936 * specify how they map into concrete compiler diagnostics. 3937 */ 3938 abstract class ResolveError extends Symbol { 3939 3940 /** The name of the kind of error, for debugging only. */ 3941 final String debugName; 3942 3943 ResolveError(Kind kind, String debugName) { 3944 super(kind, 0, null, null, null); 3945 this.debugName = debugName; 3946 } 3947 3948 @Override @DefinedBy(Api.LANGUAGE_MODEL) 3949 public <R, P> R accept(ElementVisitor<R, P> v, P p) { 3950 throw new AssertionError(); 3951 } 3952 3953 @Override 3954 public String toString() { 3955 return debugName; 3956 } 3957 3958 @Override 3959 public boolean exists() { 3960 return false; 3961 } 3962 3963 @Override 3964 public boolean isStatic() { 3965 return false; 3966 } 3967 3968 /** 3969 * Create an external representation for this erroneous symbol to be 3970 * used during attribution - by default this returns the symbol of a 3971 * brand new error type which stores the original type found 3972 * during resolution. 3973 * 3974 * @param name the name used during resolution 3975 * @param location the location from which the symbol is accessed 3976 */ 3977 protected Symbol access(Name name, TypeSymbol location) { 3978 return types.createErrorType(name, location, syms.errSymbol.type).tsym; 3979 } 3980 3981 /** 3982 * Create a diagnostic representing this resolution error. 3983 * 3984 * @param dkind The kind of the diagnostic to be created (e.g error). 3985 * @param pos The position to be used for error reporting. 3986 * @param site The original type from where the selection took place. 3987 * @param name The name of the symbol to be resolved. 3988 * @param argtypes The invocation's value arguments, 3989 * if we looked for a method. 3990 * @param typeargtypes The invocation's type arguments, 3991 * if we looked for a method. 3992 */ 3993 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3994 DiagnosticPosition pos, 3995 Symbol location, 3996 Type site, 3997 Name name, 3998 List<Type> argtypes, 3999 List<Type> typeargtypes); 4000 } 4001 4002 /** 4003 * This class is the root class of all resolution errors caused by 4004 * an invalid symbol being found during resolution. 4005 */ 4006 abstract class InvalidSymbolError extends ResolveError { 4007 4008 /** The invalid symbol found during resolution */ 4009 Symbol sym; 4010 4011 InvalidSymbolError(Kind kind, Symbol sym, String debugName) { 4012 super(kind, debugName); 4013 this.sym = sym; 4014 } 4015 4016 @Override 4017 public boolean exists() { 4018 return true; 4019 } 4020 4021 @Override 4022 public String toString() { 4023 return super.toString() + " wrongSym=" + sym; 4024 } 4025 4026 @Override 4027 public Symbol access(Name name, TypeSymbol location) { 4028 if (!sym.kind.isResolutionError() && sym.kind.matches(KindSelector.TYP)) 4029 return types.createErrorType(name, location, sym.type).tsym; 4030 else 4031 return sym; 4032 } 4033 } 4034 4035 class BadRestrictedTypeError extends ResolveError { 4036 private final Name typeName; 4037 BadRestrictedTypeError(Name typeName) { 4038 super(Kind.BAD_RESTRICTED_TYPE, "bad var use"); 4039 this.typeName = typeName; 4040 } 4041 4042 @Override 4043 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4044 return diags.create(dkind, log.currentSource(), pos, "illegal.ref.to.restricted.type", typeName); 4045 } 4046 } 4047 4048 /** 4049 * InvalidSymbolError error class indicating that a symbol matching a 4050 * given name does not exists in a given site. 4051 */ 4052 class SymbolNotFoundError extends ResolveError { 4053 4054 SymbolNotFoundError(Kind kind) { 4055 this(kind, "symbol not found error"); 4056 } 4057 4058 SymbolNotFoundError(Kind kind, String debugName) { 4059 super(kind, debugName); 4060 } 4061 4062 @Override 4063 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4064 DiagnosticPosition pos, 4065 Symbol location, 4066 Type site, 4067 Name name, 4068 List<Type> argtypes, 4069 List<Type> typeargtypes) { 4070 argtypes = argtypes == null ? List.nil() : argtypes; 4071 typeargtypes = typeargtypes == null ? List.nil() : typeargtypes; 4072 if (name == names.error) 4073 return null; 4074 4075 boolean hasLocation = false; 4076 if (location == null) { 4077 location = site.tsym; 4078 } 4079 if (!location.name.isEmpty()) { 4080 if (location.kind == PCK && !site.tsym.exists() && location.name != names.java) { 4081 return diags.create(dkind, log.currentSource(), pos, 4082 "doesnt.exist", location); 4083 } 4084 hasLocation = !location.name.equals(names._this) && 4085 !location.name.equals(names._super); 4086 } 4087 boolean isConstructor = name == names.init; 4088 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind(); 4089 Name idname = isConstructor ? site.tsym.name : name; 4090 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation); 4091 if (hasLocation) { 4092 return diags.create(dkind, log.currentSource(), pos, 4093 errKey, kindname, idname, //symbol kindname, name 4094 typeargtypes, args(argtypes), //type parameters and arguments (if any) 4095 getLocationDiag(location, site)); //location kindname, type 4096 } 4097 else { 4098 return diags.create(dkind, log.currentSource(), pos, 4099 errKey, kindname, idname, //symbol kindname, name 4100 typeargtypes, args(argtypes)); //type parameters and arguments (if any) 4101 } 4102 } 4103 //where 4104 private Object args(List<Type> args) { 4105 return args.isEmpty() ? args : methodArguments(args); 4106 } 4107 4108 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) { 4109 String key = "cant.resolve"; 4110 String suffix = hasLocation ? ".location" : ""; 4111 switch (kindname) { 4112 case METHOD: 4113 case CONSTRUCTOR: { 4114 suffix += ".args"; 4115 suffix += hasTypeArgs ? ".params" : ""; 4116 } 4117 } 4118 return key + suffix; 4119 } 4120 private JCDiagnostic getLocationDiag(Symbol location, Type site) { 4121 if (location.kind == VAR) { 4122 return diags.fragment(Fragments.Location1(kindName(location), 4123 location, 4124 location.type)); 4125 } else { 4126 return diags.fragment(Fragments.Location(typeKindName(site), 4127 site, 4128 null)); 4129 } 4130 } 4131 } 4132 4133 /** 4134 * InvalidSymbolError error class indicating that a given symbol 4135 * (either a method, a constructor or an operand) is not applicable 4136 * given an actual arguments/type argument list. 4137 */ 4138 class InapplicableSymbolError extends ResolveError { 4139 4140 protected MethodResolutionContext resolveContext; 4141 4142 InapplicableSymbolError(MethodResolutionContext context) { 4143 this(WRONG_MTH, "inapplicable symbol error", context); 4144 } 4145 4146 protected InapplicableSymbolError(Kind kind, String debugName, MethodResolutionContext context) { 4147 super(kind, debugName); 4148 this.resolveContext = context; 4149 } 4150 4151 @Override 4152 public String toString() { 4153 return super.toString(); 4154 } 4155 4156 @Override 4157 public boolean exists() { 4158 return true; 4159 } 4160 4161 @Override 4162 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4163 DiagnosticPosition pos, 4164 Symbol location, 4165 Type site, 4166 Name name, 4167 List<Type> argtypes, 4168 List<Type> typeargtypes) { 4169 if (name == names.error) 4170 return null; 4171 4172 Pair<Symbol, JCDiagnostic> c = errCandidate(); 4173 Symbol ws = c.fst.asMemberOf(site, types); 4174 UnaryOperator<JCDiagnostic> rewriter = compactMethodDiags ? 4175 d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null; 4176 4177 // If the problem is due to type arguments, then the method parameters aren't relevant, 4178 // so use the error message that omits them to avoid confusion. 4179 switch (c.snd.getCode()) { 4180 case "compiler.misc.wrong.number.type.args": 4181 case "compiler.misc.explicit.param.do.not.conform.to.bounds": 4182 return diags.create(dkind, log.currentSource(), pos, 4183 "cant.apply.symbol.noargs", 4184 rewriter, 4185 kindName(ws), 4186 ws.name == names.init ? ws.owner.name : ws.name, 4187 kindName(ws.owner), 4188 ws.owner.type, 4189 c.snd); 4190 default: 4191 // Avoid saying "constructor Array in class Array" 4192 if (ws.owner == syms.arrayClass && ws.name == names.init) { 4193 return diags.create(dkind, log.currentSource(), pos, 4194 "cant.apply.array.ctor", 4195 rewriter, 4196 methodArguments(ws.type.getParameterTypes()), 4197 methodArguments(argtypes), 4198 c.snd); 4199 } 4200 return diags.create(dkind, log.currentSource(), pos, 4201 "cant.apply.symbol", 4202 rewriter, 4203 kindName(ws), 4204 ws.name == names.init ? ws.owner.name : ws.name, 4205 methodArguments(ws.type.getParameterTypes()), 4206 methodArguments(argtypes), 4207 kindName(ws.owner), 4208 ws.owner.type, 4209 c.snd); 4210 } 4211 } 4212 4213 @Override 4214 public Symbol access(Name name, TypeSymbol location) { 4215 Pair<Symbol, JCDiagnostic> cand = errCandidate(); 4216 TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym; 4217 if (cand != null) { 4218 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd); 4219 } 4220 return errSymbol; 4221 } 4222 4223 protected Pair<Symbol, JCDiagnostic> errCandidate() { 4224 Candidate bestSoFar = null; 4225 for (Candidate c : resolveContext.candidates) { 4226 if (c.isApplicable()) continue; 4227 bestSoFar = c; 4228 } 4229 Assert.checkNonNull(bestSoFar); 4230 return new Pair<>(bestSoFar.sym, bestSoFar.details); 4231 } 4232 } 4233 4234 /** 4235 * ResolveError error class indicating that a symbol (either methods, constructors or operand) 4236 * is not applicable given an actual arguments/type argument list. 4237 */ 4238 class InapplicableSymbolsError extends InapplicableSymbolError { 4239 4240 InapplicableSymbolsError(MethodResolutionContext context) { 4241 super(WRONG_MTHS, "inapplicable symbols", context); 4242 } 4243 4244 @Override 4245 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4246 DiagnosticPosition pos, 4247 Symbol location, 4248 Type site, 4249 Name name, 4250 List<Type> argtypes, 4251 List<Type> typeargtypes) { 4252 Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates(); 4253 Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ? 4254 filterCandidates(candidatesMap) : 4255 mapCandidates(); 4256 if (filteredCandidates.isEmpty()) { 4257 filteredCandidates = candidatesMap; 4258 } 4259 boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size(); 4260 if (filteredCandidates.size() > 1) { 4261 JCDiagnostic err = diags.create(dkind, 4262 null, 4263 truncatedDiag ? 4264 EnumSet.of(DiagnosticFlag.COMPRESSED) : 4265 EnumSet.noneOf(DiagnosticFlag.class), 4266 log.currentSource(), 4267 pos, 4268 "cant.apply.symbols", 4269 name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(), 4270 name == names.init ? site.tsym.name : name, 4271 methodArguments(argtypes)); 4272 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site)); 4273 } else if (filteredCandidates.size() == 1) { 4274 Map.Entry<Symbol, JCDiagnostic> _e = 4275 filteredCandidates.entrySet().iterator().next(); 4276 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue()); 4277 JCDiagnostic d = new InapplicableSymbolError(resolveContext) { 4278 @Override 4279 protected Pair<Symbol, JCDiagnostic> errCandidate() { 4280 return p; 4281 } 4282 }.getDiagnostic(dkind, pos, 4283 location, site, name, argtypes, typeargtypes); 4284 if (truncatedDiag) { 4285 d.setFlag(DiagnosticFlag.COMPRESSED); 4286 } 4287 return d; 4288 } else { 4289 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos, 4290 location, site, name, argtypes, typeargtypes); 4291 } 4292 } 4293 //where 4294 private Map<Symbol, JCDiagnostic> mapCandidates() { 4295 MostSpecificMap candidates = new MostSpecificMap(); 4296 for (Candidate c : resolveContext.candidates) { 4297 if (c.isApplicable()) continue; 4298 candidates.put(c); 4299 } 4300 return candidates; 4301 } 4302 4303 @SuppressWarnings("serial") 4304 private class MostSpecificMap extends LinkedHashMap<Symbol, JCDiagnostic> { 4305 private void put(Candidate c) { 4306 ListBuffer<Symbol> overridden = new ListBuffer<>(); 4307 for (Symbol s : keySet()) { 4308 if (s == c.sym) { 4309 continue; 4310 } 4311 if (c.sym.overrides(s, (TypeSymbol)s.owner, types, false)) { 4312 overridden.add(s); 4313 } else if (s.overrides(c.sym, (TypeSymbol)c.sym.owner, types, false)) { 4314 return; 4315 } 4316 } 4317 for (Symbol s : overridden) { 4318 remove(s); 4319 } 4320 put(c.sym, c.details); 4321 } 4322 } 4323 4324 Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) { 4325 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>(); 4326 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) { 4327 JCDiagnostic d = _entry.getValue(); 4328 if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) { 4329 candidates.put(_entry.getKey(), d); 4330 } 4331 } 4332 return candidates; 4333 } 4334 4335 private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) { 4336 List<JCDiagnostic> details = List.nil(); 4337 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) { 4338 Symbol sym = _entry.getKey(); 4339 JCDiagnostic detailDiag = 4340 diags.fragment(Fragments.InapplicableMethod(Kinds.kindName(sym), 4341 sym.location(site, types), 4342 sym.asMemberOf(site, types), 4343 _entry.getValue())); 4344 details = details.prepend(detailDiag); 4345 } 4346 //typically members are visited in reverse order (see Scope) 4347 //so we need to reverse the candidate list so that candidates 4348 //conform to source order 4349 return details; 4350 } 4351 4352 @Override 4353 protected Pair<Symbol, JCDiagnostic> errCandidate() { 4354 Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates(); 4355 Map<Symbol, JCDiagnostic> filteredCandidates = filterCandidates(candidatesMap); 4356 if (filteredCandidates.size() == 1) { 4357 return Pair.of(filteredCandidates.keySet().iterator().next(), 4358 filteredCandidates.values().iterator().next()); 4359 } 4360 return null; 4361 } 4362 } 4363 4364 /** 4365 * DiamondError error class indicating that a constructor symbol is not applicable 4366 * given an actual arguments/type argument list using diamond inference. 4367 */ 4368 class DiamondError extends InapplicableSymbolError { 4369 4370 Symbol sym; 4371 4372 public DiamondError(Symbol sym, MethodResolutionContext context) { 4373 super(sym.kind, "diamondError", context); 4374 this.sym = sym; 4375 } 4376 4377 JCDiagnostic getDetails() { 4378 return (sym.kind == WRONG_MTH) ? 4379 ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd : 4380 null; 4381 } 4382 4383 @Override 4384 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, 4385 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4386 JCDiagnostic details = getDetails(); 4387 if (details != null && compactMethodDiags) { 4388 JCDiagnostic simpleDiag = 4389 MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, details); 4390 if (simpleDiag != null) { 4391 return simpleDiag; 4392 } 4393 } 4394 String key = details == null ? 4395 "cant.apply.diamond" : 4396 "cant.apply.diamond.1"; 4397 return diags.create(dkind, log.currentSource(), pos, key, 4398 Fragments.Diamond(site.tsym), details); 4399 } 4400 } 4401 4402 /** 4403 * An InvalidSymbolError error class indicating that a symbol is not 4404 * accessible from a given site 4405 */ 4406 class AccessError extends InvalidSymbolError { 4407 4408 private Env<AttrContext> env; 4409 private Type site; 4410 4411 AccessError(Env<AttrContext> env, Type site, Symbol sym) { 4412 super(HIDDEN, sym, "access error"); 4413 this.env = env; 4414 this.site = site; 4415 } 4416 4417 @Override 4418 public boolean exists() { 4419 return false; 4420 } 4421 4422 @Override 4423 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4424 DiagnosticPosition pos, 4425 Symbol location, 4426 Type site, 4427 Name name, 4428 List<Type> argtypes, 4429 List<Type> typeargtypes) { 4430 if (sym.name == names.init && sym.owner != site.tsym) { 4431 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, 4432 pos, location, site, name, argtypes, typeargtypes); 4433 } 4434 else if ((sym.flags() & PUBLIC) != 0 4435 || (env != null && this.site != null 4436 && !isAccessible(env, this.site))) { 4437 if (sym.owner.kind == PCK) { 4438 return diags.create(dkind, log.currentSource(), 4439 pos, "not.def.access.package.cant.access", 4440 sym, sym.location(), inaccessiblePackageReason(env, sym.packge())); 4441 } else if ( sym.packge() != syms.rootPackage 4442 && !symbolPackageVisible(env, sym)) { 4443 return diags.create(dkind, log.currentSource(), 4444 pos, "not.def.access.class.intf.cant.access.reason", 4445 sym, sym.location(), sym.location().packge(), 4446 inaccessiblePackageReason(env, sym.packge())); 4447 } else { 4448 return diags.create(dkind, log.currentSource(), 4449 pos, "not.def.access.class.intf.cant.access", 4450 sym, sym.location()); 4451 } 4452 } 4453 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) { 4454 return diags.create(dkind, log.currentSource(), 4455 pos, "report.access", sym, 4456 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)), 4457 sym.location()); 4458 } 4459 else { 4460 return diags.create(dkind, log.currentSource(), 4461 pos, "not.def.public.cant.access", sym, sym.location()); 4462 } 4463 } 4464 4465 private String toString(Type type) { 4466 StringBuilder sb = new StringBuilder(); 4467 sb.append(type); 4468 if (type != null) { 4469 sb.append("[tsym:").append(type.tsym); 4470 if (type.tsym != null) 4471 sb.append("packge:").append(type.tsym.packge()); 4472 sb.append("]"); 4473 } 4474 return sb.toString(); 4475 } 4476 } 4477 4478 class InvisibleSymbolError extends InvalidSymbolError { 4479 4480 private final Env<AttrContext> env; 4481 private final boolean suppressError; 4482 4483 InvisibleSymbolError(Env<AttrContext> env, boolean suppressError, Symbol sym) { 4484 super(HIDDEN, sym, "invisible class error"); 4485 this.env = env; 4486 this.suppressError = suppressError; 4487 this.name = sym.name; 4488 } 4489 4490 @Override 4491 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4492 DiagnosticPosition pos, 4493 Symbol location, 4494 Type site, 4495 Name name, 4496 List<Type> argtypes, 4497 List<Type> typeargtypes) { 4498 if (suppressError) 4499 return null; 4500 4501 if (sym.kind == PCK) { 4502 JCDiagnostic details = inaccessiblePackageReason(env, sym.packge()); 4503 return diags.create(dkind, log.currentSource(), 4504 pos, "package.not.visible", sym, details); 4505 } 4506 4507 JCDiagnostic details = inaccessiblePackageReason(env, sym.packge()); 4508 4509 if (pos.getTree() != null) { 4510 Symbol o = sym; 4511 JCTree tree = pos.getTree(); 4512 4513 while (o.kind != PCK && tree.hasTag(SELECT)) { 4514 o = o.owner; 4515 tree = ((JCFieldAccess) tree).selected; 4516 } 4517 4518 if (o.kind == PCK) { 4519 pos = tree.pos(); 4520 4521 return diags.create(dkind, log.currentSource(), 4522 pos, "package.not.visible", o, details); 4523 } 4524 } 4525 4526 return diags.create(dkind, log.currentSource(), 4527 pos, "not.def.access.package.cant.access", sym, sym.packge(), details); 4528 } 4529 } 4530 4531 JCDiagnostic inaccessiblePackageReason(Env<AttrContext> env, PackageSymbol sym) { 4532 //no dependency: 4533 if (!env.toplevel.modle.readModules.contains(sym.modle)) { 4534 //does not read: 4535 if (sym.modle != syms.unnamedModule) { 4536 if (env.toplevel.modle != syms.unnamedModule) { 4537 return diags.fragment(Fragments.NotDefAccessDoesNotRead(env.toplevel.modle, 4538 sym, 4539 sym.modle)); 4540 } else { 4541 return diags.fragment(Fragments.NotDefAccessDoesNotReadFromUnnamed(sym, 4542 sym.modle)); 4543 } 4544 } else { 4545 return diags.fragment(Fragments.NotDefAccessDoesNotReadUnnamed(sym, 4546 env.toplevel.modle)); 4547 } 4548 } else { 4549 if (sym.packge().modle.exports.stream().anyMatch(e -> e.packge == sym)) { 4550 //not exported to this module: 4551 if (env.toplevel.modle != syms.unnamedModule) { 4552 return diags.fragment(Fragments.NotDefAccessNotExportedToModule(sym, 4553 sym.modle, 4554 env.toplevel.modle)); 4555 } else { 4556 return diags.fragment(Fragments.NotDefAccessNotExportedToModuleFromUnnamed(sym, 4557 sym.modle)); 4558 } 4559 } else { 4560 //not exported: 4561 if (env.toplevel.modle != syms.unnamedModule) { 4562 return diags.fragment(Fragments.NotDefAccessNotExported(sym, 4563 sym.modle)); 4564 } else { 4565 return diags.fragment(Fragments.NotDefAccessNotExportedFromUnnamed(sym, 4566 sym.modle)); 4567 } 4568 } 4569 } 4570 } 4571 4572 /** 4573 * InvalidSymbolError error class indicating that an instance member 4574 * has erroneously been accessed from a static context. 4575 */ 4576 class StaticError extends InvalidSymbolError { 4577 4578 StaticError(Symbol sym) { 4579 super(STATICERR, sym, "static error"); 4580 } 4581 4582 @Override 4583 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4584 DiagnosticPosition pos, 4585 Symbol location, 4586 Type site, 4587 Name name, 4588 List<Type> argtypes, 4589 List<Type> typeargtypes) { 4590 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS)) 4591 ? types.erasure(sym.type).tsym 4592 : sym); 4593 return diags.create(dkind, log.currentSource(), pos, 4594 "non-static.cant.be.ref", kindName(sym), errSym); 4595 } 4596 } 4597 4598 /** 4599 * InvalidSymbolError error class indicating that a pair of symbols 4600 * (either methods, constructors or operands) are ambiguous 4601 * given an actual arguments/type argument list. 4602 */ 4603 class AmbiguityError extends ResolveError { 4604 4605 /** The other maximally specific symbol */ 4606 List<Symbol> ambiguousSyms = List.nil(); 4607 4608 @Override 4609 public boolean exists() { 4610 return true; 4611 } 4612 4613 AmbiguityError(Symbol sym1, Symbol sym2) { 4614 super(AMBIGUOUS, "ambiguity error"); 4615 ambiguousSyms = flatten(sym2).appendList(flatten(sym1)); 4616 } 4617 4618 private List<Symbol> flatten(Symbol sym) { 4619 if (sym.kind == AMBIGUOUS) { 4620 return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms; 4621 } else { 4622 return List.of(sym); 4623 } 4624 } 4625 4626 AmbiguityError addAmbiguousSymbol(Symbol s) { 4627 ambiguousSyms = ambiguousSyms.prepend(s); 4628 return this; 4629 } 4630 4631 @Override 4632 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4633 DiagnosticPosition pos, 4634 Symbol location, 4635 Type site, 4636 Name name, 4637 List<Type> argtypes, 4638 List<Type> typeargtypes) { 4639 List<Symbol> diagSyms = ambiguousSyms.reverse(); 4640 Symbol s1 = diagSyms.head; 4641 Symbol s2 = diagSyms.tail.head; 4642 Name sname = s1.name; 4643 if (sname == names.init) sname = s1.owner.name; 4644 return diags.create(dkind, log.currentSource(), 4645 pos, "ref.ambiguous", sname, 4646 kindName(s1), 4647 s1, 4648 s1.location(site, types), 4649 kindName(s2), 4650 s2, 4651 s2.location(site, types)); 4652 } 4653 4654 /** 4655 * If multiple applicable methods are found during overload and none of them 4656 * is more specific than the others, attempt to merge their signatures. 4657 */ 4658 Symbol mergeAbstracts(Type site) { 4659 List<Symbol> ambiguousInOrder = ambiguousSyms.reverse(); 4660 return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this); 4661 } 4662 4663 @Override 4664 protected Symbol access(Name name, TypeSymbol location) { 4665 Symbol firstAmbiguity = ambiguousSyms.last(); 4666 return firstAmbiguity.kind == TYP ? 4667 types.createErrorType(name, location, firstAmbiguity.type).tsym : 4668 firstAmbiguity; 4669 } 4670 } 4671 4672 class BadVarargsMethod extends ResolveError { 4673 4674 ResolveError delegatedError; 4675 4676 BadVarargsMethod(ResolveError delegatedError) { 4677 super(delegatedError.kind, "badVarargs"); 4678 this.delegatedError = delegatedError; 4679 } 4680 4681 @Override 4682 public Symbol baseSymbol() { 4683 return delegatedError.baseSymbol(); 4684 } 4685 4686 @Override 4687 protected Symbol access(Name name, TypeSymbol location) { 4688 return delegatedError.access(name, location); 4689 } 4690 4691 @Override 4692 public boolean exists() { 4693 return true; 4694 } 4695 4696 @Override 4697 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4698 return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes); 4699 } 4700 } 4701 4702 /** 4703 * BadMethodReferenceError error class indicating that a method reference symbol has been found, 4704 * but with the wrong staticness. 4705 */ 4706 class BadMethodReferenceError extends StaticError { 4707 4708 boolean unboundLookup; 4709 4710 public BadMethodReferenceError(Symbol sym, boolean unboundLookup) { 4711 super(sym); 4712 this.unboundLookup = unboundLookup; 4713 } 4714 4715 @Override 4716 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4717 final String key; 4718 if (!unboundLookup) { 4719 key = "bad.static.method.in.bound.lookup"; 4720 } else if (sym.isStatic()) { 4721 key = "bad.static.method.in.unbound.lookup"; 4722 } else { 4723 key = "bad.instance.method.in.unbound.lookup"; 4724 } 4725 return sym.kind.isResolutionError() ? 4726 ((ResolveError)sym).getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes) : 4727 diags.create(dkind, log.currentSource(), pos, key, Kinds.kindName(sym), sym); 4728 } 4729 } 4730 4731 /** 4732 * BadConstructorReferenceError error class indicating that a constructor reference symbol has been found, 4733 * but pointing to a class for which an enclosing instance is not available. 4734 */ 4735 class BadConstructorReferenceError extends InvalidSymbolError { 4736 4737 public BadConstructorReferenceError(Symbol sym) { 4738 super(MISSING_ENCL, sym, "BadConstructorReferenceError"); 4739 } 4740 4741 @Override 4742 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4743 return diags.create(dkind, log.currentSource(), pos, 4744 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType()); 4745 } 4746 } 4747 4748 class BadClassFileError extends InvalidSymbolError { 4749 4750 private final CompletionFailure ex; 4751 4752 public BadClassFileError(CompletionFailure ex) { 4753 super(HIDDEN, ex.sym, "BadClassFileError"); 4754 this.name = sym.name; 4755 this.ex = ex; 4756 } 4757 4758 @Override 4759 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4760 JCDiagnostic d = diags.create(dkind, log.currentSource(), pos, 4761 "cant.access", ex.sym, ex.getDetailValue()); 4762 4763 d.setFlag(DiagnosticFlag.NON_DEFERRABLE); 4764 return d; 4765 } 4766 4767 } 4768 4769 /** 4770 * Helper class for method resolution diagnostic simplification. 4771 * Certain resolution diagnostic are rewritten as simpler diagnostic 4772 * where the enclosing resolution diagnostic (i.e. 'inapplicable method') 4773 * is stripped away, as it doesn't carry additional info. The logic 4774 * for matching a given diagnostic is given in terms of a template 4775 * hierarchy: a diagnostic template can be specified programmatically, 4776 * so that only certain diagnostics are matched. Each templete is then 4777 * associated with a rewriter object that carries out the task of rewtiting 4778 * the diagnostic to a simpler one. 4779 */ 4780 static class MethodResolutionDiagHelper { 4781 4782 /** 4783 * A diagnostic rewriter transforms a method resolution diagnostic 4784 * into a simpler one 4785 */ 4786 interface DiagnosticRewriter { 4787 JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags, 4788 DiagnosticPosition preferredPos, DiagnosticSource preferredSource, 4789 DiagnosticType preferredKind, JCDiagnostic d); 4790 } 4791 4792 /** 4793 * A diagnostic template is made up of two ingredients: (i) a regular 4794 * expression for matching a diagnostic key and (ii) a list of sub-templates 4795 * for matching diagnostic arguments. 4796 */ 4797 static class Template { 4798 4799 /** regex used to match diag key */ 4800 String regex; 4801 4802 /** templates used to match diagnostic args */ 4803 Template[] subTemplates; 4804 4805 Template(String key, Template... subTemplates) { 4806 this.regex = key; 4807 this.subTemplates = subTemplates; 4808 } 4809 4810 /** 4811 * Returns true if the regex matches the diagnostic key and if 4812 * all diagnostic arguments are matches by corresponding sub-templates. 4813 */ 4814 boolean matches(Object o) { 4815 JCDiagnostic d = (JCDiagnostic)o; 4816 Object[] args = d.getArgs(); 4817 if (!d.getCode().matches(regex) || 4818 subTemplates.length != d.getArgs().length) { 4819 return false; 4820 } 4821 for (int i = 0; i < args.length ; i++) { 4822 if (!subTemplates[i].matches(args[i])) { 4823 return false; 4824 } 4825 } 4826 return true; 4827 } 4828 } 4829 4830 /** 4831 * Common rewriter for all argument mismatch simplifications. 4832 */ 4833 static class ArgMismatchRewriter implements DiagnosticRewriter { 4834 4835 /** the index of the subdiagnostic to be used as primary. */ 4836 int causeIndex; 4837 4838 public ArgMismatchRewriter(int causeIndex) { 4839 this.causeIndex = causeIndex; 4840 } 4841 4842 @Override 4843 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags, 4844 DiagnosticPosition preferredPos, DiagnosticSource preferredSource, 4845 DiagnosticType preferredKind, JCDiagnostic d) { 4846 JCDiagnostic cause = (JCDiagnostic)d.getArgs()[causeIndex]; 4847 DiagnosticPosition pos = d.getDiagnosticPosition(); 4848 if (pos == null) { 4849 pos = preferredPos; 4850 } 4851 return diags.create(preferredKind, preferredSource, pos, 4852 "prob.found.req", cause); 4853 } 4854 } 4855 4856 /** a dummy template that match any diagnostic argument */ 4857 static final Template skip = new Template("") { 4858 @Override 4859 boolean matches(Object d) { 4860 return true; 4861 } 4862 }; 4863 4864 /** template for matching inference-free arguments mismatch failures */ 4865 static final Template argMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip); 4866 4867 /** template for matching inference related arguments mismatch failures */ 4868 static final Template inferArgMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip, skip) { 4869 @Override 4870 boolean matches(Object o) { 4871 if (!super.matches(o)) { 4872 return false; 4873 } 4874 JCDiagnostic d = (JCDiagnostic)o; 4875 @SuppressWarnings("unchecked") 4876 List<Type> tvars = (List<Type>)d.getArgs()[0]; 4877 return !containsAny(d, tvars); 4878 } 4879 4880 BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> { 4881 if (o instanceof Type type) { 4882 return type.containsAny(ts); 4883 } else if (o instanceof JCDiagnostic diagnostic) { 4884 return containsAny(diagnostic, ts); 4885 } else { 4886 return false; 4887 } 4888 }; 4889 4890 boolean containsAny(JCDiagnostic d, List<Type> ts) { 4891 return Stream.of(d.getArgs()) 4892 .anyMatch(o -> containsPredicate.test(o, ts)); 4893 } 4894 }; 4895 4896 /** rewriter map used for method resolution simplification */ 4897 static final Map<Template, DiagnosticRewriter> rewriters = new LinkedHashMap<>(); 4898 4899 static { 4900 rewriters.put(argMismatchTemplate, new ArgMismatchRewriter(0)); 4901 rewriters.put(inferArgMismatchTemplate, new ArgMismatchRewriter(1)); 4902 } 4903 4904 /** 4905 * Main entry point for diagnostic rewriting - given a diagnostic, see if any templates matches it, 4906 * and rewrite it accordingly. 4907 */ 4908 static JCDiagnostic rewrite(JCDiagnostic.Factory diags, DiagnosticPosition pos, DiagnosticSource source, 4909 DiagnosticType dkind, JCDiagnostic d) { 4910 for (Map.Entry<Template, DiagnosticRewriter> _entry : rewriters.entrySet()) { 4911 if (_entry.getKey().matches(d)) { 4912 JCDiagnostic simpleDiag = 4913 _entry.getValue().rewriteDiagnostic(diags, pos, source, dkind, d); 4914 simpleDiag.setFlag(DiagnosticFlag.COMPRESSED); 4915 return simpleDiag; 4916 } 4917 } 4918 return null; 4919 } 4920 } 4921 4922 enum MethodResolutionPhase { 4923 BASIC(false, false), 4924 BOX(true, false), 4925 VARARITY(true, true) { 4926 @Override 4927 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) { 4928 //Check invariants (see {@code LookupHelper.shouldStop}) 4929 Assert.check(bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS); 4930 if (!sym.kind.isResolutionError()) { 4931 //varargs resolution successful 4932 return sym; 4933 } else { 4934 //pick best error 4935 switch (bestSoFar.kind) { 4936 case WRONG_MTH: 4937 case WRONG_MTHS: 4938 //Override previous errors if they were caused by argument mismatch. 4939 //This generally means preferring current symbols - but we need to pay 4940 //attention to the fact that the varargs lookup returns 'less' candidates 4941 //than the previous rounds, and adjust that accordingly. 4942 switch (sym.kind) { 4943 case WRONG_MTH: 4944 //if the previous round matched more than one method, return that 4945 //result instead 4946 return bestSoFar.kind == WRONG_MTHS ? 4947 bestSoFar : sym; 4948 case ABSENT_MTH: 4949 //do not override erroneous symbol if the arity lookup did not 4950 //match any method 4951 return bestSoFar; 4952 case WRONG_MTHS: 4953 default: 4954 //safe to override 4955 return sym; 4956 } 4957 default: 4958 //otherwise, return first error 4959 return bestSoFar; 4960 } 4961 } 4962 } 4963 }; 4964 4965 final boolean isBoxingRequired; 4966 final boolean isVarargsRequired; 4967 4968 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) { 4969 this.isBoxingRequired = isBoxingRequired; 4970 this.isVarargsRequired = isVarargsRequired; 4971 } 4972 4973 public boolean isBoxingRequired() { 4974 return isBoxingRequired; 4975 } 4976 4977 public boolean isVarargsRequired() { 4978 return isVarargsRequired; 4979 } 4980 4981 public Symbol mergeResults(Symbol prev, Symbol sym) { 4982 return sym; 4983 } 4984 } 4985 4986 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY); 4987 4988 /** 4989 * A resolution context is used to keep track of intermediate results of 4990 * overload resolution, such as list of method that are not applicable 4991 * (used to generate more precise diagnostics) and so on. Resolution contexts 4992 * can be nested - this means that when each overload resolution routine should 4993 * work within the resolution context it created. 4994 */ 4995 class MethodResolutionContext { 4996 4997 private List<Candidate> candidates = List.nil(); 4998 4999 MethodResolutionPhase step = null; 5000 5001 MethodCheck methodCheck = resolveMethodCheck; 5002 5003 private boolean internalResolution = false; 5004 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE; 5005 5006 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) { 5007 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null); 5008 candidates = candidates.append(c); 5009 } 5010 5011 void addApplicableCandidate(Symbol sym, Type mtype) { 5012 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype); 5013 candidates = candidates.append(c); 5014 } 5015 5016 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) { 5017 DeferredAttrContext parent = (pendingResult == null) 5018 ? deferredAttr.emptyDeferredAttrContext 5019 : pendingResult.checkContext.deferredAttrContext(); 5020 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, 5021 inferenceContext, parent, warn); 5022 } 5023 5024 /** 5025 * This class represents an overload resolution candidate. There are two 5026 * kinds of candidates: applicable methods and inapplicable methods; 5027 * applicable methods have a pointer to the instantiated method type, 5028 * while inapplicable candidates contain further details about the 5029 * reason why the method has been considered inapplicable. 5030 */ 5031 @SuppressWarnings("overrides") 5032 class Candidate { 5033 5034 final MethodResolutionPhase step; 5035 final Symbol sym; 5036 final JCDiagnostic details; 5037 final Type mtype; 5038 5039 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) { 5040 this.step = step; 5041 this.sym = sym; 5042 this.details = details; 5043 this.mtype = mtype; 5044 } 5045 5046 boolean isApplicable() { 5047 return mtype != null; 5048 } 5049 } 5050 5051 DeferredAttr.AttrMode attrMode() { 5052 return attrMode; 5053 } 5054 5055 boolean internal() { 5056 return internalResolution; 5057 } 5058 } 5059 5060 MethodResolutionContext currentResolutionContext = null; 5061 }