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