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