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