Resolve.java revision 3324:82f94333bd7e
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("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 types.asSuper(t, s.tsym) == null && 1153 types.asSuper(s, t.tsym) == null; 1154 } 1155 1156 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */ 1157 private boolean functionalInterfaceMostSpecific(Type t, Type s, JCTree tree) { 1158 Type tDesc = types.findDescriptorType(t); 1159 Type sDesc = types.findDescriptorType(s); 1160 1161 // compare type parameters -- can't use Types.hasSameBounds because bounds may have ivars 1162 final List<Type> tTypeParams = tDesc.getTypeArguments(); 1163 final List<Type> sTypeParams = sDesc.getTypeArguments(); 1164 List<Type> tIter = tTypeParams; 1165 List<Type> sIter = sTypeParams; 1166 while (tIter.nonEmpty() && sIter.nonEmpty()) { 1167 Type tBound = tIter.head.getUpperBound(); 1168 Type sBound = types.subst(sIter.head.getUpperBound(), sTypeParams, tTypeParams); 1169 if (tBound.containsAny(tTypeParams) && inferenceContext().free(sBound)) { 1170 return false; 1171 } 1172 if (!types.isSameType(tBound, inferenceContext().asUndetVar(sBound))) { 1173 return false; 1174 } 1175 tIter = tIter.tail; 1176 sIter = sIter.tail; 1177 } 1178 if (!tIter.isEmpty() || !sIter.isEmpty()) { 1179 return false; 1180 } 1181 1182 // compare parameters 1183 List<Type> tParams = tDesc.getParameterTypes(); 1184 List<Type> sParams = sDesc.getParameterTypes(); 1185 while (tParams.nonEmpty() && sParams.nonEmpty()) { 1186 Type tParam = tParams.head; 1187 Type sParam = types.subst(sParams.head, sTypeParams, tTypeParams); 1188 if (tParam.containsAny(tTypeParams) && inferenceContext().free(sParam)) { 1189 return false; 1190 } 1191 if (!types.isSameType(tParam, inferenceContext().asUndetVar(sParam))) { 1192 return false; 1193 } 1194 tParams = tParams.tail; 1195 sParams = sParams.tail; 1196 } 1197 if (!tParams.isEmpty() || !sParams.isEmpty()) { 1198 return false; 1199 } 1200 1201 // compare returns 1202 Type tRet = tDesc.getReturnType(); 1203 Type sRet = types.subst(sDesc.getReturnType(), sTypeParams, tTypeParams); 1204 if (tRet.containsAny(tTypeParams) && inferenceContext().free(sRet)) { 1205 return false; 1206 } 1207 MostSpecificFunctionReturnChecker msc = new MostSpecificFunctionReturnChecker(tRet, sRet); 1208 msc.scan(tree); 1209 return msc.result; 1210 } 1211 1212 /** 1213 * Tests whether one functional interface type can be considered more specific 1214 * than another unrelated functional interface type for the scanned expression. 1215 */ 1216 class MostSpecificFunctionReturnChecker extends DeferredAttr.PolyScanner { 1217 1218 final Type tRet; 1219 final Type sRet; 1220 boolean result; 1221 1222 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */ 1223 MostSpecificFunctionReturnChecker(Type tRet, Type sRet) { 1224 this.tRet = tRet; 1225 this.sRet = sRet; 1226 result = true; 1227 } 1228 1229 @Override 1230 void skip(JCTree tree) { 1231 result &= false; 1232 } 1233 1234 @Override 1235 public void visitConditional(JCConditional tree) { 1236 scan(asExpr(tree.truepart)); 1237 scan(asExpr(tree.falsepart)); 1238 } 1239 1240 @Override 1241 public void visitReference(JCMemberReference tree) { 1242 if (sRet.hasTag(VOID)) { 1243 result &= true; 1244 } else if (tRet.hasTag(VOID)) { 1245 result &= false; 1246 } else if (tRet.isPrimitive() != sRet.isPrimitive()) { 1247 boolean retValIsPrimitive = 1248 tree.refPolyKind == PolyKind.STANDALONE && 1249 tree.sym.type.getReturnType().isPrimitive(); 1250 result &= (retValIsPrimitive == tRet.isPrimitive()) && 1251 (retValIsPrimitive != sRet.isPrimitive()); 1252 } else { 1253 result &= compatibleBySubtyping(tRet, sRet); 1254 } 1255 } 1256 1257 @Override 1258 public void visitParens(JCParens tree) { 1259 scan(asExpr(tree.expr)); 1260 } 1261 1262 @Override 1263 public void visitLambda(JCLambda tree) { 1264 if (sRet.hasTag(VOID)) { 1265 result &= true; 1266 } else if (tRet.hasTag(VOID)) { 1267 result &= false; 1268 } else { 1269 List<JCExpression> lambdaResults = lambdaResults(tree); 1270 if (!lambdaResults.isEmpty() && unrelatedFunctionalInterfaces(tRet, sRet)) { 1271 for (JCExpression expr : lambdaResults) { 1272 result &= functionalInterfaceMostSpecific(tRet, sRet, expr); 1273 } 1274 } else if (!lambdaResults.isEmpty() && tRet.isPrimitive() != sRet.isPrimitive()) { 1275 for (JCExpression expr : lambdaResults) { 1276 boolean retValIsPrimitive = expr.isStandalone() && expr.type.isPrimitive(); 1277 result &= (retValIsPrimitive == tRet.isPrimitive()) && 1278 (retValIsPrimitive != sRet.isPrimitive()); 1279 } 1280 } else { 1281 result &= compatibleBySubtyping(tRet, sRet); 1282 } 1283 } 1284 } 1285 //where 1286 1287 private List<JCExpression> lambdaResults(JCLambda lambda) { 1288 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) { 1289 return List.of(asExpr((JCExpression) lambda.body)); 1290 } else { 1291 final ListBuffer<JCExpression> buffer = new ListBuffer<>(); 1292 DeferredAttr.LambdaReturnScanner lambdaScanner = 1293 new DeferredAttr.LambdaReturnScanner() { 1294 @Override 1295 public void visitReturn(JCReturn tree) { 1296 if (tree.expr != null) { 1297 buffer.append(asExpr(tree.expr)); 1298 } 1299 } 1300 }; 1301 lambdaScanner.scan(lambda.body); 1302 return buffer.toList(); 1303 } 1304 } 1305 1306 private JCExpression asExpr(JCExpression expr) { 1307 if (expr.type.hasTag(DEFERRED)) { 1308 JCTree speculativeTree = ((DeferredType)expr.type).speculativeTree(deferredAttrContext); 1309 if (speculativeTree != deferredAttr.stuckTree) { 1310 expr = (JCExpression)speculativeTree; 1311 } 1312 } 1313 return expr; 1314 } 1315 } 1316 1317 } 1318 1319 public MethodCheck mostSpecificCheck(List<Type> actuals) { 1320 Assert.error("Cannot get here!"); 1321 return null; 1322 } 1323 } 1324 1325 public static class InapplicableMethodException extends RuntimeException { 1326 private static final long serialVersionUID = 0; 1327 1328 JCDiagnostic diagnostic; 1329 JCDiagnostic.Factory diags; 1330 1331 InapplicableMethodException(JCDiagnostic.Factory diags) { 1332 this.diagnostic = null; 1333 this.diags = diags; 1334 } 1335 InapplicableMethodException setMessage() { 1336 return setMessage((JCDiagnostic)null); 1337 } 1338 InapplicableMethodException setMessage(String key) { 1339 return setMessage(key != null ? diags.fragment(key) : null); 1340 } 1341 InapplicableMethodException setMessage(String key, Object... args) { 1342 return setMessage(key != null ? diags.fragment(key, args) : null); 1343 } 1344 InapplicableMethodException setMessage(JCDiagnostic diag) { 1345 this.diagnostic = diag; 1346 return this; 1347 } 1348 1349 public JCDiagnostic getDiagnostic() { 1350 return diagnostic; 1351 } 1352 } 1353 private final InapplicableMethodException inapplicableMethodException; 1354 1355/* *************************************************************************** 1356 * Symbol lookup 1357 * the following naming conventions for arguments are used 1358 * 1359 * env is the environment where the symbol was mentioned 1360 * site is the type of which the symbol is a member 1361 * name is the symbol's name 1362 * if no arguments are given 1363 * argtypes are the value arguments, if we search for a method 1364 * 1365 * If no symbol was found, a ResolveError detailing the problem is returned. 1366 ****************************************************************************/ 1367 1368 /** Find field. Synthetic fields are always skipped. 1369 * @param env The current environment. 1370 * @param site The original type from where the selection takes place. 1371 * @param name The name of the field. 1372 * @param c The class to search for the field. This is always 1373 * a superclass or implemented interface of site's class. 1374 */ 1375 Symbol findField(Env<AttrContext> env, 1376 Type site, 1377 Name name, 1378 TypeSymbol c) { 1379 while (c.type.hasTag(TYPEVAR)) 1380 c = c.type.getUpperBound().tsym; 1381 Symbol bestSoFar = varNotFound; 1382 Symbol sym; 1383 for (Symbol s : c.members().getSymbolsByName(name)) { 1384 if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) { 1385 return isAccessible(env, site, s) 1386 ? s : new AccessError(env, site, s); 1387 } 1388 } 1389 Type st = types.supertype(c.type); 1390 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) { 1391 sym = findField(env, site, name, st.tsym); 1392 bestSoFar = bestOf(bestSoFar, sym); 1393 } 1394 for (List<Type> l = types.interfaces(c.type); 1395 bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); 1396 l = l.tail) { 1397 sym = findField(env, site, name, l.head.tsym); 1398 if (bestSoFar.exists() && sym.exists() && 1399 sym.owner != bestSoFar.owner) 1400 bestSoFar = new AmbiguityError(bestSoFar, sym); 1401 else 1402 bestSoFar = bestOf(bestSoFar, sym); 1403 } 1404 return bestSoFar; 1405 } 1406 1407 /** Resolve a field identifier, throw a fatal error if not found. 1408 * @param pos The position to use for error reporting. 1409 * @param env The environment current at the method invocation. 1410 * @param site The type of the qualifying expression, in which 1411 * identifier is searched. 1412 * @param name The identifier's name. 1413 */ 1414 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env, 1415 Type site, Name name) { 1416 Symbol sym = findField(env, site, name, site.tsym); 1417 if (sym.kind == VAR) return (VarSymbol)sym; 1418 else throw new FatalError( 1419 diags.fragment("fatal.err.cant.locate.field", 1420 name)); 1421 } 1422 1423 /** Find unqualified variable or field with given name. 1424 * Synthetic fields always skipped. 1425 * @param env The current environment. 1426 * @param name The name of the variable or field. 1427 */ 1428 Symbol findVar(Env<AttrContext> env, Name name) { 1429 Symbol bestSoFar = varNotFound; 1430 Env<AttrContext> env1 = env; 1431 boolean staticOnly = false; 1432 while (env1.outer != null) { 1433 Symbol sym = null; 1434 if (isStatic(env1)) staticOnly = true; 1435 for (Symbol s : env1.info.scope.getSymbolsByName(name)) { 1436 if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) { 1437 sym = s; 1438 break; 1439 } 1440 } 1441 if (sym == null) { 1442 sym = findField(env1, env1.enclClass.sym.type, name, env1.enclClass.sym); 1443 } 1444 if (sym.exists()) { 1445 if (staticOnly && 1446 sym.kind == VAR && 1447 sym.owner.kind == TYP && 1448 (sym.flags() & STATIC) == 0) 1449 return new StaticError(sym); 1450 else 1451 return sym; 1452 } else { 1453 bestSoFar = bestOf(bestSoFar, sym); 1454 } 1455 1456 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 1457 env1 = env1.outer; 1458 } 1459 1460 Symbol sym = findField(env, syms.predefClass.type, name, syms.predefClass); 1461 if (sym.exists()) 1462 return sym; 1463 if (bestSoFar.exists()) 1464 return bestSoFar; 1465 1466 Symbol origin = null; 1467 for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) { 1468 for (Symbol currentSymbol : sc.getSymbolsByName(name)) { 1469 if (currentSymbol.kind != VAR) 1470 continue; 1471 // invariant: sym.kind == Symbol.Kind.VAR 1472 if (!bestSoFar.kind.isResolutionError() && 1473 currentSymbol.owner != bestSoFar.owner) 1474 return new AmbiguityError(bestSoFar, currentSymbol); 1475 else if (!bestSoFar.kind.betterThan(VAR)) { 1476 origin = sc.getOrigin(currentSymbol).owner; 1477 bestSoFar = isAccessible(env, origin.type, currentSymbol) 1478 ? currentSymbol : new AccessError(env, origin.type, currentSymbol); 1479 } 1480 } 1481 if (bestSoFar.exists()) break; 1482 } 1483 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type) 1484 return bestSoFar.clone(origin); 1485 else 1486 return bestSoFar; 1487 } 1488 1489 Warner noteWarner = new Warner(); 1490 1491 /** Select the best method for a call site among two choices. 1492 * @param env The current environment. 1493 * @param site The original type from where the 1494 * selection takes place. 1495 * @param argtypes The invocation's value arguments, 1496 * @param typeargtypes The invocation's type arguments, 1497 * @param sym Proposed new best match. 1498 * @param bestSoFar Previously found best match. 1499 * @param allowBoxing Allow boxing conversions of arguments. 1500 * @param useVarargs Box trailing arguments into an array for varargs. 1501 */ 1502 @SuppressWarnings("fallthrough") 1503 Symbol selectBest(Env<AttrContext> env, 1504 Type site, 1505 List<Type> argtypes, 1506 List<Type> typeargtypes, 1507 Symbol sym, 1508 Symbol bestSoFar, 1509 boolean allowBoxing, 1510 boolean useVarargs) { 1511 if (sym.kind == ERR || 1512 !sym.isInheritedIn(site.tsym, types)) { 1513 return bestSoFar; 1514 } else if (useVarargs && (sym.flags() & VARARGS) == 0) { 1515 return bestSoFar.kind.isResolutionError() ? 1516 new BadVarargsMethod((ResolveError)bestSoFar.baseSymbol()) : 1517 bestSoFar; 1518 } 1519 Assert.check(!sym.kind.isResolutionError()); 1520 try { 1521 types.noWarnings.clear(); 1522 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes, 1523 allowBoxing, useVarargs, types.noWarnings); 1524 currentResolutionContext.addApplicableCandidate(sym, mt); 1525 } catch (InapplicableMethodException ex) { 1526 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic()); 1527 switch (bestSoFar.kind) { 1528 case ABSENT_MTH: 1529 return new InapplicableSymbolError(currentResolutionContext); 1530 case WRONG_MTH: 1531 bestSoFar = new InapplicableSymbolsError(currentResolutionContext); 1532 default: 1533 return bestSoFar; 1534 } 1535 } 1536 if (!isAccessible(env, site, sym)) { 1537 return (bestSoFar.kind == ABSENT_MTH) 1538 ? new AccessError(env, site, sym) 1539 : bestSoFar; 1540 } 1541 return (bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS) 1542 ? sym 1543 : mostSpecific(argtypes, sym, bestSoFar, env, site, useVarargs); 1544 } 1545 1546 /* Return the most specific of the two methods for a call, 1547 * given that both are accessible and applicable. 1548 * @param m1 A new candidate for most specific. 1549 * @param m2 The previous most specific candidate. 1550 * @param env The current environment. 1551 * @param site The original type from where the selection 1552 * takes place. 1553 * @param allowBoxing Allow boxing conversions of arguments. 1554 * @param useVarargs Box trailing arguments into an array for varargs. 1555 */ 1556 Symbol mostSpecific(List<Type> argtypes, Symbol m1, 1557 Symbol m2, 1558 Env<AttrContext> env, 1559 final Type site, 1560 boolean useVarargs) { 1561 switch (m2.kind) { 1562 case MTH: 1563 if (m1 == m2) return m1; 1564 boolean m1SignatureMoreSpecific = 1565 signatureMoreSpecific(argtypes, env, site, m1, m2, useVarargs); 1566 boolean m2SignatureMoreSpecific = 1567 signatureMoreSpecific(argtypes, env, site, m2, m1, useVarargs); 1568 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) { 1569 Type mt1 = types.memberType(site, m1); 1570 Type mt2 = types.memberType(site, m2); 1571 if (!types.overrideEquivalent(mt1, mt2)) 1572 return ambiguityError(m1, m2); 1573 1574 // same signature; select (a) the non-bridge method, or 1575 // (b) the one that overrides the other, or (c) the concrete 1576 // one, or (d) merge both abstract signatures 1577 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) 1578 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1; 1579 1580 // if one overrides or hides the other, use it 1581 TypeSymbol m1Owner = (TypeSymbol)m1.owner; 1582 TypeSymbol m2Owner = (TypeSymbol)m2.owner; 1583 if (types.asSuper(m1Owner.type, m2Owner) != null && 1584 ((m1.owner.flags_field & INTERFACE) == 0 || 1585 (m2.owner.flags_field & INTERFACE) != 0) && 1586 m1.overrides(m2, m1Owner, types, false)) 1587 return m1; 1588 if (types.asSuper(m2Owner.type, m1Owner) != null && 1589 ((m2.owner.flags_field & INTERFACE) == 0 || 1590 (m1.owner.flags_field & INTERFACE) != 0) && 1591 m2.overrides(m1, m2Owner, types, false)) 1592 return m2; 1593 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0; 1594 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0; 1595 if (m1Abstract && !m2Abstract) return m2; 1596 if (m2Abstract && !m1Abstract) return m1; 1597 // both abstract or both concrete 1598 return ambiguityError(m1, m2); 1599 } 1600 if (m1SignatureMoreSpecific) return m1; 1601 if (m2SignatureMoreSpecific) return m2; 1602 return ambiguityError(m1, m2); 1603 case AMBIGUOUS: 1604 //compare m1 to ambiguous methods in m2 1605 AmbiguityError e = (AmbiguityError)m2.baseSymbol(); 1606 boolean m1MoreSpecificThanAnyAmbiguous = true; 1607 boolean allAmbiguousMoreSpecificThanM1 = true; 1608 for (Symbol s : e.ambiguousSyms) { 1609 Symbol moreSpecific = mostSpecific(argtypes, m1, s, env, site, useVarargs); 1610 m1MoreSpecificThanAnyAmbiguous &= moreSpecific == m1; 1611 allAmbiguousMoreSpecificThanM1 &= moreSpecific == s; 1612 } 1613 if (m1MoreSpecificThanAnyAmbiguous) 1614 return m1; 1615 //if m1 is more specific than some ambiguous methods, but other ambiguous methods are 1616 //more specific than m1, add it as a new ambiguous method: 1617 if (!allAmbiguousMoreSpecificThanM1) 1618 e.addAmbiguousSymbol(m1); 1619 return e; 1620 default: 1621 throw new AssertionError(); 1622 } 1623 } 1624 //where 1625 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean useVarargs) { 1626 noteWarner.clear(); 1627 int maxLength = Math.max( 1628 Math.max(m1.type.getParameterTypes().length(), actuals.length()), 1629 m2.type.getParameterTypes().length()); 1630 MethodResolutionContext prevResolutionContext = currentResolutionContext; 1631 try { 1632 currentResolutionContext = new MethodResolutionContext(); 1633 currentResolutionContext.step = prevResolutionContext.step; 1634 currentResolutionContext.methodCheck = 1635 prevResolutionContext.methodCheck.mostSpecificCheck(actuals); 1636 Type mst = instantiate(env, site, m2, null, 1637 adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null, 1638 false, useVarargs, noteWarner); 1639 return mst != null && 1640 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED); 1641 } finally { 1642 currentResolutionContext = prevResolutionContext; 1643 } 1644 } 1645 1646 List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) { 1647 if ((msym.flags() & VARARGS) != 0 && allowVarargs) { 1648 Type varargsElem = types.elemtype(args.last()); 1649 if (varargsElem == null) { 1650 Assert.error("Bad varargs = " + args.last() + " " + msym); 1651 } 1652 List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse(); 1653 while (newArgs.length() < length) { 1654 newArgs = newArgs.append(newArgs.last()); 1655 } 1656 return newArgs; 1657 } else { 1658 return args; 1659 } 1660 } 1661 //where 1662 Type mostSpecificReturnType(Type mt1, Type mt2) { 1663 Type rt1 = mt1.getReturnType(); 1664 Type rt2 = mt2.getReturnType(); 1665 1666 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) { 1667 //if both are generic methods, adjust return type ahead of subtyping check 1668 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments()); 1669 } 1670 //first use subtyping, then return type substitutability 1671 if (types.isSubtype(rt1, rt2)) { 1672 return mt1; 1673 } else if (types.isSubtype(rt2, rt1)) { 1674 return mt2; 1675 } else if (types.returnTypeSubstitutable(mt1, mt2)) { 1676 return mt1; 1677 } else if (types.returnTypeSubstitutable(mt2, mt1)) { 1678 return mt2; 1679 } else { 1680 return null; 1681 } 1682 } 1683 //where 1684 Symbol ambiguityError(Symbol m1, Symbol m2) { 1685 if (((m1.flags() | m2.flags()) & CLASH) != 0) { 1686 return (m1.flags() & CLASH) == 0 ? m1 : m2; 1687 } else { 1688 return new AmbiguityError(m1, m2); 1689 } 1690 } 1691 1692 Symbol findMethodInScope(Env<AttrContext> env, 1693 Type site, 1694 Name name, 1695 List<Type> argtypes, 1696 List<Type> typeargtypes, 1697 Scope sc, 1698 Symbol bestSoFar, 1699 boolean allowBoxing, 1700 boolean useVarargs, 1701 boolean abstractok) { 1702 for (Symbol s : sc.getSymbolsByName(name, new LookupFilter(abstractok))) { 1703 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s, 1704 bestSoFar, allowBoxing, useVarargs); 1705 } 1706 return bestSoFar; 1707 } 1708 //where 1709 class LookupFilter implements Filter<Symbol> { 1710 1711 boolean abstractOk; 1712 1713 LookupFilter(boolean abstractOk) { 1714 this.abstractOk = abstractOk; 1715 } 1716 1717 public boolean accepts(Symbol s) { 1718 long flags = s.flags(); 1719 return s.kind == MTH && 1720 (flags & SYNTHETIC) == 0 && 1721 (abstractOk || 1722 (flags & DEFAULT) != 0 || 1723 (flags & ABSTRACT) == 0); 1724 } 1725 } 1726 1727 /** Find best qualified method matching given name, type and value 1728 * arguments. 1729 * @param env The current environment. 1730 * @param site The original type from where the selection 1731 * takes place. 1732 * @param name The method's name. 1733 * @param argtypes The method's value arguments. 1734 * @param typeargtypes The method's type arguments 1735 * @param allowBoxing Allow boxing conversions of arguments. 1736 * @param useVarargs Box trailing arguments into an array for varargs. 1737 */ 1738 Symbol findMethod(Env<AttrContext> env, 1739 Type site, 1740 Name name, 1741 List<Type> argtypes, 1742 List<Type> typeargtypes, 1743 boolean allowBoxing, 1744 boolean useVarargs) { 1745 Symbol bestSoFar = methodNotFound; 1746 bestSoFar = findMethod(env, 1747 site, 1748 name, 1749 argtypes, 1750 typeargtypes, 1751 site.tsym.type, 1752 bestSoFar, 1753 allowBoxing, 1754 useVarargs); 1755 return bestSoFar; 1756 } 1757 // where 1758 private Symbol findMethod(Env<AttrContext> env, 1759 Type site, 1760 Name name, 1761 List<Type> argtypes, 1762 List<Type> typeargtypes, 1763 Type intype, 1764 Symbol bestSoFar, 1765 boolean allowBoxing, 1766 boolean useVarargs) { 1767 @SuppressWarnings({"unchecked","rawtypes"}) 1768 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() }; 1769 1770 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK; 1771 for (TypeSymbol s : superclasses(intype)) { 1772 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes, 1773 s.members(), bestSoFar, allowBoxing, useVarargs, true); 1774 if (name == names.init) return bestSoFar; 1775 iphase = (iphase == null) ? null : iphase.update(s, this); 1776 if (iphase != null) { 1777 for (Type itype : types.interfaces(s.type)) { 1778 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]); 1779 } 1780 } 1781 } 1782 1783 Symbol concrete = bestSoFar.kind.isValid() && 1784 (bestSoFar.flags() & ABSTRACT) == 0 ? 1785 bestSoFar : methodNotFound; 1786 1787 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) { 1788 //keep searching for abstract methods 1789 for (Type itype : itypes[iphase2.ordinal()]) { 1790 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure()) 1791 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && 1792 (itype.tsym.flags() & DEFAULT) == 0) continue; 1793 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes, 1794 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, true); 1795 if (concrete != bestSoFar && 1796 concrete.kind.isValid() && 1797 bestSoFar.kind.isValid() && 1798 types.isSubSignature(concrete.type, bestSoFar.type)) { 1799 //this is an hack - as javac does not do full membership checks 1800 //most specific ends up comparing abstract methods that might have 1801 //been implemented by some concrete method in a subclass and, 1802 //because of raw override, it is possible for an abstract method 1803 //to be more specific than the concrete method - so we need 1804 //to explicitly call that out (see CR 6178365) 1805 bestSoFar = concrete; 1806 } 1807 } 1808 } 1809 return bestSoFar; 1810 } 1811 1812 enum InterfaceLookupPhase { 1813 ABSTRACT_OK() { 1814 @Override 1815 InterfaceLookupPhase update(Symbol s, Resolve rs) { 1816 //We should not look for abstract methods if receiver is a concrete class 1817 //(as concrete classes are expected to implement all abstracts coming 1818 //from superinterfaces) 1819 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) { 1820 return this; 1821 } else { 1822 return DEFAULT_OK; 1823 } 1824 } 1825 }, 1826 DEFAULT_OK() { 1827 @Override 1828 InterfaceLookupPhase update(Symbol s, Resolve rs) { 1829 return this; 1830 } 1831 }; 1832 1833 abstract InterfaceLookupPhase update(Symbol s, Resolve rs); 1834 } 1835 1836 /** 1837 * Return an Iterable object to scan the superclasses of a given type. 1838 * It's crucial that the scan is done lazily, as we don't want to accidentally 1839 * access more supertypes than strictly needed (as this could trigger completion 1840 * errors if some of the not-needed supertypes are missing/ill-formed). 1841 */ 1842 Iterable<TypeSymbol> superclasses(final Type intype) { 1843 return new Iterable<TypeSymbol>() { 1844 public Iterator<TypeSymbol> iterator() { 1845 return new Iterator<TypeSymbol>() { 1846 1847 List<TypeSymbol> seen = List.nil(); 1848 TypeSymbol currentSym = symbolFor(intype); 1849 TypeSymbol prevSym = null; 1850 1851 public boolean hasNext() { 1852 if (currentSym == syms.noSymbol) { 1853 currentSym = symbolFor(types.supertype(prevSym.type)); 1854 } 1855 return currentSym != null; 1856 } 1857 1858 public TypeSymbol next() { 1859 prevSym = currentSym; 1860 currentSym = syms.noSymbol; 1861 Assert.check(prevSym != null || prevSym != syms.noSymbol); 1862 return prevSym; 1863 } 1864 1865 public void remove() { 1866 throw new UnsupportedOperationException(); 1867 } 1868 1869 TypeSymbol symbolFor(Type t) { 1870 if (!t.hasTag(CLASS) && 1871 !t.hasTag(TYPEVAR)) { 1872 return null; 1873 } 1874 t = types.skipTypeVars(t, false); 1875 if (seen.contains(t.tsym)) { 1876 //degenerate case in which we have a circular 1877 //class hierarchy - because of ill-formed classfiles 1878 return null; 1879 } 1880 seen = seen.prepend(t.tsym); 1881 return t.tsym; 1882 } 1883 }; 1884 } 1885 }; 1886 } 1887 1888 /** Find unqualified method matching given name, type and value arguments. 1889 * @param env The current environment. 1890 * @param name The method's name. 1891 * @param argtypes The method's value arguments. 1892 * @param typeargtypes The method's type arguments. 1893 * @param allowBoxing Allow boxing conversions of arguments. 1894 * @param useVarargs Box trailing arguments into an array for varargs. 1895 */ 1896 Symbol findFun(Env<AttrContext> env, Name name, 1897 List<Type> argtypes, List<Type> typeargtypes, 1898 boolean allowBoxing, boolean useVarargs) { 1899 Symbol bestSoFar = methodNotFound; 1900 Env<AttrContext> env1 = env; 1901 boolean staticOnly = false; 1902 while (env1.outer != null) { 1903 if (isStatic(env1)) staticOnly = true; 1904 Assert.check(env1.info.preferredTreeForDiagnostics == null); 1905 env1.info.preferredTreeForDiagnostics = env.tree; 1906 try { 1907 Symbol sym = findMethod( 1908 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes, 1909 allowBoxing, useVarargs); 1910 if (sym.exists()) { 1911 if (staticOnly && 1912 sym.kind == MTH && 1913 sym.owner.kind == TYP && 1914 (sym.flags() & STATIC) == 0) return new StaticError(sym); 1915 else return sym; 1916 } else { 1917 bestSoFar = bestOf(bestSoFar, sym); 1918 } 1919 } finally { 1920 env1.info.preferredTreeForDiagnostics = null; 1921 } 1922 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 1923 env1 = env1.outer; 1924 } 1925 1926 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes, 1927 typeargtypes, allowBoxing, useVarargs); 1928 if (sym.exists()) 1929 return sym; 1930 1931 for (Symbol currentSym : env.toplevel.namedImportScope.getSymbolsByName(name)) { 1932 Symbol origin = env.toplevel.namedImportScope.getOrigin(currentSym).owner; 1933 if (currentSym.kind == MTH) { 1934 if (currentSym.owner.type != origin.type) 1935 currentSym = currentSym.clone(origin); 1936 if (!isAccessible(env, origin.type, currentSym)) 1937 currentSym = new AccessError(env, origin.type, currentSym); 1938 bestSoFar = selectBest(env, origin.type, 1939 argtypes, typeargtypes, 1940 currentSym, bestSoFar, 1941 allowBoxing, useVarargs); 1942 } 1943 } 1944 if (bestSoFar.exists()) 1945 return bestSoFar; 1946 1947 for (Symbol currentSym : env.toplevel.starImportScope.getSymbolsByName(name)) { 1948 Symbol origin = env.toplevel.starImportScope.getOrigin(currentSym).owner; 1949 if (currentSym.kind == MTH) { 1950 if (currentSym.owner.type != origin.type) 1951 currentSym = currentSym.clone(origin); 1952 if (!isAccessible(env, origin.type, currentSym)) 1953 currentSym = new AccessError(env, origin.type, currentSym); 1954 bestSoFar = selectBest(env, origin.type, 1955 argtypes, typeargtypes, 1956 currentSym, bestSoFar, 1957 allowBoxing, useVarargs); 1958 } 1959 } 1960 return bestSoFar; 1961 } 1962 1963 /** Load toplevel or member class with given fully qualified name and 1964 * verify that it is accessible. 1965 * @param env The current environment. 1966 * @param name The fully qualified name of the class to be loaded. 1967 */ 1968 Symbol loadClass(Env<AttrContext> env, Name name) { 1969 try { 1970 ClassSymbol c = finder.loadClass(env.toplevel.modle, name); 1971 return isAccessible(env, c) ? c : new AccessError(c); 1972 } catch (ClassFinder.BadClassFile err) { 1973 throw err; 1974 } catch (CompletionFailure ex) { 1975 //even if a class cannot be found in the current module and packages in modules it depends on that 1976 //are exported for any or this module, the class may exist internally in some of these modules, 1977 //or may exist in a module on which this module does not depend. Provide better diagnostic in 1978 //such cases by looking for the class in any module: 1979 for (ModuleSymbol ms : syms.getAllModules()) { 1980 //do not load currently unloaded classes, to avoid too eager completion of random things in other modules: 1981 ClassSymbol clazz = syms.getClass(ms, name); 1982 1983 if (clazz != null) { 1984 return new AccessError(clazz); 1985 } 1986 } 1987 return typeNotFound; 1988 } 1989 } 1990 1991 /** 1992 * Find a type declared in a scope (not inherited). Return null 1993 * if none is found. 1994 * @param env The current environment. 1995 * @param site The original type from where the selection takes 1996 * place. 1997 * @param name The type's name. 1998 * @param c The class to search for the member type. This is 1999 * always a superclass or implemented interface of 2000 * site's class. 2001 */ 2002 Symbol findImmediateMemberType(Env<AttrContext> env, 2003 Type site, 2004 Name name, 2005 TypeSymbol c) { 2006 for (Symbol sym : c.members().getSymbolsByName(name)) { 2007 if (sym.kind == TYP) { 2008 return isAccessible(env, site, sym) 2009 ? sym 2010 : new AccessError(env, site, sym); 2011 } 2012 } 2013 return typeNotFound; 2014 } 2015 2016 /** Find a member type inherited from a superclass or interface. 2017 * @param env The current environment. 2018 * @param site The original type from where the selection takes 2019 * place. 2020 * @param name The type's name. 2021 * @param c The class to search for the member type. This is 2022 * always a superclass or implemented interface of 2023 * site's class. 2024 */ 2025 Symbol findInheritedMemberType(Env<AttrContext> env, 2026 Type site, 2027 Name name, 2028 TypeSymbol c) { 2029 Symbol bestSoFar = typeNotFound; 2030 Symbol sym; 2031 Type st = types.supertype(c.type); 2032 if (st != null && st.hasTag(CLASS)) { 2033 sym = findMemberType(env, site, name, st.tsym); 2034 bestSoFar = bestOf(bestSoFar, sym); 2035 } 2036 for (List<Type> l = types.interfaces(c.type); 2037 bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); 2038 l = l.tail) { 2039 sym = findMemberType(env, site, name, l.head.tsym); 2040 if (!bestSoFar.kind.isResolutionError() && 2041 !sym.kind.isResolutionError() && 2042 sym.owner != bestSoFar.owner) 2043 bestSoFar = new AmbiguityError(bestSoFar, sym); 2044 else 2045 bestSoFar = bestOf(bestSoFar, sym); 2046 } 2047 return bestSoFar; 2048 } 2049 2050 /** Find qualified member type. 2051 * @param env The current environment. 2052 * @param site The original type from where the selection takes 2053 * place. 2054 * @param name The type's name. 2055 * @param c The class to search for the member type. This is 2056 * always a superclass or implemented interface of 2057 * site's class. 2058 */ 2059 Symbol findMemberType(Env<AttrContext> env, 2060 Type site, 2061 Name name, 2062 TypeSymbol c) { 2063 Symbol sym = findImmediateMemberType(env, site, name, c); 2064 2065 if (sym != typeNotFound) 2066 return sym; 2067 2068 return findInheritedMemberType(env, site, name, c); 2069 2070 } 2071 2072 /** Find a global type in given scope and load corresponding class. 2073 * @param env The current environment. 2074 * @param scope The scope in which to look for the type. 2075 * @param name The type's name. 2076 */ 2077 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) { 2078 Symbol bestSoFar = typeNotFound; 2079 for (Symbol s : scope.getSymbolsByName(name)) { 2080 Symbol sym = loadClass(env, s.flatName()); 2081 if (bestSoFar.kind == TYP && sym.kind == TYP && 2082 bestSoFar != sym) 2083 return new AmbiguityError(bestSoFar, sym); 2084 else 2085 bestSoFar = bestOf(bestSoFar, sym); 2086 } 2087 return bestSoFar; 2088 } 2089 2090 Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) { 2091 for (Symbol sym : env.info.scope.getSymbolsByName(name)) { 2092 if (sym.kind == TYP) { 2093 if (staticOnly && 2094 sym.type.hasTag(TYPEVAR) && 2095 sym.owner.kind == TYP) 2096 return new StaticError(sym); 2097 return sym; 2098 } 2099 } 2100 return typeNotFound; 2101 } 2102 2103 /** Find an unqualified type symbol. 2104 * @param env The current environment. 2105 * @param name The type's name. 2106 */ 2107 Symbol findType(Env<AttrContext> env, Name name) { 2108 if (name == names.empty) 2109 return typeNotFound; // do not allow inadvertent "lookup" of anonymous types 2110 Symbol bestSoFar = typeNotFound; 2111 Symbol sym; 2112 boolean staticOnly = false; 2113 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) { 2114 if (isStatic(env1)) staticOnly = true; 2115 // First, look for a type variable and the first member type 2116 final Symbol tyvar = findTypeVar(env1, name, staticOnly); 2117 sym = findImmediateMemberType(env1, env1.enclClass.sym.type, 2118 name, env1.enclClass.sym); 2119 2120 // Return the type variable if we have it, and have no 2121 // immediate member, OR the type variable is for a method. 2122 if (tyvar != typeNotFound) { 2123 if (env.baseClause || sym == typeNotFound || 2124 (tyvar.kind == TYP && tyvar.exists() && 2125 tyvar.owner.kind == MTH)) { 2126 return tyvar; 2127 } 2128 } 2129 2130 // If the environment is a class def, finish up, 2131 // otherwise, do the entire findMemberType 2132 if (sym == typeNotFound) 2133 sym = findInheritedMemberType(env1, env1.enclClass.sym.type, 2134 name, env1.enclClass.sym); 2135 2136 if (staticOnly && sym.kind == TYP && 2137 sym.type.hasTag(CLASS) && 2138 sym.type.getEnclosingType().hasTag(CLASS) && 2139 env1.enclClass.sym.type.isParameterized() && 2140 sym.type.getEnclosingType().isParameterized()) 2141 return new StaticError(sym); 2142 else if (sym.exists()) return sym; 2143 else bestSoFar = bestOf(bestSoFar, sym); 2144 2145 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass; 2146 if ((encl.sym.flags() & STATIC) != 0) 2147 staticOnly = true; 2148 } 2149 2150 if (!env.tree.hasTag(IMPORT)) { 2151 sym = findGlobalType(env, env.toplevel.namedImportScope, name); 2152 if (sym.exists()) return sym; 2153 else bestSoFar = bestOf(bestSoFar, sym); 2154 2155 sym = findGlobalType(env, env.toplevel.packge.members(), name); 2156 if (sym.exists()) return sym; 2157 else bestSoFar = bestOf(bestSoFar, sym); 2158 2159 sym = findGlobalType(env, env.toplevel.starImportScope, name); 2160 if (sym.exists()) return sym; 2161 else bestSoFar = bestOf(bestSoFar, sym); 2162 } 2163 2164 return bestSoFar; 2165 } 2166 2167 /** Find an unqualified identifier which matches a specified kind set. 2168 * @param env The current environment. 2169 * @param name The identifier's name. 2170 * @param kind Indicates the possible symbol kinds 2171 * (a subset of VAL, TYP, PCK). 2172 */ 2173 Symbol findIdent(Env<AttrContext> env, Name name, KindSelector kind) { 2174 Symbol bestSoFar = typeNotFound; 2175 Symbol sym; 2176 2177 if (kind.contains(KindSelector.VAL)) { 2178 sym = findVar(env, name); 2179 if (sym.exists()) return sym; 2180 else bestSoFar = bestOf(bestSoFar, sym); 2181 } 2182 2183 if (kind.contains(KindSelector.TYP)) { 2184 sym = findType(env, name); 2185 2186 if (sym.exists()) return sym; 2187 else bestSoFar = bestOf(bestSoFar, sym); 2188 } 2189 2190 if (kind.contains(KindSelector.PCK)) 2191 return syms.lookupPackage(env.toplevel.modle, name); 2192 else return bestSoFar; 2193 } 2194 2195 /** Find an identifier in a package which matches a specified kind set. 2196 * @param env The current environment. 2197 * @param name The identifier's name. 2198 * @param kind Indicates the possible symbol kinds 2199 * (a nonempty subset of TYP, PCK). 2200 */ 2201 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck, 2202 Name name, KindSelector kind) { 2203 Name fullname = TypeSymbol.formFullName(name, pck); 2204 Symbol bestSoFar = typeNotFound; 2205 PackageSymbol pack = null; 2206 if (kind.contains(KindSelector.PCK)) { 2207 pack = syms.lookupPackage(env.toplevel.modle, fullname); 2208 if (pack.exists()) return pack; 2209 } 2210 if (kind.contains(KindSelector.TYP)) { 2211 Symbol sym = loadClass(env, fullname); 2212 if (sym.exists()) { 2213 // don't allow programs to use flatnames 2214 if (name == sym.name) return sym; 2215 } 2216 else bestSoFar = bestOf(bestSoFar, sym); 2217 } 2218 return (pack != null) ? pack : bestSoFar; 2219 } 2220 2221 /** Find an identifier among the members of a given type `site'. 2222 * @param env The current environment. 2223 * @param site The type containing the symbol to be found. 2224 * @param name The identifier's name. 2225 * @param kind Indicates the possible symbol kinds 2226 * (a subset of VAL, TYP). 2227 */ 2228 Symbol findIdentInType(Env<AttrContext> env, Type site, 2229 Name name, KindSelector kind) { 2230 Symbol bestSoFar = typeNotFound; 2231 Symbol sym; 2232 if (kind.contains(KindSelector.VAL)) { 2233 sym = findField(env, site, name, site.tsym); 2234 if (sym.exists()) return sym; 2235 else bestSoFar = bestOf(bestSoFar, sym); 2236 } 2237 2238 if (kind.contains(KindSelector.TYP)) { 2239 sym = findMemberType(env, site, name, site.tsym); 2240 if (sym.exists()) return sym; 2241 else bestSoFar = bestOf(bestSoFar, sym); 2242 } 2243 return bestSoFar; 2244 } 2245 2246/* *************************************************************************** 2247 * Access checking 2248 * The following methods convert ResolveErrors to ErrorSymbols, issuing 2249 * an error message in the process 2250 ****************************************************************************/ 2251 2252 /** If `sym' is a bad symbol: report error and return errSymbol 2253 * else pass through unchanged, 2254 * additional arguments duplicate what has been used in trying to find the 2255 * symbol {@literal (--> flyweight pattern)}. This improves performance since we 2256 * expect misses to happen frequently. 2257 * 2258 * @param sym The symbol that was found, or a ResolveError. 2259 * @param pos The position to use for error reporting. 2260 * @param location The symbol the served as a context for this lookup 2261 * @param site The original type from where the selection took place. 2262 * @param name The symbol's name. 2263 * @param qualified Did we get here through a qualified expression resolution? 2264 * @param argtypes The invocation's value arguments, 2265 * if we looked for a method. 2266 * @param typeargtypes The invocation's type arguments, 2267 * if we looked for a method. 2268 * @param logResolveHelper helper class used to log resolve errors 2269 */ 2270 Symbol accessInternal(Symbol sym, 2271 DiagnosticPosition pos, 2272 Symbol location, 2273 Type site, 2274 Name name, 2275 boolean qualified, 2276 List<Type> argtypes, 2277 List<Type> typeargtypes, 2278 LogResolveHelper logResolveHelper) { 2279 if (sym.kind.isResolutionError()) { 2280 ResolveError errSym = (ResolveError)sym.baseSymbol(); 2281 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol); 2282 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes); 2283 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) { 2284 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes); 2285 } 2286 } 2287 return sym; 2288 } 2289 2290 /** 2291 * Variant of the generalized access routine, to be used for generating method 2292 * resolution diagnostics 2293 */ 2294 Symbol accessMethod(Symbol sym, 2295 DiagnosticPosition pos, 2296 Symbol location, 2297 Type site, 2298 Name name, 2299 boolean qualified, 2300 List<Type> argtypes, 2301 List<Type> typeargtypes) { 2302 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper); 2303 } 2304 2305 /** Same as original accessMethod(), but without location. 2306 */ 2307 Symbol accessMethod(Symbol sym, 2308 DiagnosticPosition pos, 2309 Type site, 2310 Name name, 2311 boolean qualified, 2312 List<Type> argtypes, 2313 List<Type> typeargtypes) { 2314 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes); 2315 } 2316 2317 /** 2318 * Variant of the generalized access routine, to be used for generating variable, 2319 * type resolution diagnostics 2320 */ 2321 Symbol accessBase(Symbol sym, 2322 DiagnosticPosition pos, 2323 Symbol location, 2324 Type site, 2325 Name name, 2326 boolean qualified) { 2327 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper); 2328 } 2329 2330 /** Same as original accessBase(), but without location. 2331 */ 2332 Symbol accessBase(Symbol sym, 2333 DiagnosticPosition pos, 2334 Type site, 2335 Name name, 2336 boolean qualified) { 2337 return accessBase(sym, pos, site.tsym, site, name, qualified); 2338 } 2339 2340 interface LogResolveHelper { 2341 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes); 2342 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes); 2343 } 2344 2345 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() { 2346 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) { 2347 return !site.isErroneous(); 2348 } 2349 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) { 2350 return argtypes; 2351 } 2352 }; 2353 2354 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() { 2355 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) { 2356 return !site.isErroneous() && 2357 !Type.isErroneous(argtypes) && 2358 (typeargtypes == null || !Type.isErroneous(typeargtypes)); 2359 } 2360 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) { 2361 return argtypes.map(new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step)); 2362 } 2363 }; 2364 2365 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap { 2366 2367 public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) { 2368 deferredAttr.super(mode, msym, step); 2369 } 2370 2371 @Override 2372 protected Type typeOf(DeferredType dt) { 2373 Type res = super.typeOf(dt); 2374 if (!res.isErroneous()) { 2375 switch (TreeInfo.skipParens(dt.tree).getTag()) { 2376 case LAMBDA: 2377 case REFERENCE: 2378 return dt; 2379 case CONDEXPR: 2380 return res == Type.recoveryType ? 2381 dt : res; 2382 } 2383 } 2384 return res; 2385 } 2386 } 2387 2388 /** Check that sym is not an abstract method. 2389 */ 2390 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) { 2391 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0) 2392 log.error(pos, "abstract.cant.be.accessed.directly", 2393 kindName(sym), sym, sym.location()); 2394 } 2395 2396/* *************************************************************************** 2397 * Name resolution 2398 * Naming conventions are as for symbol lookup 2399 * Unlike the find... methods these methods will report access errors 2400 ****************************************************************************/ 2401 2402 /** Resolve an unqualified (non-method) identifier. 2403 * @param pos The position to use for error reporting. 2404 * @param env The environment current at the identifier use. 2405 * @param name The identifier's name. 2406 * @param kind The set of admissible symbol kinds for the identifier. 2407 */ 2408 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env, 2409 Name name, KindSelector kind) { 2410 return accessBase( 2411 findIdent(env, name, kind), 2412 pos, env.enclClass.sym.type, name, false); 2413 } 2414 2415 /** Resolve an unqualified method identifier. 2416 * @param pos The position to use for error reporting. 2417 * @param env The environment current at the method invocation. 2418 * @param name The identifier's name. 2419 * @param argtypes The types of the invocation's value arguments. 2420 * @param typeargtypes The types of the invocation's type arguments. 2421 */ 2422 Symbol resolveMethod(DiagnosticPosition pos, 2423 Env<AttrContext> env, 2424 Name name, 2425 List<Type> argtypes, 2426 List<Type> typeargtypes) { 2427 return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck, 2428 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) { 2429 @Override 2430 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2431 return findFun(env, name, argtypes, typeargtypes, 2432 phase.isBoxingRequired(), 2433 phase.isVarargsRequired()); 2434 }}); 2435 } 2436 2437 /** Resolve a qualified method identifier 2438 * @param pos The position to use for error reporting. 2439 * @param env The environment current at the method invocation. 2440 * @param site The type of the qualifying expression, in which 2441 * identifier is searched. 2442 * @param name The identifier's name. 2443 * @param argtypes The types of the invocation's value arguments. 2444 * @param typeargtypes The types of the invocation's type arguments. 2445 */ 2446 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env, 2447 Type site, Name name, List<Type> argtypes, 2448 List<Type> typeargtypes) { 2449 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes); 2450 } 2451 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env, 2452 Symbol location, Type site, Name name, List<Type> argtypes, 2453 List<Type> typeargtypes) { 2454 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes); 2455 } 2456 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext, 2457 DiagnosticPosition pos, Env<AttrContext> env, 2458 Symbol location, Type site, Name name, List<Type> argtypes, 2459 List<Type> typeargtypes) { 2460 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) { 2461 @Override 2462 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2463 return findMethod(env, site, name, argtypes, typeargtypes, 2464 phase.isBoxingRequired(), 2465 phase.isVarargsRequired()); 2466 } 2467 @Override 2468 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 2469 if (sym.kind.isResolutionError()) { 2470 sym = super.access(env, pos, location, sym); 2471 } else if (allowMethodHandles) { 2472 MethodSymbol msym = (MethodSymbol)sym; 2473 if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) { 2474 return findPolymorphicSignatureInstance(env, sym, argtypes); 2475 } 2476 } 2477 return sym; 2478 } 2479 }); 2480 } 2481 2482 /** Find or create an implicit method of exactly the given type (after erasure). 2483 * Searches in a side table, not the main scope of the site. 2484 * This emulates the lookup process required by JSR 292 in JVM. 2485 * @param env Attribution environment 2486 * @param spMethod signature polymorphic method - i.e. MH.invokeExact 2487 * @param argtypes The required argument types 2488 */ 2489 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, 2490 final Symbol spMethod, 2491 List<Type> argtypes) { 2492 Type mtype = infer.instantiatePolymorphicSignatureInstance(env, 2493 (MethodSymbol)spMethod, currentResolutionContext, argtypes); 2494 for (Symbol sym : polymorphicSignatureScope.getSymbolsByName(spMethod.name)) { 2495 // Check that there is already a method symbol for the method 2496 // type and owner 2497 if (types.isSameType(mtype, sym.type) && 2498 spMethod.owner == sym.owner) { 2499 return sym; 2500 } 2501 } 2502 2503 // Create the desired method 2504 // Retain static modifier is to support invocations to 2505 // MethodHandle.linkTo* methods 2506 long flags = ABSTRACT | HYPOTHETICAL | 2507 spMethod.flags() & (Flags.AccessFlags | Flags.STATIC); 2508 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) { 2509 @Override 2510 public Symbol baseSymbol() { 2511 return spMethod; 2512 } 2513 }; 2514 if (!mtype.isErroneous()) { // Cache only if kosher. 2515 polymorphicSignatureScope.enter(msym); 2516 } 2517 return msym; 2518 } 2519 2520 /** Resolve a qualified method identifier, throw a fatal error if not 2521 * found. 2522 * @param pos The position to use for error reporting. 2523 * @param env The environment current at the method invocation. 2524 * @param site The type of the qualifying expression, in which 2525 * identifier is searched. 2526 * @param name The identifier's name. 2527 * @param argtypes The types of the invocation's value arguments. 2528 * @param typeargtypes The types of the invocation's type arguments. 2529 */ 2530 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env, 2531 Type site, Name name, 2532 List<Type> argtypes, 2533 List<Type> typeargtypes) { 2534 MethodResolutionContext resolveContext = new MethodResolutionContext(); 2535 resolveContext.internalResolution = true; 2536 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym, 2537 site, name, argtypes, typeargtypes); 2538 if (sym.kind == MTH) return (MethodSymbol)sym; 2539 else throw new FatalError( 2540 diags.fragment("fatal.err.cant.locate.meth", 2541 name)); 2542 } 2543 2544 /** Resolve constructor. 2545 * @param pos The position to use for error reporting. 2546 * @param env The environment current at the constructor invocation. 2547 * @param site The type of class for which a constructor is searched. 2548 * @param argtypes The types of the constructor invocation's value 2549 * arguments. 2550 * @param typeargtypes The types of the constructor invocation's type 2551 * arguments. 2552 */ 2553 Symbol resolveConstructor(DiagnosticPosition pos, 2554 Env<AttrContext> env, 2555 Type site, 2556 List<Type> argtypes, 2557 List<Type> typeargtypes) { 2558 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes); 2559 } 2560 2561 private Symbol resolveConstructor(MethodResolutionContext resolveContext, 2562 final DiagnosticPosition pos, 2563 Env<AttrContext> env, 2564 Type site, 2565 List<Type> argtypes, 2566 List<Type> typeargtypes) { 2567 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) { 2568 @Override 2569 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2570 return findConstructor(pos, env, site, argtypes, typeargtypes, 2571 phase.isBoxingRequired(), 2572 phase.isVarargsRequired()); 2573 } 2574 }); 2575 } 2576 2577 /** Resolve a constructor, throw a fatal error if not found. 2578 * @param pos The position to use for error reporting. 2579 * @param env The environment current at the method invocation. 2580 * @param site The type to be constructed. 2581 * @param argtypes The types of the invocation's value arguments. 2582 * @param typeargtypes The types of the invocation's type arguments. 2583 */ 2584 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env, 2585 Type site, 2586 List<Type> argtypes, 2587 List<Type> typeargtypes) { 2588 MethodResolutionContext resolveContext = new MethodResolutionContext(); 2589 resolveContext.internalResolution = true; 2590 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes); 2591 if (sym.kind == MTH) return (MethodSymbol)sym; 2592 else throw new FatalError( 2593 diags.fragment("fatal.err.cant.locate.ctor", site)); 2594 } 2595 2596 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env, 2597 Type site, List<Type> argtypes, 2598 List<Type> typeargtypes, 2599 boolean allowBoxing, 2600 boolean useVarargs) { 2601 Symbol sym = findMethod(env, site, 2602 names.init, argtypes, 2603 typeargtypes, allowBoxing, 2604 useVarargs); 2605 chk.checkDeprecated(pos, env.info.scope.owner, sym); 2606 return sym; 2607 } 2608 2609 /** Resolve constructor using diamond inference. 2610 * @param pos The position to use for error reporting. 2611 * @param env The environment current at the constructor invocation. 2612 * @param site The type of class for which a constructor is searched. 2613 * The scope of this class has been touched in attribution. 2614 * @param argtypes The types of the constructor invocation's value 2615 * arguments. 2616 * @param typeargtypes The types of the constructor invocation's type 2617 * arguments. 2618 */ 2619 Symbol resolveDiamond(DiagnosticPosition pos, 2620 Env<AttrContext> env, 2621 Type site, 2622 List<Type> argtypes, 2623 List<Type> typeargtypes) { 2624 return lookupMethod(env, pos, site.tsym, resolveMethodCheck, 2625 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) { 2626 @Override 2627 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { 2628 return findDiamond(env, site, argtypes, typeargtypes, 2629 phase.isBoxingRequired(), 2630 phase.isVarargsRequired()); 2631 } 2632 @Override 2633 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 2634 if (sym.kind.isResolutionError()) { 2635 if (sym.kind != WRONG_MTH && 2636 sym.kind != WRONG_MTHS) { 2637 sym = super.access(env, pos, location, sym); 2638 } else { 2639 final JCDiagnostic details = sym.kind == WRONG_MTH ? 2640 ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd : 2641 null; 2642 sym = new DiamondError(sym, currentResolutionContext); 2643 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes); 2644 env.info.pendingResolutionPhase = currentResolutionContext.step; 2645 } 2646 } 2647 return sym; 2648 }}); 2649 } 2650 2651 /** This method scans all the constructor symbol in a given class scope - 2652 * assuming that the original scope contains a constructor of the kind: 2653 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo, 2654 * a method check is executed against the modified constructor type: 2655 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond 2656 * inference. The inferred return type of the synthetic constructor IS 2657 * the inferred type for the diamond operator. 2658 */ 2659 private Symbol findDiamond(Env<AttrContext> env, 2660 Type site, 2661 List<Type> argtypes, 2662 List<Type> typeargtypes, 2663 boolean allowBoxing, 2664 boolean useVarargs) { 2665 Symbol bestSoFar = methodNotFound; 2666 TypeSymbol tsym = site.tsym.isInterface() ? syms.objectType.tsym : site.tsym; 2667 for (final Symbol sym : tsym.members().getSymbolsByName(names.init)) { 2668 //- System.out.println(" e " + e.sym); 2669 if (sym.kind == MTH && 2670 (sym.flags_field & SYNTHETIC) == 0) { 2671 List<Type> oldParams = sym.type.hasTag(FORALL) ? 2672 ((ForAll)sym.type).tvars : 2673 List.<Type>nil(); 2674 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams), 2675 types.createMethodTypeWithReturn(sym.type.asMethodType(), site)); 2676 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) { 2677 @Override 2678 public Symbol baseSymbol() { 2679 return sym; 2680 } 2681 }; 2682 bestSoFar = selectBest(env, site, argtypes, typeargtypes, 2683 newConstr, 2684 bestSoFar, 2685 allowBoxing, 2686 useVarargs); 2687 } 2688 } 2689 return bestSoFar; 2690 } 2691 2692 Symbol getMemberReference(DiagnosticPosition pos, 2693 Env<AttrContext> env, 2694 JCMemberReference referenceTree, 2695 Type site, 2696 Name name) { 2697 2698 site = types.capture(site); 2699 2700 ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper( 2701 referenceTree, site, name, List.<Type>nil(), null, VARARITY); 2702 2703 Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup()); 2704 Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym, 2705 nilMethodCheck, lookupHelper); 2706 2707 env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase; 2708 2709 return sym; 2710 } 2711 2712 ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree, 2713 Type site, 2714 Name name, 2715 List<Type> argtypes, 2716 List<Type> typeargtypes, 2717 MethodResolutionPhase maxPhase) { 2718 if (!name.equals(names.init)) { 2719 //method reference 2720 return new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase); 2721 } else if (site.hasTag(ARRAY)) { 2722 //array constructor reference 2723 return new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase); 2724 } else { 2725 //class constructor reference 2726 return new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase); 2727 } 2728 } 2729 2730 /** 2731 * Resolution of member references is typically done as a single 2732 * overload resolution step, where the argument types A are inferred from 2733 * the target functional descriptor. 2734 * 2735 * If the member reference is a method reference with a type qualifier, 2736 * a two-step lookup process is performed. The first step uses the 2737 * expected argument list A, while the second step discards the first 2738 * type from A (which is treated as a receiver type). 2739 * 2740 * There are two cases in which inference is performed: (i) if the member 2741 * reference is a constructor reference and the qualifier type is raw - in 2742 * which case diamond inference is used to infer a parameterization for the 2743 * type qualifier; (ii) if the member reference is an unbound reference 2744 * where the type qualifier is raw - in that case, during the unbound lookup 2745 * the receiver argument type is used to infer an instantiation for the raw 2746 * qualifier type. 2747 * 2748 * When a multi-step resolution process is exploited, the process of picking 2749 * the resulting symbol is delegated to an helper class {@link com.sun.tools.javac.comp.Resolve.ReferenceChooser}. 2750 * 2751 * This routine returns a pair (T,S), where S is the member reference symbol, 2752 * and T is the type of the class in which S is defined. This is necessary as 2753 * the type T might be dynamically inferred (i.e. if constructor reference 2754 * has a raw qualifier). 2755 */ 2756 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env, 2757 JCMemberReference referenceTree, 2758 Type site, 2759 Name name, 2760 List<Type> argtypes, 2761 List<Type> typeargtypes, 2762 MethodCheck methodCheck, 2763 InferenceContext inferenceContext, 2764 ReferenceChooser referenceChooser) { 2765 2766 //step 1 - bound lookup 2767 ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper( 2768 referenceTree, site, name, argtypes, typeargtypes, VARARITY); 2769 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup()); 2770 MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext(); 2771 boundSearchResolveContext.methodCheck = methodCheck; 2772 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), 2773 site.tsym, boundSearchResolveContext, boundLookupHelper); 2774 ReferenceLookupResult boundRes = new ReferenceLookupResult(boundSym, boundSearchResolveContext); 2775 2776 //step 2 - unbound lookup 2777 Symbol unboundSym = methodNotFound; 2778 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup()); 2779 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext); 2780 ReferenceLookupResult unboundRes = referenceNotFound; 2781 if (unboundLookupHelper != null) { 2782 MethodResolutionContext unboundSearchResolveContext = 2783 new MethodResolutionContext(); 2784 unboundSearchResolveContext.methodCheck = methodCheck; 2785 unboundSym = lookupMethod(unboundEnv, env.tree.pos(), 2786 site.tsym, unboundSearchResolveContext, unboundLookupHelper); 2787 unboundRes = new ReferenceLookupResult(unboundSym, unboundSearchResolveContext); 2788 } 2789 2790 //merge results 2791 Pair<Symbol, ReferenceLookupHelper> res; 2792 Symbol bestSym = referenceChooser.result(boundRes, unboundRes); 2793 res = new Pair<>(bestSym, 2794 bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper); 2795 env.info.pendingResolutionPhase = bestSym == unboundSym ? 2796 unboundEnv.info.pendingResolutionPhase : 2797 boundEnv.info.pendingResolutionPhase; 2798 2799 return res; 2800 } 2801 2802 /** 2803 * This class is used to represent a method reference lookup result. It keeps track of two 2804 * things: (i) the symbol found during a method reference lookup and (ii) the static kind 2805 * of the lookup (see {@link com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind}). 2806 */ 2807 static class ReferenceLookupResult { 2808 2809 /** 2810 * Static kind associated with a method reference lookup. Erroneous lookups end up with 2811 * the UNDEFINED kind; successful lookups will end up with either STATIC, NON_STATIC, 2812 * depending on whether all applicable candidates are static or non-static methods, 2813 * respectively. If a successful lookup has both static and non-static applicable methods, 2814 * its kind is set to BOTH. 2815 */ 2816 enum StaticKind { 2817 STATIC, 2818 NON_STATIC, 2819 BOTH, 2820 UNDEFINED; 2821 2822 /** 2823 * Retrieve the static kind associated with a given (method) symbol. 2824 */ 2825 static StaticKind from(Symbol s) { 2826 return s.isStatic() ? 2827 STATIC : NON_STATIC; 2828 } 2829 2830 /** 2831 * Merge two static kinds together. 2832 */ 2833 static StaticKind reduce(StaticKind sk1, StaticKind sk2) { 2834 if (sk1 == UNDEFINED) { 2835 return sk2; 2836 } else if (sk2 == UNDEFINED) { 2837 return sk1; 2838 } else { 2839 return sk1 == sk2 ? sk1 : BOTH; 2840 } 2841 } 2842 } 2843 2844 /** The static kind. */ 2845 StaticKind staticKind; 2846 2847 /** The lookup result. */ 2848 Symbol sym; 2849 2850 ReferenceLookupResult(Symbol sym, MethodResolutionContext resolutionContext) { 2851 this.staticKind = staticKind(sym, resolutionContext); 2852 this.sym = sym; 2853 } 2854 2855 private StaticKind staticKind(Symbol sym, MethodResolutionContext resolutionContext) { 2856 switch (sym.kind) { 2857 case MTH: 2858 case AMBIGUOUS: 2859 return resolutionContext.candidates.stream() 2860 .filter(c -> c.isApplicable() && c.step == resolutionContext.step) 2861 .map(c -> StaticKind.from(c.sym)) 2862 .reduce(StaticKind::reduce) 2863 .orElse(StaticKind.UNDEFINED); 2864 default: 2865 return StaticKind.UNDEFINED; 2866 } 2867 } 2868 2869 /** 2870 * Does this result corresponds to a successful lookup (i.e. one where a method has been found?) 2871 */ 2872 boolean isSuccess() { 2873 return staticKind != StaticKind.UNDEFINED; 2874 } 2875 2876 /** 2877 * Does this result have given static kind? 2878 */ 2879 boolean hasKind(StaticKind sk) { 2880 return this.staticKind == sk; 2881 } 2882 2883 /** 2884 * Error recovery helper: can this lookup result be ignored (for the purpose of returning 2885 * some 'better' result) ? 2886 */ 2887 boolean canIgnore() { 2888 switch (sym.kind) { 2889 case ABSENT_MTH: 2890 return true; 2891 case WRONG_MTH: 2892 InapplicableSymbolError errSym = 2893 (InapplicableSymbolError)sym.baseSymbol(); 2894 return new Template(MethodCheckDiag.ARITY_MISMATCH.regex()) 2895 .matches(errSym.errCandidate().snd); 2896 case WRONG_MTHS: 2897 InapplicableSymbolsError errSyms = 2898 (InapplicableSymbolsError)sym.baseSymbol(); 2899 return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty(); 2900 default: 2901 return false; 2902 } 2903 } 2904 } 2905 2906 /** 2907 * This abstract class embodies the logic that converts one (bound lookup) or two (unbound lookup) 2908 * {@code ReferenceLookupResult} objects into a (@code Symbol), which is then regarded as the 2909 * result of method reference resolution. 2910 */ 2911 abstract class ReferenceChooser { 2912 /** 2913 * Generate a result from a pair of lookup result objects. This method delegates to the 2914 * appropriate result generation routine. 2915 */ 2916 Symbol result(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 2917 return unboundRes != referenceNotFound ? 2918 unboundResult(boundRes, unboundRes) : 2919 boundResult(boundRes); 2920 } 2921 2922 /** 2923 * Generate a symbol from a given bound lookup result. 2924 */ 2925 abstract Symbol boundResult(ReferenceLookupResult boundRes); 2926 2927 /** 2928 * Generate a symbol from a pair of bound/unbound lookup results. 2929 */ 2930 abstract Symbol unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes); 2931 } 2932 2933 /** 2934 * This chooser implements the selection strategy used during a full lookup; this logic 2935 * is described in JLS SE 8 (15.3.2). 2936 */ 2937 ReferenceChooser basicReferenceChooser = new ReferenceChooser() { 2938 2939 @Override 2940 Symbol boundResult(ReferenceLookupResult boundRes) { 2941 return !boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC) ? 2942 boundRes.sym : //the search produces a non-static method 2943 new BadMethodReferenceError(boundRes.sym, false); 2944 } 2945 2946 @Override 2947 Symbol unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 2948 if (boundRes.hasKind(StaticKind.STATIC) && 2949 (!unboundRes.isSuccess() || unboundRes.hasKind(StaticKind.STATIC))) { 2950 //the first search produces a static method and no non-static method is applicable 2951 //during the second search 2952 return boundRes.sym; 2953 } else if (unboundRes.hasKind(StaticKind.NON_STATIC) && 2954 (!boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC))) { 2955 //the second search produces a non-static method and no static method is applicable 2956 //during the first search 2957 return unboundRes.sym; 2958 } else if (boundRes.isSuccess() && unboundRes.isSuccess()) { 2959 //both searches produce some result; ambiguity (error recovery) 2960 return ambiguityError(boundRes.sym, unboundRes.sym); 2961 } else if (boundRes.isSuccess() || unboundRes.isSuccess()) { 2962 //Both searches failed to produce a result with correct staticness (i.e. first search 2963 //produces an non-static method). Alternatively, a given search produced a result 2964 //with the right staticness, but the other search has applicable methods with wrong 2965 //staticness (error recovery) 2966 return new BadMethodReferenceError(boundRes.isSuccess() ? boundRes.sym : unboundRes.sym, true); 2967 } else { 2968 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery) 2969 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ? 2970 unboundRes.sym : boundRes.sym; 2971 } 2972 } 2973 }; 2974 2975 /** 2976 * This chooser implements the selection strategy used during an arity-based lookup; this logic 2977 * is described in JLS SE 8 (15.12.2.1). 2978 */ 2979 ReferenceChooser structuralReferenceChooser = new ReferenceChooser() { 2980 2981 @Override 2982 Symbol boundResult(ReferenceLookupResult boundRes) { 2983 return (!boundRes.isSuccess() || !boundRes.hasKind(StaticKind.STATIC)) ? 2984 boundRes.sym : //the search has at least one applicable non-static method 2985 new BadMethodReferenceError(boundRes.sym, false); 2986 } 2987 2988 @Override 2989 Symbol unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) { 2990 if (boundRes.isSuccess() && !boundRes.hasKind(StaticKind.NON_STATIC)) { 2991 //the first serach has at least one applicable static method 2992 return boundRes.sym; 2993 } else if (unboundRes.isSuccess() && !unboundRes.hasKind(StaticKind.STATIC)) { 2994 //the second search has at least one applicable non-static method 2995 return unboundRes.sym; 2996 } else if (boundRes.isSuccess() || unboundRes.isSuccess()) { 2997 //either the first search produces a non-static method, or second search produces 2998 //a non-static method (error recovery) 2999 return new BadMethodReferenceError(boundRes.isSuccess() ? boundRes.sym : unboundRes.sym, true); 3000 } else { 3001 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery) 3002 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ? 3003 unboundRes.sym : boundRes.sym; 3004 } 3005 } 3006 }; 3007 3008 /** 3009 * Helper for defining custom method-like lookup logic; a lookup helper 3010 * provides hooks for (i) the actual lookup logic and (ii) accessing the 3011 * lookup result (this step might result in compiler diagnostics to be generated) 3012 */ 3013 abstract class LookupHelper { 3014 3015 /** name of the symbol to lookup */ 3016 Name name; 3017 3018 /** location in which the lookup takes place */ 3019 Type site; 3020 3021 /** actual types used during the lookup */ 3022 List<Type> argtypes; 3023 3024 /** type arguments used during the lookup */ 3025 List<Type> typeargtypes; 3026 3027 /** Max overload resolution phase handled by this helper */ 3028 MethodResolutionPhase maxPhase; 3029 3030 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3031 this.name = name; 3032 this.site = site; 3033 this.argtypes = argtypes; 3034 this.typeargtypes = typeargtypes; 3035 this.maxPhase = maxPhase; 3036 } 3037 3038 /** 3039 * Should lookup stop at given phase with given result 3040 */ 3041 final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) { 3042 return phase.ordinal() > maxPhase.ordinal() || 3043 !sym.kind.isResolutionError() || sym.kind == AMBIGUOUS; 3044 } 3045 3046 /** 3047 * Search for a symbol under a given overload resolution phase - this method 3048 * is usually called several times, once per each overload resolution phase 3049 */ 3050 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase); 3051 3052 /** 3053 * Dump overload resolution info 3054 */ 3055 void debug(DiagnosticPosition pos, Symbol sym) { 3056 //do nothing 3057 } 3058 3059 /** 3060 * Validate the result of the lookup 3061 */ 3062 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym); 3063 } 3064 3065 abstract class BasicLookupHelper extends LookupHelper { 3066 3067 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) { 3068 this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY); 3069 } 3070 3071 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3072 super(name, site, argtypes, typeargtypes, maxPhase); 3073 } 3074 3075 @Override 3076 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3077 Symbol sym = doLookup(env, phase); 3078 if (sym.kind == AMBIGUOUS) { 3079 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol(); 3080 sym = a_err.mergeAbstracts(site); 3081 } 3082 return sym; 3083 } 3084 3085 abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase); 3086 3087 @Override 3088 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 3089 if (sym.kind.isResolutionError()) { 3090 //if nothing is found return the 'first' error 3091 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes); 3092 } 3093 return sym; 3094 } 3095 3096 @Override 3097 void debug(DiagnosticPosition pos, Symbol sym) { 3098 reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym); 3099 } 3100 } 3101 3102 /** 3103 * Helper class for member reference lookup. A reference lookup helper 3104 * defines the basic logic for member reference lookup; a method gives 3105 * access to an 'unbound' helper used to perform an unbound member 3106 * reference lookup. 3107 */ 3108 abstract class ReferenceLookupHelper extends LookupHelper { 3109 3110 /** The member reference tree */ 3111 JCMemberReference referenceTree; 3112 3113 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3114 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3115 super(name, site, argtypes, typeargtypes, maxPhase); 3116 this.referenceTree = referenceTree; 3117 } 3118 3119 /** 3120 * Returns an unbound version of this lookup helper. By default, this 3121 * method returns an dummy lookup helper. 3122 */ 3123 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3124 return null; 3125 } 3126 3127 /** 3128 * Get the kind of the member reference 3129 */ 3130 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym); 3131 3132 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) { 3133 if (sym.kind == AMBIGUOUS) { 3134 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol(); 3135 sym = a_err.mergeAbstracts(site); 3136 } 3137 //skip error reporting 3138 return sym; 3139 } 3140 } 3141 3142 /** 3143 * Helper class for method reference lookup. The lookup logic is based 3144 * upon Resolve.findMethod; in certain cases, this helper class has a 3145 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper). 3146 * In such cases, non-static lookup results are thrown away. 3147 */ 3148 class MethodReferenceLookupHelper extends ReferenceLookupHelper { 3149 3150 /** The original method reference lookup site. */ 3151 Type originalSite; 3152 3153 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3154 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3155 super(referenceTree, name, types.skipTypeVars(site, true), argtypes, typeargtypes, maxPhase); 3156 this.originalSite = site; 3157 } 3158 3159 @Override 3160 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3161 return findMethod(env, site, name, argtypes, typeargtypes, 3162 phase.isBoxingRequired(), phase.isVarargsRequired()); 3163 } 3164 3165 @Override 3166 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3167 if (TreeInfo.isStaticSelector(referenceTree.expr, names)) { 3168 if (argtypes.nonEmpty() && 3169 (argtypes.head.hasTag(NONE) || 3170 types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), site))) { 3171 return new UnboundMethodReferenceLookupHelper(referenceTree, name, 3172 originalSite, argtypes, typeargtypes, maxPhase); 3173 } else { 3174 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) { 3175 @Override 3176 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3177 return this; 3178 } 3179 3180 @Override 3181 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3182 return methodNotFound; 3183 } 3184 3185 @Override 3186 ReferenceKind referenceKind(Symbol sym) { 3187 Assert.error(); 3188 return null; 3189 } 3190 }; 3191 } 3192 } else { 3193 return super.unboundLookup(inferenceContext); 3194 } 3195 } 3196 3197 @Override 3198 ReferenceKind referenceKind(Symbol sym) { 3199 if (sym.isStatic()) { 3200 return ReferenceKind.STATIC; 3201 } else { 3202 Name selName = TreeInfo.name(referenceTree.getQualifierExpression()); 3203 return selName != null && selName == names._super ? 3204 ReferenceKind.SUPER : 3205 ReferenceKind.BOUND; 3206 } 3207 } 3208 } 3209 3210 /** 3211 * Helper class for unbound method reference lookup. Essentially the same 3212 * as the basic method reference lookup helper; main difference is that static 3213 * lookup results are thrown away. If qualifier type is raw, an attempt to 3214 * infer a parameterized type is made using the first actual argument (that 3215 * would otherwise be ignored during the lookup). 3216 */ 3217 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper { 3218 3219 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site, 3220 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3221 super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase); 3222 if (site.isRaw() && !argtypes.head.hasTag(NONE)) { 3223 Type asSuperSite = types.asSuper(argtypes.head, site.tsym); 3224 this.site = types.skipTypeVars(asSuperSite, true); 3225 } 3226 } 3227 3228 @Override 3229 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) { 3230 return this; 3231 } 3232 3233 @Override 3234 ReferenceKind referenceKind(Symbol sym) { 3235 return ReferenceKind.UNBOUND; 3236 } 3237 } 3238 3239 /** 3240 * Helper class for array constructor lookup; an array constructor lookup 3241 * is simulated by looking up a method that returns the array type specified 3242 * as qualifier, and that accepts a single int parameter (size of the array). 3243 */ 3244 class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper { 3245 3246 ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes, 3247 List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3248 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase); 3249 } 3250 3251 @Override 3252 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3253 WriteableScope sc = WriteableScope.create(syms.arrayClass); 3254 MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym); 3255 arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass); 3256 sc.enter(arrayConstr); 3257 return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false); 3258 } 3259 3260 @Override 3261 ReferenceKind referenceKind(Symbol sym) { 3262 return ReferenceKind.ARRAY_CTOR; 3263 } 3264 } 3265 3266 /** 3267 * Helper class for constructor reference lookup. The lookup logic is based 3268 * upon either Resolve.findMethod or Resolve.findDiamond - depending on 3269 * whether the constructor reference needs diamond inference (this is the case 3270 * if the qualifier type is raw). A special erroneous symbol is returned 3271 * if the lookup returns the constructor of an inner class and there's no 3272 * enclosing instance in scope. 3273 */ 3274 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper { 3275 3276 boolean needsInference; 3277 3278 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes, 3279 List<Type> typeargtypes, MethodResolutionPhase maxPhase) { 3280 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase); 3281 if (site.isRaw()) { 3282 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym, site.getMetadata()); 3283 needsInference = true; 3284 } 3285 } 3286 3287 @Override 3288 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) { 3289 Symbol sym = needsInference ? 3290 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) : 3291 findMethod(env, site, name, argtypes, typeargtypes, 3292 phase.isBoxingRequired(), phase.isVarargsRequired()); 3293 return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym; 3294 } 3295 3296 @Override 3297 ReferenceKind referenceKind(Symbol sym) { 3298 return site.getEnclosingType().hasTag(NONE) ? 3299 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER; 3300 } 3301 } 3302 3303 /** 3304 * Main overload resolution routine. On each overload resolution step, a 3305 * lookup helper class is used to perform the method/constructor lookup; 3306 * at the end of the lookup, the helper is used to validate the results 3307 * (this last step might trigger overload resolution diagnostics). 3308 */ 3309 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) { 3310 MethodResolutionContext resolveContext = new MethodResolutionContext(); 3311 resolveContext.methodCheck = methodCheck; 3312 return lookupMethod(env, pos, location, resolveContext, lookupHelper); 3313 } 3314 3315 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, 3316 MethodResolutionContext resolveContext, LookupHelper lookupHelper) { 3317 MethodResolutionContext prevResolutionContext = currentResolutionContext; 3318 try { 3319 Symbol bestSoFar = methodNotFound; 3320 currentResolutionContext = resolveContext; 3321 for (MethodResolutionPhase phase : methodResolutionSteps) { 3322 if (lookupHelper.shouldStop(bestSoFar, phase)) 3323 break; 3324 MethodResolutionPhase prevPhase = currentResolutionContext.step; 3325 Symbol prevBest = bestSoFar; 3326 currentResolutionContext.step = phase; 3327 Symbol sym = lookupHelper.lookup(env, phase); 3328 lookupHelper.debug(pos, sym); 3329 bestSoFar = phase.mergeResults(bestSoFar, sym); 3330 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase; 3331 } 3332 return lookupHelper.access(env, pos, location, bestSoFar); 3333 } finally { 3334 currentResolutionContext = prevResolutionContext; 3335 } 3336 } 3337 3338 /** 3339 * Resolve `c.name' where name == this or name == super. 3340 * @param pos The position to use for error reporting. 3341 * @param env The environment current at the expression. 3342 * @param c The qualifier. 3343 * @param name The identifier's name. 3344 */ 3345 Symbol resolveSelf(DiagnosticPosition pos, 3346 Env<AttrContext> env, 3347 TypeSymbol c, 3348 Name name) { 3349 Env<AttrContext> env1 = env; 3350 boolean staticOnly = false; 3351 while (env1.outer != null) { 3352 if (isStatic(env1)) staticOnly = true; 3353 if (env1.enclClass.sym == c) { 3354 Symbol sym = env1.info.scope.findFirst(name); 3355 if (sym != null) { 3356 if (staticOnly) sym = new StaticError(sym); 3357 return accessBase(sym, pos, env.enclClass.sym.type, 3358 name, true); 3359 } 3360 } 3361 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; 3362 env1 = env1.outer; 3363 } 3364 if (c.isInterface() && 3365 name == names._super && !isStatic(env) && 3366 types.isDirectSuperInterface(c, env.enclClass.sym)) { 3367 //this might be a default super call if one of the superinterfaces is 'c' 3368 for (Type t : pruneInterfaces(env.enclClass.type)) { 3369 if (t.tsym == c) { 3370 env.info.defaultSuperCallSite = t; 3371 return new VarSymbol(0, names._super, 3372 types.asSuper(env.enclClass.type, c), env.enclClass.sym); 3373 } 3374 } 3375 //find a direct superinterface that is a subtype of 'c' 3376 for (Type i : types.interfaces(env.enclClass.type)) { 3377 if (i.tsym.isSubClass(c, types) && i.tsym != c) { 3378 log.error(pos, "illegal.default.super.call", c, 3379 diags.fragment("redundant.supertype", c, i)); 3380 return syms.errSymbol; 3381 } 3382 } 3383 Assert.error(); 3384 } 3385 log.error(pos, "not.encl.class", c); 3386 return syms.errSymbol; 3387 } 3388 //where 3389 private List<Type> pruneInterfaces(Type t) { 3390 ListBuffer<Type> result = new ListBuffer<>(); 3391 for (Type t1 : types.interfaces(t)) { 3392 boolean shouldAdd = true; 3393 for (Type t2 : types.interfaces(t)) { 3394 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) { 3395 shouldAdd = false; 3396 } 3397 } 3398 if (shouldAdd) { 3399 result.append(t1); 3400 } 3401 } 3402 return result.toList(); 3403 } 3404 3405 3406 /** 3407 * Resolve `c.this' for an enclosing class c that contains the 3408 * named member. 3409 * @param pos The position to use for error reporting. 3410 * @param env The environment current at the expression. 3411 * @param member The member that must be contained in the result. 3412 */ 3413 Symbol resolveSelfContaining(DiagnosticPosition pos, 3414 Env<AttrContext> env, 3415 Symbol member, 3416 boolean isSuperCall) { 3417 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall); 3418 if (sym == null) { 3419 log.error(pos, "encl.class.required", member); 3420 return syms.errSymbol; 3421 } else { 3422 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true); 3423 } 3424 } 3425 3426 boolean enclosingInstanceMissing(Env<AttrContext> env, Type type) { 3427 if (type.hasTag(CLASS) && type.getEnclosingType().hasTag(CLASS)) { 3428 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false); 3429 return encl == null || encl.kind.isResolutionError(); 3430 } 3431 return false; 3432 } 3433 3434 private Symbol resolveSelfContainingInternal(Env<AttrContext> env, 3435 Symbol member, 3436 boolean isSuperCall) { 3437 Name name = names._this; 3438 Env<AttrContext> env1 = isSuperCall ? env.outer : env; 3439 boolean staticOnly = false; 3440 if (env1 != null) { 3441 while (env1 != null && env1.outer != null) { 3442 if (isStatic(env1)) staticOnly = true; 3443 if (env1.enclClass.sym.isSubClass(member.owner.enclClass(), types)) { 3444 Symbol sym = env1.info.scope.findFirst(name); 3445 if (sym != null) { 3446 if (staticOnly) sym = new StaticError(sym); 3447 return sym; 3448 } 3449 } 3450 if ((env1.enclClass.sym.flags() & STATIC) != 0) 3451 staticOnly = true; 3452 env1 = env1.outer; 3453 } 3454 } 3455 return null; 3456 } 3457 3458 /** 3459 * Resolve an appropriate implicit this instance for t's container. 3460 * JLS 8.8.5.1 and 15.9.2 3461 */ 3462 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) { 3463 return resolveImplicitThis(pos, env, t, false); 3464 } 3465 3466 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) { 3467 Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH) 3468 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this) 3469 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type; 3470 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym) 3471 log.error(pos, "cant.ref.before.ctor.called", "this"); 3472 return thisType; 3473 } 3474 3475/* *************************************************************************** 3476 * ResolveError classes, indicating error situations when accessing symbols 3477 ****************************************************************************/ 3478 3479 //used by TransTypes when checking target type of synthetic cast 3480 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) { 3481 AccessError error = new AccessError(env, env.enclClass.type, type.tsym); 3482 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null); 3483 } 3484 //where 3485 private void logResolveError(ResolveError error, 3486 DiagnosticPosition pos, 3487 Symbol location, 3488 Type site, 3489 Name name, 3490 List<Type> argtypes, 3491 List<Type> typeargtypes) { 3492 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 3493 pos, location, site, name, argtypes, typeargtypes); 3494 if (d != null) { 3495 d.setFlag(DiagnosticFlag.RESOLVE_ERROR); 3496 log.report(d); 3497 } 3498 } 3499 3500 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args"); 3501 3502 public Object methodArguments(List<Type> argtypes) { 3503 if (argtypes == null || argtypes.isEmpty()) { 3504 return noArgs; 3505 } else { 3506 ListBuffer<Object> diagArgs = new ListBuffer<>(); 3507 for (Type t : argtypes) { 3508 if (t.hasTag(DEFERRED)) { 3509 diagArgs.append(((DeferredAttr.DeferredType)t).tree); 3510 } else { 3511 diagArgs.append(t); 3512 } 3513 } 3514 return diagArgs; 3515 } 3516 } 3517 3518 /** 3519 * Root class for resolution errors. Subclass of ResolveError 3520 * represent a different kinds of resolution error - as such they must 3521 * specify how they map into concrete compiler diagnostics. 3522 */ 3523 abstract class ResolveError extends Symbol { 3524 3525 /** The name of the kind of error, for debugging only. */ 3526 final String debugName; 3527 3528 ResolveError(Kind kind, String debugName) { 3529 super(kind, 0, null, null, null); 3530 this.debugName = debugName; 3531 } 3532 3533 @Override @DefinedBy(Api.LANGUAGE_MODEL) 3534 public <R, P> R accept(ElementVisitor<R, P> v, P p) { 3535 throw new AssertionError(); 3536 } 3537 3538 @Override 3539 public String toString() { 3540 return debugName; 3541 } 3542 3543 @Override 3544 public boolean exists() { 3545 return false; 3546 } 3547 3548 @Override 3549 public boolean isStatic() { 3550 return false; 3551 } 3552 3553 /** 3554 * Create an external representation for this erroneous symbol to be 3555 * used during attribution - by default this returns the symbol of a 3556 * brand new error type which stores the original type found 3557 * during resolution. 3558 * 3559 * @param name the name used during resolution 3560 * @param location the location from which the symbol is accessed 3561 */ 3562 protected Symbol access(Name name, TypeSymbol location) { 3563 return types.createErrorType(name, location, syms.errSymbol.type).tsym; 3564 } 3565 3566 /** 3567 * Create a diagnostic representing this resolution error. 3568 * 3569 * @param dkind The kind of the diagnostic to be created (e.g error). 3570 * @param pos The position to be used for error reporting. 3571 * @param site The original type from where the selection took place. 3572 * @param name The name of the symbol to be resolved. 3573 * @param argtypes The invocation's value arguments, 3574 * if we looked for a method. 3575 * @param typeargtypes The invocation's type arguments, 3576 * if we looked for a method. 3577 */ 3578 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3579 DiagnosticPosition pos, 3580 Symbol location, 3581 Type site, 3582 Name name, 3583 List<Type> argtypes, 3584 List<Type> typeargtypes); 3585 } 3586 3587 /** 3588 * This class is the root class of all resolution errors caused by 3589 * an invalid symbol being found during resolution. 3590 */ 3591 abstract class InvalidSymbolError extends ResolveError { 3592 3593 /** The invalid symbol found during resolution */ 3594 Symbol sym; 3595 3596 InvalidSymbolError(Kind kind, Symbol sym, String debugName) { 3597 super(kind, debugName); 3598 this.sym = sym; 3599 } 3600 3601 @Override 3602 public boolean exists() { 3603 return true; 3604 } 3605 3606 @Override 3607 public String toString() { 3608 return super.toString() + " wrongSym=" + sym; 3609 } 3610 3611 @Override 3612 public Symbol access(Name name, TypeSymbol location) { 3613 if (!sym.kind.isResolutionError() && sym.kind.matches(KindSelector.TYP)) 3614 return types.createErrorType(name, location, sym.type).tsym; 3615 else 3616 return sym; 3617 } 3618 } 3619 3620 /** 3621 * InvalidSymbolError error class indicating that a symbol matching a 3622 * given name does not exists in a given site. 3623 */ 3624 class SymbolNotFoundError extends ResolveError { 3625 3626 SymbolNotFoundError(Kind kind) { 3627 this(kind, "symbol not found error"); 3628 } 3629 3630 SymbolNotFoundError(Kind kind, String debugName) { 3631 super(kind, debugName); 3632 } 3633 3634 @Override 3635 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3636 DiagnosticPosition pos, 3637 Symbol location, 3638 Type site, 3639 Name name, 3640 List<Type> argtypes, 3641 List<Type> typeargtypes) { 3642 argtypes = argtypes == null ? List.<Type>nil() : argtypes; 3643 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes; 3644 if (name == names.error) 3645 return null; 3646 3647 boolean hasLocation = false; 3648 if (location == null) { 3649 location = site.tsym; 3650 } 3651 if (!location.name.isEmpty()) { 3652 if (location.kind == PCK && !site.tsym.exists()) { 3653 return diags.create(dkind, log.currentSource(), pos, 3654 "doesnt.exist", location); 3655 } 3656 hasLocation = !location.name.equals(names._this) && 3657 !location.name.equals(names._super); 3658 } 3659 boolean isConstructor = name == names.init; 3660 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind(); 3661 Name idname = isConstructor ? site.tsym.name : name; 3662 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation); 3663 if (hasLocation) { 3664 return diags.create(dkind, log.currentSource(), pos, 3665 errKey, kindname, idname, //symbol kindname, name 3666 typeargtypes, args(argtypes), //type parameters and arguments (if any) 3667 getLocationDiag(location, site)); //location kindname, type 3668 } 3669 else { 3670 return diags.create(dkind, log.currentSource(), pos, 3671 errKey, kindname, idname, //symbol kindname, name 3672 typeargtypes, args(argtypes)); //type parameters and arguments (if any) 3673 } 3674 } 3675 //where 3676 private Object args(List<Type> args) { 3677 return args.isEmpty() ? args : methodArguments(args); 3678 } 3679 3680 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) { 3681 String key = "cant.resolve"; 3682 String suffix = hasLocation ? ".location" : ""; 3683 switch (kindname) { 3684 case METHOD: 3685 case CONSTRUCTOR: { 3686 suffix += ".args"; 3687 suffix += hasTypeArgs ? ".params" : ""; 3688 } 3689 } 3690 return key + suffix; 3691 } 3692 private JCDiagnostic getLocationDiag(Symbol location, Type site) { 3693 if (location.kind == VAR) { 3694 return diags.fragment("location.1", 3695 kindName(location), 3696 location, 3697 location.type); 3698 } else { 3699 return diags.fragment("location", 3700 typeKindName(site), 3701 site, 3702 null); 3703 } 3704 } 3705 } 3706 3707 /** 3708 * InvalidSymbolError error class indicating that a given symbol 3709 * (either a method, a constructor or an operand) is not applicable 3710 * given an actual arguments/type argument list. 3711 */ 3712 class InapplicableSymbolError extends ResolveError { 3713 3714 protected MethodResolutionContext resolveContext; 3715 3716 InapplicableSymbolError(MethodResolutionContext context) { 3717 this(WRONG_MTH, "inapplicable symbol error", context); 3718 } 3719 3720 protected InapplicableSymbolError(Kind kind, String debugName, MethodResolutionContext context) { 3721 super(kind, debugName); 3722 this.resolveContext = context; 3723 } 3724 3725 @Override 3726 public String toString() { 3727 return super.toString(); 3728 } 3729 3730 @Override 3731 public boolean exists() { 3732 return true; 3733 } 3734 3735 @Override 3736 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3737 DiagnosticPosition pos, 3738 Symbol location, 3739 Type site, 3740 Name name, 3741 List<Type> argtypes, 3742 List<Type> typeargtypes) { 3743 if (name == names.error) 3744 return null; 3745 3746 Pair<Symbol, JCDiagnostic> c = errCandidate(); 3747 if (compactMethodDiags) { 3748 JCDiagnostic simpleDiag = 3749 MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd); 3750 if (simpleDiag != null) { 3751 return simpleDiag; 3752 } 3753 } 3754 Symbol ws = c.fst.asMemberOf(site, types); 3755 return diags.create(dkind, log.currentSource(), pos, 3756 "cant.apply.symbol", 3757 kindName(ws), 3758 ws.name == names.init ? ws.owner.name : ws.name, 3759 methodArguments(ws.type.getParameterTypes()), 3760 methodArguments(argtypes), 3761 kindName(ws.owner), 3762 ws.owner.type, 3763 c.snd); 3764 } 3765 3766 @Override 3767 public Symbol access(Name name, TypeSymbol location) { 3768 return types.createErrorType(name, location, syms.errSymbol.type).tsym; 3769 } 3770 3771 protected Pair<Symbol, JCDiagnostic> errCandidate() { 3772 Candidate bestSoFar = null; 3773 for (Candidate c : resolveContext.candidates) { 3774 if (c.isApplicable()) continue; 3775 bestSoFar = c; 3776 } 3777 Assert.checkNonNull(bestSoFar); 3778 return new Pair<>(bestSoFar.sym, bestSoFar.details); 3779 } 3780 } 3781 3782 /** 3783 * ResolveError error class indicating that a symbol (either methods, constructors or operand) 3784 * is not applicable given an actual arguments/type argument list. 3785 */ 3786 class InapplicableSymbolsError extends InapplicableSymbolError { 3787 3788 InapplicableSymbolsError(MethodResolutionContext context) { 3789 super(WRONG_MTHS, "inapplicable symbols", context); 3790 } 3791 3792 @Override 3793 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3794 DiagnosticPosition pos, 3795 Symbol location, 3796 Type site, 3797 Name name, 3798 List<Type> argtypes, 3799 List<Type> typeargtypes) { 3800 Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates(); 3801 Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ? 3802 filterCandidates(candidatesMap) : 3803 mapCandidates(); 3804 if (filteredCandidates.isEmpty()) { 3805 filteredCandidates = candidatesMap; 3806 } 3807 boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size(); 3808 if (filteredCandidates.size() > 1) { 3809 JCDiagnostic err = diags.create(dkind, 3810 null, 3811 truncatedDiag ? 3812 EnumSet.of(DiagnosticFlag.COMPRESSED) : 3813 EnumSet.noneOf(DiagnosticFlag.class), 3814 log.currentSource(), 3815 pos, 3816 "cant.apply.symbols", 3817 name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(), 3818 name == names.init ? site.tsym.name : name, 3819 methodArguments(argtypes)); 3820 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site)); 3821 } else if (filteredCandidates.size() == 1) { 3822 Map.Entry<Symbol, JCDiagnostic> _e = 3823 filteredCandidates.entrySet().iterator().next(); 3824 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue()); 3825 JCDiagnostic d = new InapplicableSymbolError(resolveContext) { 3826 @Override 3827 protected Pair<Symbol, JCDiagnostic> errCandidate() { 3828 return p; 3829 } 3830 }.getDiagnostic(dkind, pos, 3831 location, site, name, argtypes, typeargtypes); 3832 if (truncatedDiag) { 3833 d.setFlag(DiagnosticFlag.COMPRESSED); 3834 } 3835 return d; 3836 } else { 3837 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos, 3838 location, site, name, argtypes, typeargtypes); 3839 } 3840 } 3841 //where 3842 private Map<Symbol, JCDiagnostic> mapCandidates() { 3843 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>(); 3844 for (Candidate c : resolveContext.candidates) { 3845 if (c.isApplicable()) continue; 3846 candidates.put(c.sym, c.details); 3847 } 3848 return candidates; 3849 } 3850 3851 Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) { 3852 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>(); 3853 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) { 3854 JCDiagnostic d = _entry.getValue(); 3855 if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) { 3856 candidates.put(_entry.getKey(), d); 3857 } 3858 } 3859 return candidates; 3860 } 3861 3862 private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) { 3863 List<JCDiagnostic> details = List.nil(); 3864 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) { 3865 Symbol sym = _entry.getKey(); 3866 JCDiagnostic detailDiag = diags.fragment("inapplicable.method", 3867 Kinds.kindName(sym), 3868 sym.location(site, types), 3869 sym.asMemberOf(site, types), 3870 _entry.getValue()); 3871 details = details.prepend(detailDiag); 3872 } 3873 //typically members are visited in reverse order (see Scope) 3874 //so we need to reverse the candidate list so that candidates 3875 //conform to source order 3876 return details; 3877 } 3878 } 3879 3880 /** 3881 * DiamondError error class indicating that a constructor symbol is not applicable 3882 * given an actual arguments/type argument list using diamond inference. 3883 */ 3884 class DiamondError extends InapplicableSymbolError { 3885 3886 Symbol sym; 3887 3888 public DiamondError(Symbol sym, MethodResolutionContext context) { 3889 super(sym.kind, "diamondError", context); 3890 this.sym = sym; 3891 } 3892 3893 JCDiagnostic getDetails() { 3894 return (sym.kind == WRONG_MTH) ? 3895 ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd : 3896 null; 3897 } 3898 3899 @Override 3900 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, 3901 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 3902 JCDiagnostic details = getDetails(); 3903 if (details != null && compactMethodDiags) { 3904 JCDiagnostic simpleDiag = 3905 MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, details); 3906 if (simpleDiag != null) { 3907 return simpleDiag; 3908 } 3909 } 3910 String key = details == null ? 3911 "cant.apply.diamond" : 3912 "cant.apply.diamond.1"; 3913 return diags.create(dkind, log.currentSource(), pos, key, 3914 diags.fragment("diamond", site.tsym), details); 3915 } 3916 } 3917 3918 /** 3919 * An InvalidSymbolError error class indicating that a symbol is not 3920 * accessible from a given site 3921 */ 3922 class AccessError extends InvalidSymbolError { 3923 3924 private Env<AttrContext> env; 3925 private Type site; 3926 3927 AccessError(Symbol sym) { 3928 this(null, null, sym); 3929 } 3930 3931 AccessError(Env<AttrContext> env, Type site, Symbol sym) { 3932 super(HIDDEN, sym, "access error"); 3933 this.env = env; 3934 this.site = site; 3935 } 3936 3937 @Override 3938 public boolean exists() { 3939 return false; 3940 } 3941 3942 @Override 3943 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 3944 DiagnosticPosition pos, 3945 Symbol location, 3946 Type site, 3947 Name name, 3948 List<Type> argtypes, 3949 List<Type> typeargtypes) { 3950 if (sym.owner.type.hasTag(ERROR)) 3951 return null; 3952 3953 if (sym.name == names.init && sym.owner != site.tsym) { 3954 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, 3955 pos, location, site, name, argtypes, typeargtypes); 3956 } 3957 else if ((sym.flags() & PUBLIC) != 0 3958 || (env != null && this.site != null 3959 && !isAccessible(env, this.site))) { 3960 if (sym.owner.kind == PCK) { 3961 return diags.create(dkind, log.currentSource(), 3962 pos, "not.def.access.package.cant.access", 3963 sym, sym.location()); 3964 } else { 3965 return diags.create(dkind, log.currentSource(), 3966 pos, "not.def.access.class.intf.cant.access", 3967 sym, sym.location()); 3968 } 3969 } 3970 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) { 3971 return diags.create(dkind, log.currentSource(), 3972 pos, "report.access", sym, 3973 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)), 3974 sym.location()); 3975 } 3976 else { 3977 return diags.create(dkind, log.currentSource(), 3978 pos, "not.def.public.cant.access", sym, sym.location()); 3979 } 3980 } 3981 3982 private String toString(Type type) { 3983 StringBuilder sb = new StringBuilder(); 3984 sb.append(type); 3985 if (type != null) { 3986 sb.append("[tsym:").append(type.tsym); 3987 if (type.tsym != null) 3988 sb.append("packge:").append(type.tsym.packge()); 3989 sb.append("]"); 3990 } 3991 return sb.toString(); 3992 } 3993 } 3994 3995 /** 3996 * InvalidSymbolError error class indicating that an instance member 3997 * has erroneously been accessed from a static context. 3998 */ 3999 class StaticError extends InvalidSymbolError { 4000 4001 StaticError(Symbol sym) { 4002 super(STATICERR, sym, "static error"); 4003 } 4004 4005 @Override 4006 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4007 DiagnosticPosition pos, 4008 Symbol location, 4009 Type site, 4010 Name name, 4011 List<Type> argtypes, 4012 List<Type> typeargtypes) { 4013 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS)) 4014 ? types.erasure(sym.type).tsym 4015 : sym); 4016 return diags.create(dkind, log.currentSource(), pos, 4017 "non-static.cant.be.ref", kindName(sym), errSym); 4018 } 4019 } 4020 4021 /** 4022 * InvalidSymbolError error class indicating that a pair of symbols 4023 * (either methods, constructors or operands) are ambiguous 4024 * given an actual arguments/type argument list. 4025 */ 4026 class AmbiguityError extends ResolveError { 4027 4028 /** The other maximally specific symbol */ 4029 List<Symbol> ambiguousSyms = List.nil(); 4030 4031 @Override 4032 public boolean exists() { 4033 return true; 4034 } 4035 4036 AmbiguityError(Symbol sym1, Symbol sym2) { 4037 super(AMBIGUOUS, "ambiguity error"); 4038 ambiguousSyms = flatten(sym2).appendList(flatten(sym1)); 4039 } 4040 4041 private List<Symbol> flatten(Symbol sym) { 4042 if (sym.kind == AMBIGUOUS) { 4043 return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms; 4044 } else { 4045 return List.of(sym); 4046 } 4047 } 4048 4049 AmbiguityError addAmbiguousSymbol(Symbol s) { 4050 ambiguousSyms = ambiguousSyms.prepend(s); 4051 return this; 4052 } 4053 4054 @Override 4055 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, 4056 DiagnosticPosition pos, 4057 Symbol location, 4058 Type site, 4059 Name name, 4060 List<Type> argtypes, 4061 List<Type> typeargtypes) { 4062 List<Symbol> diagSyms = ambiguousSyms.reverse(); 4063 Symbol s1 = diagSyms.head; 4064 Symbol s2 = diagSyms.tail.head; 4065 Name sname = s1.name; 4066 if (sname == names.init) sname = s1.owner.name; 4067 return diags.create(dkind, log.currentSource(), 4068 pos, "ref.ambiguous", sname, 4069 kindName(s1), 4070 s1, 4071 s1.location(site, types), 4072 kindName(s2), 4073 s2, 4074 s2.location(site, types)); 4075 } 4076 4077 /** 4078 * If multiple applicable methods are found during overload and none of them 4079 * is more specific than the others, attempt to merge their signatures. 4080 */ 4081 Symbol mergeAbstracts(Type site) { 4082 List<Symbol> ambiguousInOrder = ambiguousSyms.reverse(); 4083 for (Symbol s : ambiguousInOrder) { 4084 Type mt = types.memberType(site, s); 4085 boolean found = true; 4086 List<Type> allThrown = mt.getThrownTypes(); 4087 for (Symbol s2 : ambiguousInOrder) { 4088 Type mt2 = types.memberType(site, s2); 4089 if ((s2.flags() & ABSTRACT) == 0 || 4090 !types.overrideEquivalent(mt, mt2) || 4091 !types.isSameTypes(s.erasure(types).getParameterTypes(), 4092 s2.erasure(types).getParameterTypes())) { 4093 //ambiguity cannot be resolved 4094 return this; 4095 } 4096 Type mst = mostSpecificReturnType(mt, mt2); 4097 if (mst == null || mst != mt) { 4098 found = false; 4099 break; 4100 } 4101 List<Type> thrownTypes2 = mt2.getThrownTypes(); 4102 if (mt.hasTag(FORALL) && mt2.hasTag(FORALL)) { 4103 // if both are generic methods, adjust thrown types ahead of intersection computation 4104 thrownTypes2 = types.subst(thrownTypes2, mt2.getTypeArguments(), mt.getTypeArguments()); 4105 } 4106 allThrown = chk.intersect(allThrown, thrownTypes2); 4107 } 4108 if (found) { 4109 //all ambiguous methods were abstract and one method had 4110 //most specific return type then others 4111 return (allThrown == mt.getThrownTypes()) ? 4112 s : new MethodSymbol( 4113 s.flags(), 4114 s.name, 4115 types.createMethodTypeWithThrown(s.type, allThrown), 4116 s.owner); 4117 } 4118 } 4119 return this; 4120 } 4121 4122 @Override 4123 protected Symbol access(Name name, TypeSymbol location) { 4124 Symbol firstAmbiguity = ambiguousSyms.last(); 4125 return firstAmbiguity.kind == TYP ? 4126 types.createErrorType(name, location, firstAmbiguity.type).tsym : 4127 firstAmbiguity; 4128 } 4129 } 4130 4131 class BadVarargsMethod extends ResolveError { 4132 4133 ResolveError delegatedError; 4134 4135 BadVarargsMethod(ResolveError delegatedError) { 4136 super(delegatedError.kind, "badVarargs"); 4137 this.delegatedError = delegatedError; 4138 } 4139 4140 @Override 4141 public Symbol baseSymbol() { 4142 return delegatedError.baseSymbol(); 4143 } 4144 4145 @Override 4146 protected Symbol access(Name name, TypeSymbol location) { 4147 return delegatedError.access(name, location); 4148 } 4149 4150 @Override 4151 public boolean exists() { 4152 return true; 4153 } 4154 4155 @Override 4156 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4157 return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes); 4158 } 4159 } 4160 4161 /** 4162 * BadMethodReferenceError error class indicating that a method reference symbol has been found, 4163 * but with the wrong staticness. 4164 */ 4165 class BadMethodReferenceError extends StaticError { 4166 4167 boolean unboundLookup; 4168 4169 public BadMethodReferenceError(Symbol sym, boolean unboundLookup) { 4170 super(sym); 4171 this.unboundLookup = unboundLookup; 4172 } 4173 4174 @Override 4175 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4176 final String key; 4177 if (!unboundLookup) { 4178 key = "bad.static.method.in.bound.lookup"; 4179 } else if (sym.isStatic()) { 4180 key = "bad.static.method.in.unbound.lookup"; 4181 } else { 4182 key = "bad.instance.method.in.unbound.lookup"; 4183 } 4184 return sym.kind.isResolutionError() ? 4185 ((ResolveError)sym).getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes) : 4186 diags.create(dkind, log.currentSource(), pos, key, Kinds.kindName(sym), sym); 4187 } 4188 } 4189 4190 /** 4191 * BadConstructorReferenceError error class indicating that a constructor reference symbol has been found, 4192 * but pointing to a class for which an enclosing instance is not available. 4193 */ 4194 class BadConstructorReferenceError extends InvalidSymbolError { 4195 4196 public BadConstructorReferenceError(Symbol sym) { 4197 super(MISSING_ENCL, sym, "BadConstructorReferenceError"); 4198 } 4199 4200 @Override 4201 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { 4202 return diags.create(dkind, log.currentSource(), pos, 4203 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType()); 4204 } 4205 } 4206 4207 /** 4208 * Helper class for method resolution diagnostic simplification. 4209 * Certain resolution diagnostic are rewritten as simpler diagnostic 4210 * where the enclosing resolution diagnostic (i.e. 'inapplicable method') 4211 * is stripped away, as it doesn't carry additional info. The logic 4212 * for matching a given diagnostic is given in terms of a template 4213 * hierarchy: a diagnostic template can be specified programmatically, 4214 * so that only certain diagnostics are matched. Each templete is then 4215 * associated with a rewriter object that carries out the task of rewtiting 4216 * the diagnostic to a simpler one. 4217 */ 4218 static class MethodResolutionDiagHelper { 4219 4220 /** 4221 * A diagnostic rewriter transforms a method resolution diagnostic 4222 * into a simpler one 4223 */ 4224 interface DiagnosticRewriter { 4225 JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags, 4226 DiagnosticPosition preferedPos, DiagnosticSource preferredSource, 4227 DiagnosticType preferredKind, JCDiagnostic d); 4228 } 4229 4230 /** 4231 * A diagnostic template is made up of two ingredients: (i) a regular 4232 * expression for matching a diagnostic key and (ii) a list of sub-templates 4233 * for matching diagnostic arguments. 4234 */ 4235 static class Template { 4236 4237 /** regex used to match diag key */ 4238 String regex; 4239 4240 /** templates used to match diagnostic args */ 4241 Template[] subTemplates; 4242 4243 Template(String key, Template... subTemplates) { 4244 this.regex = key; 4245 this.subTemplates = subTemplates; 4246 } 4247 4248 /** 4249 * Returns true if the regex matches the diagnostic key and if 4250 * all diagnostic arguments are matches by corresponding sub-templates. 4251 */ 4252 boolean matches(Object o) { 4253 JCDiagnostic d = (JCDiagnostic)o; 4254 Object[] args = d.getArgs(); 4255 if (!d.getCode().matches(regex) || 4256 subTemplates.length != d.getArgs().length) { 4257 return false; 4258 } 4259 for (int i = 0; i < args.length ; i++) { 4260 if (!subTemplates[i].matches(args[i])) { 4261 return false; 4262 } 4263 } 4264 return true; 4265 } 4266 } 4267 4268 /** 4269 * Common rewriter for all argument mismatch simplifications. 4270 */ 4271 static class ArgMismatchRewriter implements DiagnosticRewriter { 4272 4273 /** the index of the subdiagnostic to be used as primary. */ 4274 int causeIndex; 4275 4276 public ArgMismatchRewriter(int causeIndex) { 4277 this.causeIndex = causeIndex; 4278 } 4279 4280 @Override 4281 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags, 4282 DiagnosticPosition preferedPos, DiagnosticSource preferredSource, 4283 DiagnosticType preferredKind, JCDiagnostic d) { 4284 JCDiagnostic cause = (JCDiagnostic)d.getArgs()[causeIndex]; 4285 DiagnosticPosition pos = d.getDiagnosticPosition(); 4286 if (pos == null) { 4287 pos = preferedPos; 4288 } 4289 return diags.create(preferredKind, preferredSource, pos, 4290 "prob.found.req", cause); 4291 } 4292 } 4293 4294 /** a dummy template that match any diagnostic argument */ 4295 static final Template skip = new Template("") { 4296 @Override 4297 boolean matches(Object d) { 4298 return true; 4299 } 4300 }; 4301 4302 /** template for matching inference-free arguments mismatch failures */ 4303 static final Template argMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip); 4304 4305 /** template for matching inference related arguments mismatch failures */ 4306 static final Template inferArgMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip, skip) { 4307 @Override 4308 boolean matches(Object o) { 4309 if (!super.matches(o)) { 4310 return false; 4311 } 4312 JCDiagnostic d = (JCDiagnostic)o; 4313 @SuppressWarnings("unchecked") 4314 List<Type> tvars = (List<Type>)d.getArgs()[0]; 4315 return !containsAny(d, tvars); 4316 } 4317 4318 BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> { 4319 if (o instanceof Type) { 4320 return ((Type)o).containsAny(ts); 4321 } else if (o instanceof JCDiagnostic) { 4322 return containsAny((JCDiagnostic)o, ts); 4323 } else { 4324 return false; 4325 } 4326 }; 4327 4328 boolean containsAny(JCDiagnostic d, List<Type> ts) { 4329 return Stream.of(d.getArgs()) 4330 .anyMatch(o -> containsPredicate.test(o, ts)); 4331 } 4332 }; 4333 4334 /** rewriter map used for method resolution simplification */ 4335 static final Map<Template, DiagnosticRewriter> rewriters = new LinkedHashMap<>(); 4336 4337 static { 4338 rewriters.put(argMismatchTemplate, new ArgMismatchRewriter(0)); 4339 rewriters.put(inferArgMismatchTemplate, new ArgMismatchRewriter(1)); 4340 } 4341 4342 /** 4343 * Main entry point for diagnostic rewriting - given a diagnostic, see if any templates matches it, 4344 * and rewrite it accordingly. 4345 */ 4346 static JCDiagnostic rewrite(JCDiagnostic.Factory diags, DiagnosticPosition pos, DiagnosticSource source, 4347 DiagnosticType dkind, JCDiagnostic d) { 4348 for (Map.Entry<Template, DiagnosticRewriter> _entry : rewriters.entrySet()) { 4349 if (_entry.getKey().matches(d)) { 4350 JCDiagnostic simpleDiag = 4351 _entry.getValue().rewriteDiagnostic(diags, pos, source, dkind, d); 4352 simpleDiag.setFlag(DiagnosticFlag.COMPRESSED); 4353 return simpleDiag; 4354 } 4355 } 4356 return null; 4357 } 4358 } 4359 4360 enum MethodResolutionPhase { 4361 BASIC(false, false), 4362 BOX(true, false), 4363 VARARITY(true, true) { 4364 @Override 4365 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) { 4366 //Check invariants (see {@code LookupHelper.shouldStop}) 4367 Assert.check(bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS); 4368 if (!sym.kind.isResolutionError()) { 4369 //varargs resolution successful 4370 return sym; 4371 } else { 4372 //pick best error 4373 switch (bestSoFar.kind) { 4374 case WRONG_MTH: 4375 case WRONG_MTHS: 4376 //Override previous errors if they were caused by argument mismatch. 4377 //This generally means preferring current symbols - but we need to pay 4378 //attention to the fact that the varargs lookup returns 'less' candidates 4379 //than the previous rounds, and adjust that accordingly. 4380 switch (sym.kind) { 4381 case WRONG_MTH: 4382 //if the previous round matched more than one method, return that 4383 //result instead 4384 return bestSoFar.kind == WRONG_MTHS ? 4385 bestSoFar : sym; 4386 case ABSENT_MTH: 4387 //do not override erroneous symbol if the arity lookup did not 4388 //match any method 4389 return bestSoFar; 4390 case WRONG_MTHS: 4391 default: 4392 //safe to override 4393 return sym; 4394 } 4395 default: 4396 //otherwise, return first error 4397 return bestSoFar; 4398 } 4399 } 4400 } 4401 }; 4402 4403 final boolean isBoxingRequired; 4404 final boolean isVarargsRequired; 4405 4406 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) { 4407 this.isBoxingRequired = isBoxingRequired; 4408 this.isVarargsRequired = isVarargsRequired; 4409 } 4410 4411 public boolean isBoxingRequired() { 4412 return isBoxingRequired; 4413 } 4414 4415 public boolean isVarargsRequired() { 4416 return isVarargsRequired; 4417 } 4418 4419 public Symbol mergeResults(Symbol prev, Symbol sym) { 4420 return sym; 4421 } 4422 } 4423 4424 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY); 4425 4426 /** 4427 * A resolution context is used to keep track of intermediate results of 4428 * overload resolution, such as list of method that are not applicable 4429 * (used to generate more precise diagnostics) and so on. Resolution contexts 4430 * can be nested - this means that when each overload resolution routine should 4431 * work within the resolution context it created. 4432 */ 4433 class MethodResolutionContext { 4434 4435 private List<Candidate> candidates = List.nil(); 4436 4437 MethodResolutionPhase step = null; 4438 4439 MethodCheck methodCheck = resolveMethodCheck; 4440 4441 private boolean internalResolution = false; 4442 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE; 4443 4444 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) { 4445 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null); 4446 candidates = candidates.append(c); 4447 } 4448 4449 void addApplicableCandidate(Symbol sym, Type mtype) { 4450 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype); 4451 candidates = candidates.append(c); 4452 } 4453 4454 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) { 4455 DeferredAttrContext parent = (pendingResult == null) 4456 ? deferredAttr.emptyDeferredAttrContext 4457 : pendingResult.checkContext.deferredAttrContext(); 4458 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, 4459 inferenceContext, parent, warn); 4460 } 4461 4462 /** 4463 * This class represents an overload resolution candidate. There are two 4464 * kinds of candidates: applicable methods and inapplicable methods; 4465 * applicable methods have a pointer to the instantiated method type, 4466 * while inapplicable candidates contain further details about the 4467 * reason why the method has been considered inapplicable. 4468 */ 4469 @SuppressWarnings("overrides") 4470 class Candidate { 4471 4472 final MethodResolutionPhase step; 4473 final Symbol sym; 4474 final JCDiagnostic details; 4475 final Type mtype; 4476 4477 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) { 4478 this.step = step; 4479 this.sym = sym; 4480 this.details = details; 4481 this.mtype = mtype; 4482 } 4483 4484 @Override 4485 public boolean equals(Object o) { 4486 if (o instanceof Candidate) { 4487 Symbol s1 = this.sym; 4488 Symbol s2 = ((Candidate)o).sym; 4489 if ((s1 != s2 && 4490 (s1.overrides(s2, s1.owner.type.tsym, types, false) || 4491 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) || 4492 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner)) 4493 return true; 4494 } 4495 return false; 4496 } 4497 4498 boolean isApplicable() { 4499 return mtype != null; 4500 } 4501 } 4502 4503 DeferredAttr.AttrMode attrMode() { 4504 return attrMode; 4505 } 4506 4507 boolean internal() { 4508 return internalResolution; 4509 } 4510 } 4511 4512 MethodResolutionContext currentResolutionContext = null; 4513} 4514