Mon, 03 Jun 2013 17:09:26 -0700
8006615: [doclint] move remaining messages into resource bundle
Reviewed-by: mcimadamore, vromero
1 /*
2 * Copyright (c) 1999, 2013, 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.tools.javac.api.Formattable.LocalizedString;
29 import com.sun.tools.javac.code.*;
30 import com.sun.tools.javac.code.Symbol.*;
31 import com.sun.tools.javac.code.Type.*;
32 import com.sun.tools.javac.comp.Attr.ResultInfo;
33 import com.sun.tools.javac.comp.Check.CheckContext;
34 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
35 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
36 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
37 import com.sun.tools.javac.comp.Infer.InferenceContext;
38 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
40 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.DiagnosticRewriter;
41 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
42 import com.sun.tools.javac.jvm.*;
43 import com.sun.tools.javac.main.Option;
44 import com.sun.tools.javac.tree.*;
45 import com.sun.tools.javac.tree.JCTree.*;
46 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
47 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
48 import com.sun.tools.javac.util.*;
49 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
51 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.EnumMap;
56 import java.util.EnumSet;
57 import java.util.Iterator;
58 import java.util.LinkedHashMap;
59 import java.util.LinkedHashSet;
60 import java.util.Map;
62 import javax.lang.model.element.ElementVisitor;
64 import static com.sun.tools.javac.code.Flags.*;
65 import static com.sun.tools.javac.code.Flags.BLOCK;
66 import static com.sun.tools.javac.code.Kinds.*;
67 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
68 import static com.sun.tools.javac.code.TypeTag.*;
69 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
70 import static com.sun.tools.javac.tree.JCTree.Tag.*;
72 /** Helper class for name resolution, used mostly by the attribution phase.
73 *
74 * <p><b>This is NOT part of any supported API.
75 * If you write code that depends on this, you do so at your own risk.
76 * This code and its internal interfaces are subject to change or
77 * deletion without notice.</b>
78 */
79 public class Resolve {
80 protected static final Context.Key<Resolve> resolveKey =
81 new Context.Key<Resolve>();
83 Names names;
84 Log log;
85 Symtab syms;
86 Attr attr;
87 DeferredAttr deferredAttr;
88 Check chk;
89 Infer infer;
90 ClassReader reader;
91 TreeInfo treeinfo;
92 Types types;
93 JCDiagnostic.Factory diags;
94 public final boolean boxingEnabled; // = source.allowBoxing();
95 public final boolean varargsEnabled; // = source.allowVarargs();
96 public final boolean allowMethodHandles;
97 public final boolean allowDefaultMethods;
98 public final boolean allowStructuralMostSpecific;
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 typeNotFound = new
114 SymbolNotFoundError(ABSENT_TYP);
116 names = Names.instance(context);
117 log = Log.instance(context);
118 attr = Attr.instance(context);
119 deferredAttr = DeferredAttr.instance(context);
120 chk = Check.instance(context);
121 infer = Infer.instance(context);
122 reader = ClassReader.instance(context);
123 treeinfo = TreeInfo.instance(context);
124 types = Types.instance(context);
125 diags = JCDiagnostic.Factory.instance(context);
126 Source source = Source.instance(context);
127 boxingEnabled = source.allowBoxing();
128 varargsEnabled = source.allowVarargs();
129 Options options = Options.instance(context);
130 debugResolve = options.isSet("debugresolve");
131 compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
132 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
133 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
134 Target target = Target.instance(context);
135 allowMethodHandles = target.hasMethodHandles();
136 allowDefaultMethods = source.allowDefaultMethods();
137 allowStructuralMostSpecific = source.allowStructuralMostSpecific();
138 polymorphicSignatureScope = new Scope(syms.noSymbol);
140 inapplicableMethodException = new InapplicableMethodException(diags);
141 }
143 /** error symbols, which are returned when resolution fails
144 */
145 private final SymbolNotFoundError varNotFound;
146 private final SymbolNotFoundError methodNotFound;
147 private final SymbolNotFoundError typeNotFound;
149 public static Resolve instance(Context context) {
150 Resolve instance = context.get(resolveKey);
151 if (instance == null)
152 instance = new Resolve(context);
153 return instance;
154 }
156 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
157 enum VerboseResolutionMode {
158 SUCCESS("success"),
159 FAILURE("failure"),
160 APPLICABLE("applicable"),
161 INAPPLICABLE("inapplicable"),
162 DEFERRED_INST("deferred-inference"),
163 PREDEF("predef"),
164 OBJECT_INIT("object-init"),
165 INTERNAL("internal");
167 final String opt;
169 private VerboseResolutionMode(String opt) {
170 this.opt = opt;
171 }
173 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
174 String s = opts.get("verboseResolution");
175 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
176 if (s == null) return res;
177 if (s.contains("all")) {
178 res = EnumSet.allOf(VerboseResolutionMode.class);
179 }
180 Collection<String> args = Arrays.asList(s.split(","));
181 for (VerboseResolutionMode mode : values()) {
182 if (args.contains(mode.opt)) {
183 res.add(mode);
184 } else if (args.contains("-" + mode.opt)) {
185 res.remove(mode);
186 }
187 }
188 return res;
189 }
190 }
192 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
193 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
194 boolean success = bestSoFar.kind < ERRONEOUS;
196 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
197 return;
198 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
199 return;
200 }
202 if (bestSoFar.name == names.init &&
203 bestSoFar.owner == syms.objectType.tsym &&
204 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
205 return; //skip diags for Object constructor resolution
206 } else if (site == syms.predefClass.type &&
207 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
208 return; //skip spurious diags for predef symbols (i.e. operators)
209 } else if (currentResolutionContext.internalResolution &&
210 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
211 return;
212 }
214 int pos = 0;
215 int mostSpecificPos = -1;
216 ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
217 for (Candidate c : currentResolutionContext.candidates) {
218 if (currentResolutionContext.step != c.step ||
219 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
220 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
221 continue;
222 } else {
223 subDiags.append(c.isApplicable() ?
224 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
225 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
226 if (c.sym == bestSoFar)
227 mostSpecificPos = pos;
228 pos++;
229 }
230 }
231 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
232 List<Type> argtypes2 = Type.map(argtypes,
233 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
234 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
235 site.tsym, mostSpecificPos, currentResolutionContext.step,
236 methodArguments(argtypes2),
237 methodArguments(typeargtypes));
238 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
239 log.report(d);
240 }
242 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
243 JCDiagnostic subDiag = null;
244 if (sym.type.hasTag(FORALL)) {
245 subDiag = diags.fragment("partial.inst.sig", inst);
246 }
248 String key = subDiag == null ?
249 "applicable.method.found" :
250 "applicable.method.found.1";
252 return diags.fragment(key, pos, sym, subDiag);
253 }
255 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
256 return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
257 }
258 // </editor-fold>
260 /* ************************************************************************
261 * Identifier resolution
262 *************************************************************************/
264 /** An environment is "static" if its static level is greater than
265 * the one of its outer environment
266 */
267 protected static boolean isStatic(Env<AttrContext> env) {
268 return env.info.staticLevel > env.outer.info.staticLevel;
269 }
271 /** An environment is an "initializer" if it is a constructor or
272 * an instance initializer.
273 */
274 static boolean isInitializer(Env<AttrContext> env) {
275 Symbol owner = env.info.scope.owner;
276 return owner.isConstructor() ||
277 owner.owner.kind == TYP &&
278 (owner.kind == VAR ||
279 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
280 (owner.flags() & STATIC) == 0;
281 }
283 /** Is class accessible in given evironment?
284 * @param env The current environment.
285 * @param c The class whose accessibility is checked.
286 */
287 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
288 return isAccessible(env, c, false);
289 }
291 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
292 boolean isAccessible = false;
293 switch ((short)(c.flags() & AccessFlags)) {
294 case PRIVATE:
295 isAccessible =
296 env.enclClass.sym.outermostClass() ==
297 c.owner.outermostClass();
298 break;
299 case 0:
300 isAccessible =
301 env.toplevel.packge == c.owner // fast special case
302 ||
303 env.toplevel.packge == c.packge()
304 ||
305 // Hack: this case is added since synthesized default constructors
306 // of anonymous classes should be allowed to access
307 // classes which would be inaccessible otherwise.
308 env.enclMethod != null &&
309 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
310 break;
311 default: // error recovery
312 case PUBLIC:
313 isAccessible = true;
314 break;
315 case PROTECTED:
316 isAccessible =
317 env.toplevel.packge == c.owner // fast special case
318 ||
319 env.toplevel.packge == c.packge()
320 ||
321 isInnerSubClass(env.enclClass.sym, c.owner);
322 break;
323 }
324 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
325 isAccessible :
326 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
327 }
328 //where
329 /** Is given class a subclass of given base class, or an inner class
330 * of a subclass?
331 * Return null if no such class exists.
332 * @param c The class which is the subclass or is contained in it.
333 * @param base The base class
334 */
335 private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
336 while (c != null && !c.isSubClass(base, types)) {
337 c = c.owner.enclClass();
338 }
339 return c != null;
340 }
342 boolean isAccessible(Env<AttrContext> env, Type t) {
343 return isAccessible(env, t, false);
344 }
346 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
347 return (t.hasTag(ARRAY))
348 ? isAccessible(env, types.elemtype(t))
349 : isAccessible(env, t.tsym, checkInner);
350 }
352 /** Is symbol accessible as a member of given type in given environment?
353 * @param env The current environment.
354 * @param site The type of which the tested symbol is regarded
355 * as a member.
356 * @param sym The symbol.
357 */
358 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
359 return isAccessible(env, site, sym, false);
360 }
361 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
362 if (sym.name == names.init && sym.owner != site.tsym) return false;
363 switch ((short)(sym.flags() & AccessFlags)) {
364 case PRIVATE:
365 return
366 (env.enclClass.sym == sym.owner // fast special case
367 ||
368 env.enclClass.sym.outermostClass() ==
369 sym.owner.outermostClass())
370 &&
371 sym.isInheritedIn(site.tsym, types);
372 case 0:
373 return
374 (env.toplevel.packge == sym.owner.owner // fast special case
375 ||
376 env.toplevel.packge == sym.packge())
377 &&
378 isAccessible(env, site, checkInner)
379 &&
380 sym.isInheritedIn(site.tsym, types)
381 &&
382 notOverriddenIn(site, sym);
383 case PROTECTED:
384 return
385 (env.toplevel.packge == sym.owner.owner // fast special case
386 ||
387 env.toplevel.packge == sym.packge()
388 ||
389 isProtectedAccessible(sym, env.enclClass.sym, site)
390 ||
391 // OK to select instance method or field from 'super' or type name
392 // (but type names should be disallowed elsewhere!)
393 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
394 &&
395 isAccessible(env, site, checkInner)
396 &&
397 notOverriddenIn(site, sym);
398 default: // this case includes erroneous combinations as well
399 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
400 }
401 }
402 //where
403 /* `sym' is accessible only if not overridden by
404 * another symbol which is a member of `site'
405 * (because, if it is overridden, `sym' is not strictly
406 * speaking a member of `site'). A polymorphic signature method
407 * cannot be overridden (e.g. MH.invokeExact(Object[])).
408 */
409 private boolean notOverriddenIn(Type site, Symbol sym) {
410 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
411 return true;
412 else {
413 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
414 return (s2 == null || s2 == sym || sym.owner == s2.owner ||
415 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
416 }
417 }
418 //where
419 /** Is given protected symbol accessible if it is selected from given site
420 * and the selection takes place in given class?
421 * @param sym The symbol with protected access
422 * @param c The class where the access takes place
423 * @site The type of the qualifier
424 */
425 private
426 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
427 while (c != null &&
428 !(c.isSubClass(sym.owner, types) &&
429 (c.flags() & INTERFACE) == 0 &&
430 // In JLS 2e 6.6.2.1, the subclass restriction applies
431 // only to instance fields and methods -- types are excluded
432 // regardless of whether they are declared 'static' or not.
433 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
434 c = c.owner.enclClass();
435 return c != null;
436 }
438 /**
439 * Performs a recursive scan of a type looking for accessibility problems
440 * from current attribution environment
441 */
442 void checkAccessibleType(Env<AttrContext> env, Type t) {
443 accessibilityChecker.visit(t, env);
444 }
446 /**
447 * Accessibility type-visitor
448 */
449 Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
450 new Types.SimpleVisitor<Void, Env<AttrContext>>() {
452 void visit(List<Type> ts, Env<AttrContext> env) {
453 for (Type t : ts) {
454 visit(t, env);
455 }
456 }
458 public Void visitType(Type t, Env<AttrContext> env) {
459 return null;
460 }
462 @Override
463 public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
464 visit(t.elemtype, env);
465 return null;
466 }
468 @Override
469 public Void visitClassType(ClassType t, Env<AttrContext> env) {
470 visit(t.getTypeArguments(), env);
471 if (!isAccessible(env, t, true)) {
472 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
473 }
474 return null;
475 }
477 @Override
478 public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
479 visit(t.type, env);
480 return null;
481 }
483 @Override
484 public Void visitMethodType(MethodType t, Env<AttrContext> env) {
485 visit(t.getParameterTypes(), env);
486 visit(t.getReturnType(), env);
487 visit(t.getThrownTypes(), env);
488 return null;
489 }
490 };
492 /** Try to instantiate the type of a method so that it fits
493 * given type arguments and argument types. If successful, return
494 * the method's instantiated type, else return null.
495 * The instantiation will take into account an additional leading
496 * formal parameter if the method is an instance method seen as a member
497 * of an under determined site. In this case, we treat site as an additional
498 * parameter and the parameters of the class containing the method as
499 * additional type variables that get instantiated.
500 *
501 * @param env The current environment
502 * @param site The type of which the method is a member.
503 * @param m The method symbol.
504 * @param argtypes The invocation's given value arguments.
505 * @param typeargtypes The invocation's given type arguments.
506 * @param allowBoxing Allow boxing conversions of arguments.
507 * @param useVarargs Box trailing arguments into an array for varargs.
508 */
509 Type rawInstantiate(Env<AttrContext> env,
510 Type site,
511 Symbol m,
512 ResultInfo resultInfo,
513 List<Type> argtypes,
514 List<Type> typeargtypes,
515 boolean allowBoxing,
516 boolean useVarargs,
517 Warner warn) throws Infer.InferenceException {
519 Type mt = types.memberType(site, m);
520 // tvars is the list of formal type variables for which type arguments
521 // need to inferred.
522 List<Type> tvars = List.nil();
523 if (typeargtypes == null) typeargtypes = List.nil();
524 if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
525 // This is not a polymorphic method, but typeargs are supplied
526 // which is fine, see JLS 15.12.2.1
527 } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
528 ForAll pmt = (ForAll) mt;
529 if (typeargtypes.length() != pmt.tvars.length())
530 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
531 // Check type arguments are within bounds
532 List<Type> formals = pmt.tvars;
533 List<Type> actuals = typeargtypes;
534 while (formals.nonEmpty() && actuals.nonEmpty()) {
535 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
536 pmt.tvars, typeargtypes);
537 for (; bounds.nonEmpty(); bounds = bounds.tail)
538 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
539 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
540 formals = formals.tail;
541 actuals = actuals.tail;
542 }
543 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
544 } else if (mt.hasTag(FORALL)) {
545 ForAll pmt = (ForAll) mt;
546 List<Type> tvars1 = types.newInstances(pmt.tvars);
547 tvars = tvars.appendList(tvars1);
548 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
549 }
551 // find out whether we need to go the slow route via infer
552 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
553 for (List<Type> l = argtypes;
554 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
555 l = l.tail) {
556 if (l.head.hasTag(FORALL)) instNeeded = true;
557 }
559 if (instNeeded)
560 return infer.instantiateMethod(env,
561 tvars,
562 (MethodType)mt,
563 resultInfo,
564 m,
565 argtypes,
566 allowBoxing,
567 useVarargs,
568 currentResolutionContext,
569 warn);
571 currentResolutionContext.methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn),
572 argtypes, mt.getParameterTypes(), warn);
573 return mt;
574 }
576 Type checkMethod(Env<AttrContext> env,
577 Type site,
578 Symbol m,
579 ResultInfo resultInfo,
580 List<Type> argtypes,
581 List<Type> typeargtypes,
582 Warner warn) {
583 MethodResolutionContext prevContext = currentResolutionContext;
584 try {
585 currentResolutionContext = new MethodResolutionContext();
586 currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
587 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
588 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
589 step.isBoxingRequired(), step.isVarargsRequired(), warn);
590 }
591 finally {
592 currentResolutionContext = prevContext;
593 }
594 }
596 /** Same but returns null instead throwing a NoInstanceException
597 */
598 Type instantiate(Env<AttrContext> env,
599 Type site,
600 Symbol m,
601 ResultInfo resultInfo,
602 List<Type> argtypes,
603 List<Type> typeargtypes,
604 boolean allowBoxing,
605 boolean useVarargs,
606 Warner warn) {
607 try {
608 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
609 allowBoxing, useVarargs, warn);
610 } catch (InapplicableMethodException ex) {
611 return null;
612 }
613 }
615 /**
616 * This interface defines an entry point that should be used to perform a
617 * method check. A method check usually consist in determining as to whether
618 * a set of types (actuals) is compatible with another set of types (formals).
619 * Since the notion of compatibility can vary depending on the circumstances,
620 * this interfaces allows to easily add new pluggable method check routines.
621 */
622 interface MethodCheck {
623 /**
624 * Main method check routine. A method check usually consist in determining
625 * as to whether a set of types (actuals) is compatible with another set of
626 * types (formals). If an incompatibility is found, an unchecked exception
627 * is assumed to be thrown.
628 */
629 void argumentsAcceptable(Env<AttrContext> env,
630 DeferredAttrContext deferredAttrContext,
631 List<Type> argtypes,
632 List<Type> formals,
633 Warner warn);
635 /**
636 * Retrieve the method check object that will be used during a
637 * most specific check.
638 */
639 MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
640 }
642 /**
643 * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
644 */
645 enum MethodCheckDiag {
646 /**
647 * Actuals and formals differs in length.
648 */
649 ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
650 /**
651 * An actual is incompatible with a formal.
652 */
653 ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
654 /**
655 * An actual is incompatible with the varargs element type.
656 */
657 VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
658 /**
659 * The varargs element type is inaccessible.
660 */
661 INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
663 final String basicKey;
664 final String inferKey;
666 MethodCheckDiag(String basicKey, String inferKey) {
667 this.basicKey = basicKey;
668 this.inferKey = inferKey;
669 }
671 String regex() {
672 return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
673 }
674 }
676 /**
677 * Dummy method check object. All methods are deemed applicable, regardless
678 * of their formal parameter types.
679 */
680 MethodCheck nilMethodCheck = new MethodCheck() {
681 public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
682 //do nothing - method always applicable regardless of actuals
683 }
685 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
686 return this;
687 }
688 };
690 /**
691 * Base class for 'real' method checks. The class defines the logic for
692 * iterating through formals and actuals and provides and entry point
693 * that can be used by subclasses in order to define the actual check logic.
694 */
695 abstract class AbstractMethodCheck implements MethodCheck {
696 @Override
697 public void argumentsAcceptable(final Env<AttrContext> env,
698 DeferredAttrContext deferredAttrContext,
699 List<Type> argtypes,
700 List<Type> formals,
701 Warner warn) {
702 //should we expand formals?
703 boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
704 List<JCExpression> trees = TreeInfo.args(env.tree);
706 //inference context used during this method check
707 InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
709 Type varargsFormal = useVarargs ? formals.last() : null;
711 if (varargsFormal == null &&
712 argtypes.size() != formals.size()) {
713 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
714 }
716 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
717 DiagnosticPosition pos = trees != null ? trees.head : null;
718 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
719 argtypes = argtypes.tail;
720 formals = formals.tail;
721 trees = trees != null ? trees.tail : trees;
722 }
724 if (formals.head != varargsFormal) {
725 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
726 }
728 if (useVarargs) {
729 //note: if applicability check is triggered by most specific test,
730 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
731 final Type elt = types.elemtype(varargsFormal);
732 while (argtypes.nonEmpty()) {
733 DiagnosticPosition pos = trees != null ? trees.head : null;
734 checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
735 argtypes = argtypes.tail;
736 trees = trees != null ? trees.tail : trees;
737 }
738 }
739 }
741 /**
742 * Does the actual argument conforms to the corresponding formal?
743 */
744 abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
746 protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
747 boolean inferDiag = inferenceContext != infer.emptyContext;
748 InapplicableMethodException ex = inferDiag ?
749 infer.inferenceException : inapplicableMethodException;
750 if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
751 Object[] args2 = new Object[args.length + 1];
752 System.arraycopy(args, 0, args2, 1, args.length);
753 args2[0] = inferenceContext.inferenceVars();
754 args = args2;
755 }
756 String key = inferDiag ? diag.inferKey : diag.basicKey;
757 throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
758 }
760 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
761 return nilMethodCheck;
762 }
763 }
765 /**
766 * Arity-based method check. A method is applicable if the number of actuals
767 * supplied conforms to the method signature.
768 */
769 MethodCheck arityMethodCheck = new AbstractMethodCheck() {
770 @Override
771 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
772 //do nothing - actual always compatible to formals
773 }
774 };
776 /**
777 * Main method applicability routine. Given a list of actual types A,
778 * a list of formal types F, determines whether the types in A are
779 * compatible (by method invocation conversion) with the types in F.
780 *
781 * Since this routine is shared between overload resolution and method
782 * type-inference, a (possibly empty) inference context is used to convert
783 * formal types to the corresponding 'undet' form ahead of a compatibility
784 * check so that constraints can be propagated and collected.
785 *
786 * Moreover, if one or more types in A is a deferred type, this routine uses
787 * DeferredAttr in order to perform deferred attribution. If one or more actual
788 * deferred types are stuck, they are placed in a queue and revisited later
789 * after the remainder of the arguments have been seen. If this is not sufficient
790 * to 'unstuck' the argument, a cyclic inference error is called out.
791 *
792 * A method check handler (see above) is used in order to report errors.
793 */
794 MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
796 @Override
797 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
798 ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
799 mresult.check(pos, actual);
800 }
802 @Override
803 public void argumentsAcceptable(final Env<AttrContext> env,
804 DeferredAttrContext deferredAttrContext,
805 List<Type> argtypes,
806 List<Type> formals,
807 Warner warn) {
808 super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
809 //should we expand formals?
810 if (deferredAttrContext.phase.isVarargsRequired()) {
811 //check varargs element type accessibility
812 varargsAccessible(env, types.elemtype(formals.last()),
813 deferredAttrContext.inferenceContext);
814 }
815 }
817 private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
818 if (inferenceContext.free(t)) {
819 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
820 @Override
821 public void typesInferred(InferenceContext inferenceContext) {
822 varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
823 }
824 });
825 } else {
826 if (!isAccessible(env, t)) {
827 Symbol location = env.enclClass.sym;
828 reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
829 }
830 }
831 }
833 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
834 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
835 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
836 MethodCheckDiag methodDiag = varargsCheck ?
837 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
839 @Override
840 public void report(DiagnosticPosition pos, JCDiagnostic details) {
841 reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
842 }
843 };
844 return new MethodResultInfo(to, checkContext);
845 }
847 @Override
848 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
849 return new MostSpecificCheck(strict, actuals);
850 }
851 };
853 /**
854 * Check context to be used during method applicability checks. A method check
855 * context might contain inference variables.
856 */
857 abstract class MethodCheckContext implements CheckContext {
859 boolean strict;
860 DeferredAttrContext deferredAttrContext;
861 Warner rsWarner;
863 public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
864 this.strict = strict;
865 this.deferredAttrContext = deferredAttrContext;
866 this.rsWarner = rsWarner;
867 }
869 public boolean compatible(Type found, Type req, Warner warn) {
870 return strict ?
871 types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
872 types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
873 }
875 public void report(DiagnosticPosition pos, JCDiagnostic details) {
876 throw inapplicableMethodException.setMessage(details);
877 }
879 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
880 return rsWarner;
881 }
883 public InferenceContext inferenceContext() {
884 return deferredAttrContext.inferenceContext;
885 }
887 public DeferredAttrContext deferredAttrContext() {
888 return deferredAttrContext;
889 }
890 }
892 /**
893 * ResultInfo class to be used during method applicability checks. Check
894 * for deferred types goes through special path.
895 */
896 class MethodResultInfo extends ResultInfo {
898 public MethodResultInfo(Type pt, CheckContext checkContext) {
899 attr.super(VAL, pt, checkContext);
900 }
902 @Override
903 protected Type check(DiagnosticPosition pos, Type found) {
904 if (found.hasTag(DEFERRED)) {
905 DeferredType dt = (DeferredType)found;
906 return dt.check(this);
907 } else {
908 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
909 }
910 }
912 @Override
913 protected MethodResultInfo dup(Type newPt) {
914 return new MethodResultInfo(newPt, checkContext);
915 }
917 @Override
918 protected ResultInfo dup(CheckContext newContext) {
919 return new MethodResultInfo(pt, newContext);
920 }
921 }
923 /**
924 * Most specific method applicability routine. Given a list of actual types A,
925 * a list of formal types F1, and a list of formal types F2, the routine determines
926 * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
927 * argument types A.
928 */
929 class MostSpecificCheck implements MethodCheck {
931 boolean strict;
932 List<Type> actuals;
934 MostSpecificCheck(boolean strict, List<Type> actuals) {
935 this.strict = strict;
936 this.actuals = actuals;
937 }
939 @Override
940 public void argumentsAcceptable(final Env<AttrContext> env,
941 DeferredAttrContext deferredAttrContext,
942 List<Type> formals1,
943 List<Type> formals2,
944 Warner warn) {
945 formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
946 while (formals2.nonEmpty()) {
947 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
948 mresult.check(null, formals1.head);
949 formals1 = formals1.tail;
950 formals2 = formals2.tail;
951 actuals = actuals.isEmpty() ? actuals : actuals.tail;
952 }
953 }
955 /**
956 * Create a method check context to be used during the most specific applicability check
957 */
958 ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
959 Warner rsWarner, Type actual) {
960 return attr.new ResultInfo(Kinds.VAL, to,
961 new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
962 }
964 /**
965 * Subclass of method check context class that implements most specific
966 * method conversion. If the actual type under analysis is a deferred type
967 * a full blown structural analysis is carried out.
968 */
969 class MostSpecificCheckContext extends MethodCheckContext {
971 Type actual;
973 public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
974 super(strict, deferredAttrContext, rsWarner);
975 this.actual = actual;
976 }
978 public boolean compatible(Type found, Type req, Warner warn) {
979 if (!allowStructuralMostSpecific || actual == null) {
980 return super.compatible(found, req, warn);
981 } else {
982 switch (actual.getTag()) {
983 case DEFERRED:
984 DeferredType dt = (DeferredType) actual;
985 DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
986 return (e == null || e.speculativeTree == deferredAttr.stuckTree)
987 ? false : mostSpecific(found, req, e.speculativeTree, warn);
988 default:
989 return standaloneMostSpecific(found, req, actual, warn);
990 }
991 }
992 }
994 private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
995 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
996 msc.scan(tree);
997 return msc.result;
998 }
1000 boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
1001 return (!t1.isPrimitive() && t2.isPrimitive())
1002 ? true : super.compatible(t1, t2, warn);
1003 }
1005 boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
1006 return (exprType.isPrimitive() == t1.isPrimitive()
1007 && exprType.isPrimitive() != t2.isPrimitive())
1008 ? true : super.compatible(t1, t2, warn);
1009 }
1011 /**
1012 * Structural checker for most specific.
1013 */
1014 class MostSpecificChecker extends DeferredAttr.PolyScanner {
1016 final Type t;
1017 final Type s;
1018 final Warner warn;
1019 boolean result;
1021 MostSpecificChecker(Type t, Type s, Warner warn) {
1022 this.t = t;
1023 this.s = s;
1024 this.warn = warn;
1025 result = true;
1026 }
1028 @Override
1029 void skip(JCTree tree) {
1030 result &= standaloneMostSpecific(t, s, tree.type, warn);
1031 }
1033 @Override
1034 public void visitConditional(JCConditional tree) {
1035 if (tree.polyKind == PolyKind.STANDALONE) {
1036 result &= standaloneMostSpecific(t, s, tree.type, warn);
1037 } else {
1038 super.visitConditional(tree);
1039 }
1040 }
1042 @Override
1043 public void visitApply(JCMethodInvocation tree) {
1044 result &= (tree.polyKind == PolyKind.STANDALONE)
1045 ? standaloneMostSpecific(t, s, tree.type, warn)
1046 : polyMostSpecific(t, s, warn);
1047 }
1049 @Override
1050 public void visitNewClass(JCNewClass tree) {
1051 result &= (tree.polyKind == PolyKind.STANDALONE)
1052 ? standaloneMostSpecific(t, s, tree.type, warn)
1053 : polyMostSpecific(t, s, warn);
1054 }
1056 @Override
1057 public void visitReference(JCMemberReference tree) {
1058 if (types.isFunctionalInterface(t.tsym) &&
1059 types.isFunctionalInterface(s.tsym) &&
1060 types.asSuper(t, s.tsym) == null &&
1061 types.asSuper(s, t.tsym) == null) {
1062 Type desc_t = types.findDescriptorType(t);
1063 Type desc_s = types.findDescriptorType(s);
1064 if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
1065 if (!desc_s.getReturnType().hasTag(VOID)) {
1066 //perform structural comparison
1067 Type ret_t = desc_t.getReturnType();
1068 Type ret_s = desc_s.getReturnType();
1069 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
1070 ? standaloneMostSpecific(ret_t, ret_s, tree.sym.type.getReturnType(), warn)
1071 : polyMostSpecific(ret_t, ret_s, warn));
1072 } else {
1073 return;
1074 }
1075 } else {
1076 result &= false;
1077 }
1078 } else {
1079 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
1080 }
1081 }
1083 @Override
1084 public void visitLambda(JCLambda tree) {
1085 if (types.isFunctionalInterface(t.tsym) &&
1086 types.isFunctionalInterface(s.tsym) &&
1087 types.asSuper(t, s.tsym) == null &&
1088 types.asSuper(s, t.tsym) == null) {
1089 Type desc_t = types.findDescriptorType(t);
1090 Type desc_s = types.findDescriptorType(s);
1091 if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
1092 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
1093 if (!desc_s.getReturnType().hasTag(VOID)) {
1094 //perform structural comparison
1095 Type ret_t = desc_t.getReturnType();
1096 Type ret_s = desc_s.getReturnType();
1097 scanLambdaBody(tree, ret_t, ret_s);
1098 } else {
1099 return;
1100 }
1101 } else {
1102 result &= false;
1103 }
1104 } else {
1105 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
1106 }
1107 }
1108 //where
1110 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
1111 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
1112 result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
1113 } else {
1114 DeferredAttr.LambdaReturnScanner lambdaScanner =
1115 new DeferredAttr.LambdaReturnScanner() {
1116 @Override
1117 public void visitReturn(JCReturn tree) {
1118 if (tree.expr != null) {
1119 result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
1120 }
1121 }
1122 };
1123 lambdaScanner.scan(lambda.body);
1124 }
1125 }
1126 }
1127 }
1129 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
1130 Assert.error("Cannot get here!");
1131 return null;
1132 }
1133 }
1135 public static class InapplicableMethodException extends RuntimeException {
1136 private static final long serialVersionUID = 0;
1138 JCDiagnostic diagnostic;
1139 JCDiagnostic.Factory diags;
1141 InapplicableMethodException(JCDiagnostic.Factory diags) {
1142 this.diagnostic = null;
1143 this.diags = diags;
1144 }
1145 InapplicableMethodException setMessage() {
1146 return setMessage((JCDiagnostic)null);
1147 }
1148 InapplicableMethodException setMessage(String key) {
1149 return setMessage(key != null ? diags.fragment(key) : null);
1150 }
1151 InapplicableMethodException setMessage(String key, Object... args) {
1152 return setMessage(key != null ? diags.fragment(key, args) : null);
1153 }
1154 InapplicableMethodException setMessage(JCDiagnostic diag) {
1155 this.diagnostic = diag;
1156 return this;
1157 }
1159 public JCDiagnostic getDiagnostic() {
1160 return diagnostic;
1161 }
1162 }
1163 private final InapplicableMethodException inapplicableMethodException;
1165 /* ***************************************************************************
1166 * Symbol lookup
1167 * the following naming conventions for arguments are used
1168 *
1169 * env is the environment where the symbol was mentioned
1170 * site is the type of which the symbol is a member
1171 * name is the symbol's name
1172 * if no arguments are given
1173 * argtypes are the value arguments, if we search for a method
1174 *
1175 * If no symbol was found, a ResolveError detailing the problem is returned.
1176 ****************************************************************************/
1178 /** Find field. Synthetic fields are always skipped.
1179 * @param env The current environment.
1180 * @param site The original type from where the selection takes place.
1181 * @param name The name of the field.
1182 * @param c The class to search for the field. This is always
1183 * a superclass or implemented interface of site's class.
1184 */
1185 Symbol findField(Env<AttrContext> env,
1186 Type site,
1187 Name name,
1188 TypeSymbol c) {
1189 while (c.type.hasTag(TYPEVAR))
1190 c = c.type.getUpperBound().tsym;
1191 Symbol bestSoFar = varNotFound;
1192 Symbol sym;
1193 Scope.Entry e = c.members().lookup(name);
1194 while (e.scope != null) {
1195 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
1196 return isAccessible(env, site, e.sym)
1197 ? e.sym : new AccessError(env, site, e.sym);
1198 }
1199 e = e.next();
1200 }
1201 Type st = types.supertype(c.type);
1202 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
1203 sym = findField(env, site, name, st.tsym);
1204 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1205 }
1206 for (List<Type> l = types.interfaces(c.type);
1207 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1208 l = l.tail) {
1209 sym = findField(env, site, name, l.head.tsym);
1210 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1211 sym.owner != bestSoFar.owner)
1212 bestSoFar = new AmbiguityError(bestSoFar, sym);
1213 else if (sym.kind < bestSoFar.kind)
1214 bestSoFar = sym;
1215 }
1216 return bestSoFar;
1217 }
1219 /** Resolve a field identifier, throw a fatal error if not found.
1220 * @param pos The position to use for error reporting.
1221 * @param env The environment current at the method invocation.
1222 * @param site The type of the qualifying expression, in which
1223 * identifier is searched.
1224 * @param name The identifier's name.
1225 */
1226 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
1227 Type site, Name name) {
1228 Symbol sym = findField(env, site, name, site.tsym);
1229 if (sym.kind == VAR) return (VarSymbol)sym;
1230 else throw new FatalError(
1231 diags.fragment("fatal.err.cant.locate.field",
1232 name));
1233 }
1235 /** Find unqualified variable or field with given name.
1236 * Synthetic fields always skipped.
1237 * @param env The current environment.
1238 * @param name The name of the variable or field.
1239 */
1240 Symbol findVar(Env<AttrContext> env, Name name) {
1241 Symbol bestSoFar = varNotFound;
1242 Symbol sym;
1243 Env<AttrContext> env1 = env;
1244 boolean staticOnly = false;
1245 while (env1.outer != null) {
1246 if (isStatic(env1)) staticOnly = true;
1247 Scope.Entry e = env1.info.scope.lookup(name);
1248 while (e.scope != null &&
1249 (e.sym.kind != VAR ||
1250 (e.sym.flags_field & SYNTHETIC) != 0))
1251 e = e.next();
1252 sym = (e.scope != null)
1253 ? e.sym
1254 : findField(
1255 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
1256 if (sym.exists()) {
1257 if (staticOnly &&
1258 sym.kind == VAR &&
1259 sym.owner.kind == TYP &&
1260 (sym.flags() & STATIC) == 0)
1261 return new StaticError(sym);
1262 else
1263 return sym;
1264 } else if (sym.kind < bestSoFar.kind) {
1265 bestSoFar = sym;
1266 }
1268 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1269 env1 = env1.outer;
1270 }
1272 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1273 if (sym.exists())
1274 return sym;
1275 if (bestSoFar.exists())
1276 return bestSoFar;
1278 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1279 for (; e.scope != null; e = e.next()) {
1280 sym = e.sym;
1281 Type origin = e.getOrigin().owner.type;
1282 if (sym.kind == VAR) {
1283 if (e.sym.owner.type != origin)
1284 sym = sym.clone(e.getOrigin().owner);
1285 return isAccessible(env, origin, sym)
1286 ? sym : new AccessError(env, origin, sym);
1287 }
1288 }
1290 Symbol origin = null;
1291 e = env.toplevel.starImportScope.lookup(name);
1292 for (; e.scope != null; e = e.next()) {
1293 sym = e.sym;
1294 if (sym.kind != VAR)
1295 continue;
1296 // invariant: sym.kind == VAR
1297 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
1298 return new AmbiguityError(bestSoFar, sym);
1299 else if (bestSoFar.kind >= VAR) {
1300 origin = e.getOrigin().owner;
1301 bestSoFar = isAccessible(env, origin.type, sym)
1302 ? sym : new AccessError(env, origin.type, sym);
1303 }
1304 }
1305 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1306 return bestSoFar.clone(origin);
1307 else
1308 return bestSoFar;
1309 }
1311 Warner noteWarner = new Warner();
1313 /** Select the best method for a call site among two choices.
1314 * @param env The current environment.
1315 * @param site The original type from where the
1316 * selection takes place.
1317 * @param argtypes The invocation's value arguments,
1318 * @param typeargtypes The invocation's type arguments,
1319 * @param sym Proposed new best match.
1320 * @param bestSoFar Previously found best match.
1321 * @param allowBoxing Allow boxing conversions of arguments.
1322 * @param useVarargs Box trailing arguments into an array for varargs.
1323 */
1324 @SuppressWarnings("fallthrough")
1325 Symbol selectBest(Env<AttrContext> env,
1326 Type site,
1327 List<Type> argtypes,
1328 List<Type> typeargtypes,
1329 Symbol sym,
1330 Symbol bestSoFar,
1331 boolean allowBoxing,
1332 boolean useVarargs,
1333 boolean operator) {
1334 if (sym.kind == ERR ||
1335 !sym.isInheritedIn(site.tsym, types)) {
1336 return bestSoFar;
1337 } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
1338 return bestSoFar.kind >= ERRONEOUS ?
1339 new BadVarargsMethod((ResolveError)bestSoFar) :
1340 bestSoFar;
1341 }
1342 Assert.check(sym.kind < AMBIGUOUS);
1343 try {
1344 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1345 allowBoxing, useVarargs, types.noWarnings);
1346 if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
1347 currentResolutionContext.addApplicableCandidate(sym, mt);
1348 } catch (InapplicableMethodException ex) {
1349 if (!operator)
1350 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1351 switch (bestSoFar.kind) {
1352 case ABSENT_MTH:
1353 return new InapplicableSymbolError(currentResolutionContext);
1354 case WRONG_MTH:
1355 if (operator) return bestSoFar;
1356 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1357 default:
1358 return bestSoFar;
1359 }
1360 }
1361 if (!isAccessible(env, site, sym)) {
1362 return (bestSoFar.kind == ABSENT_MTH)
1363 ? new AccessError(env, site, sym)
1364 : bestSoFar;
1365 }
1366 return (bestSoFar.kind > AMBIGUOUS)
1367 ? sym
1368 : mostSpecific(argtypes, sym, bestSoFar, env, site,
1369 allowBoxing && operator, useVarargs);
1370 }
1372 /* Return the most specific of the two methods for a call,
1373 * given that both are accessible and applicable.
1374 * @param m1 A new candidate for most specific.
1375 * @param m2 The previous most specific candidate.
1376 * @param env The current environment.
1377 * @param site The original type from where the selection
1378 * takes place.
1379 * @param allowBoxing Allow boxing conversions of arguments.
1380 * @param useVarargs Box trailing arguments into an array for varargs.
1381 */
1382 Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1383 Symbol m2,
1384 Env<AttrContext> env,
1385 final Type site,
1386 boolean allowBoxing,
1387 boolean useVarargs) {
1388 switch (m2.kind) {
1389 case MTH:
1390 if (m1 == m2) return m1;
1391 boolean m1SignatureMoreSpecific =
1392 signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1393 boolean m2SignatureMoreSpecific =
1394 signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1395 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1396 Type mt1 = types.memberType(site, m1);
1397 Type mt2 = types.memberType(site, m2);
1398 if (!types.overrideEquivalent(mt1, mt2))
1399 return ambiguityError(m1, m2);
1401 // same signature; select (a) the non-bridge method, or
1402 // (b) the one that overrides the other, or (c) the concrete
1403 // one, or (d) merge both abstract signatures
1404 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1405 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1407 // if one overrides or hides the other, use it
1408 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1409 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1410 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1411 ((m1.owner.flags_field & INTERFACE) == 0 ||
1412 (m2.owner.flags_field & INTERFACE) != 0) &&
1413 m1.overrides(m2, m1Owner, types, false))
1414 return m1;
1415 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1416 ((m2.owner.flags_field & INTERFACE) == 0 ||
1417 (m1.owner.flags_field & INTERFACE) != 0) &&
1418 m2.overrides(m1, m2Owner, types, false))
1419 return m2;
1420 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1421 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1422 if (m1Abstract && !m2Abstract) return m2;
1423 if (m2Abstract && !m1Abstract) return m1;
1424 // both abstract or both concrete
1425 return ambiguityError(m1, m2);
1426 }
1427 if (m1SignatureMoreSpecific) return m1;
1428 if (m2SignatureMoreSpecific) return m2;
1429 return ambiguityError(m1, m2);
1430 case AMBIGUOUS:
1431 //check if m1 is more specific than all ambiguous methods in m2
1432 AmbiguityError e = (AmbiguityError)m2;
1433 for (Symbol s : e.ambiguousSyms) {
1434 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
1435 return e.addAmbiguousSymbol(m1);
1436 }
1437 }
1438 return m1;
1439 default:
1440 throw new AssertionError();
1441 }
1442 }
1443 //where
1444 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1445 noteWarner.clear();
1446 int maxLength = Math.max(
1447 Math.max(m1.type.getParameterTypes().length(), actuals.length()),
1448 m2.type.getParameterTypes().length());
1449 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1450 try {
1451 currentResolutionContext = new MethodResolutionContext();
1452 currentResolutionContext.step = prevResolutionContext.step;
1453 currentResolutionContext.methodCheck =
1454 prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
1455 Type mst = instantiate(env, site, m2, null,
1456 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
1457 allowBoxing, useVarargs, noteWarner);
1458 return mst != null &&
1459 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1460 } finally {
1461 currentResolutionContext = prevResolutionContext;
1462 }
1463 }
1464 private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
1465 if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
1466 Type varargsElem = types.elemtype(args.last());
1467 if (varargsElem == null) {
1468 Assert.error("Bad varargs = " + args.last() + " " + msym);
1469 }
1470 List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
1471 while (newArgs.length() < length) {
1472 newArgs = newArgs.append(newArgs.last());
1473 }
1474 return newArgs;
1475 } else {
1476 return args;
1477 }
1478 }
1479 //where
1480 Type mostSpecificReturnType(Type mt1, Type mt2) {
1481 Type rt1 = mt1.getReturnType();
1482 Type rt2 = mt2.getReturnType();
1484 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1485 //if both are generic methods, adjust return type ahead of subtyping check
1486 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1487 }
1488 //first use subtyping, then return type substitutability
1489 if (types.isSubtype(rt1, rt2)) {
1490 return mt1;
1491 } else if (types.isSubtype(rt2, rt1)) {
1492 return mt2;
1493 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1494 return mt1;
1495 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1496 return mt2;
1497 } else {
1498 return null;
1499 }
1500 }
1501 //where
1502 Symbol ambiguityError(Symbol m1, Symbol m2) {
1503 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1504 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1505 } else {
1506 return new AmbiguityError(m1, m2);
1507 }
1508 }
1510 Symbol findMethodInScope(Env<AttrContext> env,
1511 Type site,
1512 Name name,
1513 List<Type> argtypes,
1514 List<Type> typeargtypes,
1515 Scope sc,
1516 Symbol bestSoFar,
1517 boolean allowBoxing,
1518 boolean useVarargs,
1519 boolean operator,
1520 boolean abstractok) {
1521 for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
1522 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1523 bestSoFar, allowBoxing, useVarargs, operator);
1524 }
1525 return bestSoFar;
1526 }
1527 //where
1528 class LookupFilter implements Filter<Symbol> {
1530 boolean abstractOk;
1532 LookupFilter(boolean abstractOk) {
1533 this.abstractOk = abstractOk;
1534 }
1536 public boolean accepts(Symbol s) {
1537 long flags = s.flags();
1538 return s.kind == MTH &&
1539 (flags & SYNTHETIC) == 0 &&
1540 (abstractOk ||
1541 (flags & DEFAULT) != 0 ||
1542 (flags & ABSTRACT) == 0);
1543 }
1544 };
1546 /** Find best qualified method matching given name, type and value
1547 * arguments.
1548 * @param env The current environment.
1549 * @param site The original type from where the selection
1550 * takes place.
1551 * @param name The method's name.
1552 * @param argtypes The method's value arguments.
1553 * @param typeargtypes The method's type arguments
1554 * @param allowBoxing Allow boxing conversions of arguments.
1555 * @param useVarargs Box trailing arguments into an array for varargs.
1556 */
1557 Symbol findMethod(Env<AttrContext> env,
1558 Type site,
1559 Name name,
1560 List<Type> argtypes,
1561 List<Type> typeargtypes,
1562 boolean allowBoxing,
1563 boolean useVarargs,
1564 boolean operator) {
1565 Symbol bestSoFar = methodNotFound;
1566 bestSoFar = findMethod(env,
1567 site,
1568 name,
1569 argtypes,
1570 typeargtypes,
1571 site.tsym.type,
1572 bestSoFar,
1573 allowBoxing,
1574 useVarargs,
1575 operator);
1576 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1577 return bestSoFar;
1578 }
1579 // where
1580 private Symbol findMethod(Env<AttrContext> env,
1581 Type site,
1582 Name name,
1583 List<Type> argtypes,
1584 List<Type> typeargtypes,
1585 Type intype,
1586 Symbol bestSoFar,
1587 boolean allowBoxing,
1588 boolean useVarargs,
1589 boolean operator) {
1590 @SuppressWarnings({"unchecked","rawtypes"})
1591 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1592 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1593 for (TypeSymbol s : superclasses(intype)) {
1594 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1595 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1596 if (name == names.init) return bestSoFar;
1597 iphase = (iphase == null) ? null : iphase.update(s, this);
1598 if (iphase != null) {
1599 for (Type itype : types.interfaces(s.type)) {
1600 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1601 }
1602 }
1603 }
1605 Symbol concrete = bestSoFar.kind < ERR &&
1606 (bestSoFar.flags() & ABSTRACT) == 0 ?
1607 bestSoFar : methodNotFound;
1609 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1610 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
1611 //keep searching for abstract methods
1612 for (Type itype : itypes[iphase2.ordinal()]) {
1613 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1614 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1615 (itype.tsym.flags() & DEFAULT) == 0) continue;
1616 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1617 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1618 if (concrete != bestSoFar &&
1619 concrete.kind < ERR && bestSoFar.kind < ERR &&
1620 types.isSubSignature(concrete.type, bestSoFar.type)) {
1621 //this is an hack - as javac does not do full membership checks
1622 //most specific ends up comparing abstract methods that might have
1623 //been implemented by some concrete method in a subclass and,
1624 //because of raw override, it is possible for an abstract method
1625 //to be more specific than the concrete method - so we need
1626 //to explicitly call that out (see CR 6178365)
1627 bestSoFar = concrete;
1628 }
1629 }
1630 }
1631 return bestSoFar;
1632 }
1634 enum InterfaceLookupPhase {
1635 ABSTRACT_OK() {
1636 @Override
1637 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1638 //We should not look for abstract methods if receiver is a concrete class
1639 //(as concrete classes are expected to implement all abstracts coming
1640 //from superinterfaces)
1641 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1642 return this;
1643 } else if (rs.allowDefaultMethods) {
1644 return DEFAULT_OK;
1645 } else {
1646 return null;
1647 }
1648 }
1649 },
1650 DEFAULT_OK() {
1651 @Override
1652 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1653 return this;
1654 }
1655 };
1657 abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1658 }
1660 /**
1661 * Return an Iterable object to scan the superclasses of a given type.
1662 * It's crucial that the scan is done lazily, as we don't want to accidentally
1663 * access more supertypes than strictly needed (as this could trigger completion
1664 * errors if some of the not-needed supertypes are missing/ill-formed).
1665 */
1666 Iterable<TypeSymbol> superclasses(final Type intype) {
1667 return new Iterable<TypeSymbol>() {
1668 public Iterator<TypeSymbol> iterator() {
1669 return new Iterator<TypeSymbol>() {
1671 List<TypeSymbol> seen = List.nil();
1672 TypeSymbol currentSym = symbolFor(intype);
1673 TypeSymbol prevSym = null;
1675 public boolean hasNext() {
1676 if (currentSym == syms.noSymbol) {
1677 currentSym = symbolFor(types.supertype(prevSym.type));
1678 }
1679 return currentSym != null;
1680 }
1682 public TypeSymbol next() {
1683 prevSym = currentSym;
1684 currentSym = syms.noSymbol;
1685 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1686 return prevSym;
1687 }
1689 public void remove() {
1690 throw new UnsupportedOperationException();
1691 }
1693 TypeSymbol symbolFor(Type t) {
1694 if (!t.hasTag(CLASS) &&
1695 !t.hasTag(TYPEVAR)) {
1696 return null;
1697 }
1698 while (t.hasTag(TYPEVAR))
1699 t = t.getUpperBound();
1700 if (seen.contains(t.tsym)) {
1701 //degenerate case in which we have a circular
1702 //class hierarchy - because of ill-formed classfiles
1703 return null;
1704 }
1705 seen = seen.prepend(t.tsym);
1706 return t.tsym;
1707 }
1708 };
1709 }
1710 };
1711 }
1713 /** Find unqualified method matching given name, type and value arguments.
1714 * @param env The current environment.
1715 * @param name The method's name.
1716 * @param argtypes The method's value arguments.
1717 * @param typeargtypes The method's type arguments.
1718 * @param allowBoxing Allow boxing conversions of arguments.
1719 * @param useVarargs Box trailing arguments into an array for varargs.
1720 */
1721 Symbol findFun(Env<AttrContext> env, Name name,
1722 List<Type> argtypes, List<Type> typeargtypes,
1723 boolean allowBoxing, boolean useVarargs) {
1724 Symbol bestSoFar = methodNotFound;
1725 Symbol sym;
1726 Env<AttrContext> env1 = env;
1727 boolean staticOnly = false;
1728 while (env1.outer != null) {
1729 if (isStatic(env1)) staticOnly = true;
1730 sym = findMethod(
1731 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1732 allowBoxing, useVarargs, false);
1733 if (sym.exists()) {
1734 if (staticOnly &&
1735 sym.kind == MTH &&
1736 sym.owner.kind == TYP &&
1737 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1738 else return sym;
1739 } else if (sym.kind < bestSoFar.kind) {
1740 bestSoFar = sym;
1741 }
1742 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1743 env1 = env1.outer;
1744 }
1746 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1747 typeargtypes, allowBoxing, useVarargs, false);
1748 if (sym.exists())
1749 return sym;
1751 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1752 for (; e.scope != null; e = e.next()) {
1753 sym = e.sym;
1754 Type origin = e.getOrigin().owner.type;
1755 if (sym.kind == MTH) {
1756 if (e.sym.owner.type != origin)
1757 sym = sym.clone(e.getOrigin().owner);
1758 if (!isAccessible(env, origin, sym))
1759 sym = new AccessError(env, origin, sym);
1760 bestSoFar = selectBest(env, origin,
1761 argtypes, typeargtypes,
1762 sym, bestSoFar,
1763 allowBoxing, useVarargs, false);
1764 }
1765 }
1766 if (bestSoFar.exists())
1767 return bestSoFar;
1769 e = env.toplevel.starImportScope.lookup(name);
1770 for (; e.scope != null; e = e.next()) {
1771 sym = e.sym;
1772 Type origin = e.getOrigin().owner.type;
1773 if (sym.kind == MTH) {
1774 if (e.sym.owner.type != origin)
1775 sym = sym.clone(e.getOrigin().owner);
1776 if (!isAccessible(env, origin, sym))
1777 sym = new AccessError(env, origin, sym);
1778 bestSoFar = selectBest(env, origin,
1779 argtypes, typeargtypes,
1780 sym, bestSoFar,
1781 allowBoxing, useVarargs, false);
1782 }
1783 }
1784 return bestSoFar;
1785 }
1787 /** Load toplevel or member class with given fully qualified name and
1788 * verify that it is accessible.
1789 * @param env The current environment.
1790 * @param name The fully qualified name of the class to be loaded.
1791 */
1792 Symbol loadClass(Env<AttrContext> env, Name name) {
1793 try {
1794 ClassSymbol c = reader.loadClass(name);
1795 return isAccessible(env, c) ? c : new AccessError(c);
1796 } catch (ClassReader.BadClassFile err) {
1797 throw err;
1798 } catch (CompletionFailure ex) {
1799 return typeNotFound;
1800 }
1801 }
1803 /** Find qualified member type.
1804 * @param env The current environment.
1805 * @param site The original type from where the selection takes
1806 * place.
1807 * @param name The type's name.
1808 * @param c The class to search for the member type. This is
1809 * always a superclass or implemented interface of
1810 * site's class.
1811 */
1812 Symbol findMemberType(Env<AttrContext> env,
1813 Type site,
1814 Name name,
1815 TypeSymbol c) {
1816 Symbol bestSoFar = typeNotFound;
1817 Symbol sym;
1818 Scope.Entry e = c.members().lookup(name);
1819 while (e.scope != null) {
1820 if (e.sym.kind == TYP) {
1821 return isAccessible(env, site, e.sym)
1822 ? e.sym
1823 : new AccessError(env, site, e.sym);
1824 }
1825 e = e.next();
1826 }
1827 Type st = types.supertype(c.type);
1828 if (st != null && st.hasTag(CLASS)) {
1829 sym = findMemberType(env, site, name, st.tsym);
1830 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1831 }
1832 for (List<Type> l = types.interfaces(c.type);
1833 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1834 l = l.tail) {
1835 sym = findMemberType(env, site, name, l.head.tsym);
1836 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1837 sym.owner != bestSoFar.owner)
1838 bestSoFar = new AmbiguityError(bestSoFar, sym);
1839 else if (sym.kind < bestSoFar.kind)
1840 bestSoFar = sym;
1841 }
1842 return bestSoFar;
1843 }
1845 /** Find a global type in given scope and load corresponding class.
1846 * @param env The current environment.
1847 * @param scope The scope in which to look for the type.
1848 * @param name The type's name.
1849 */
1850 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1851 Symbol bestSoFar = typeNotFound;
1852 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1853 Symbol sym = loadClass(env, e.sym.flatName());
1854 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1855 bestSoFar != sym)
1856 return new AmbiguityError(bestSoFar, sym);
1857 else if (sym.kind < bestSoFar.kind)
1858 bestSoFar = sym;
1859 }
1860 return bestSoFar;
1861 }
1863 /** Find an unqualified type symbol.
1864 * @param env The current environment.
1865 * @param name The type's name.
1866 */
1867 Symbol findType(Env<AttrContext> env, Name name) {
1868 Symbol bestSoFar = typeNotFound;
1869 Symbol sym;
1870 boolean staticOnly = false;
1871 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1872 if (isStatic(env1)) staticOnly = true;
1873 for (Scope.Entry e = env1.info.scope.lookup(name);
1874 e.scope != null;
1875 e = e.next()) {
1876 if (e.sym.kind == TYP) {
1877 if (staticOnly &&
1878 e.sym.type.hasTag(TYPEVAR) &&
1879 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1880 return e.sym;
1881 }
1882 }
1884 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1885 env1.enclClass.sym);
1886 if (staticOnly && sym.kind == TYP &&
1887 sym.type.hasTag(CLASS) &&
1888 sym.type.getEnclosingType().hasTag(CLASS) &&
1889 env1.enclClass.sym.type.isParameterized() &&
1890 sym.type.getEnclosingType().isParameterized())
1891 return new StaticError(sym);
1892 else if (sym.exists()) return sym;
1893 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1895 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1896 if ((encl.sym.flags() & STATIC) != 0)
1897 staticOnly = true;
1898 }
1900 if (!env.tree.hasTag(IMPORT)) {
1901 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1902 if (sym.exists()) return sym;
1903 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1905 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1906 if (sym.exists()) return sym;
1907 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1909 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1910 if (sym.exists()) return sym;
1911 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1912 }
1914 return bestSoFar;
1915 }
1917 /** Find an unqualified identifier which matches a specified kind set.
1918 * @param env The current environment.
1919 * @param name The identifier's name.
1920 * @param kind Indicates the possible symbol kinds
1921 * (a subset of VAL, TYP, PCK).
1922 */
1923 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1924 Symbol bestSoFar = typeNotFound;
1925 Symbol sym;
1927 if ((kind & VAR) != 0) {
1928 sym = findVar(env, name);
1929 if (sym.exists()) return sym;
1930 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1931 }
1933 if ((kind & TYP) != 0) {
1934 sym = findType(env, name);
1935 if (sym.kind==TYP) {
1936 reportDependence(env.enclClass.sym, sym);
1937 }
1938 if (sym.exists()) return sym;
1939 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1940 }
1942 if ((kind & PCK) != 0) return reader.enterPackage(name);
1943 else return bestSoFar;
1944 }
1946 /** Report dependencies.
1947 * @param from The enclosing class sym
1948 * @param to The found identifier that the class depends on.
1949 */
1950 public void reportDependence(Symbol from, Symbol to) {
1951 // Override if you want to collect the reported dependencies.
1952 }
1954 /** Find an identifier in a package which matches a specified kind set.
1955 * @param env The current environment.
1956 * @param name The identifier's name.
1957 * @param kind Indicates the possible symbol kinds
1958 * (a nonempty subset of TYP, PCK).
1959 */
1960 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1961 Name name, int kind) {
1962 Name fullname = TypeSymbol.formFullName(name, pck);
1963 Symbol bestSoFar = typeNotFound;
1964 PackageSymbol pack = null;
1965 if ((kind & PCK) != 0) {
1966 pack = reader.enterPackage(fullname);
1967 if (pack.exists()) return pack;
1968 }
1969 if ((kind & TYP) != 0) {
1970 Symbol sym = loadClass(env, fullname);
1971 if (sym.exists()) {
1972 // don't allow programs to use flatnames
1973 if (name == sym.name) return sym;
1974 }
1975 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1976 }
1977 return (pack != null) ? pack : bestSoFar;
1978 }
1980 /** Find an identifier among the members of a given type `site'.
1981 * @param env The current environment.
1982 * @param site The type containing the symbol to be found.
1983 * @param name The identifier's name.
1984 * @param kind Indicates the possible symbol kinds
1985 * (a subset of VAL, TYP).
1986 */
1987 Symbol findIdentInType(Env<AttrContext> env, Type site,
1988 Name name, int kind) {
1989 Symbol bestSoFar = typeNotFound;
1990 Symbol sym;
1991 if ((kind & VAR) != 0) {
1992 sym = findField(env, site, name, site.tsym);
1993 if (sym.exists()) return sym;
1994 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1995 }
1997 if ((kind & TYP) != 0) {
1998 sym = findMemberType(env, site, name, site.tsym);
1999 if (sym.exists()) return sym;
2000 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
2001 }
2002 return bestSoFar;
2003 }
2005 /* ***************************************************************************
2006 * Access checking
2007 * The following methods convert ResolveErrors to ErrorSymbols, issuing
2008 * an error message in the process
2009 ****************************************************************************/
2011 /** If `sym' is a bad symbol: report error and return errSymbol
2012 * else pass through unchanged,
2013 * additional arguments duplicate what has been used in trying to find the
2014 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
2015 * expect misses to happen frequently.
2016 *
2017 * @param sym The symbol that was found, or a ResolveError.
2018 * @param pos The position to use for error reporting.
2019 * @param location The symbol the served as a context for this lookup
2020 * @param site The original type from where the selection took place.
2021 * @param name The symbol's name.
2022 * @param qualified Did we get here through a qualified expression resolution?
2023 * @param argtypes The invocation's value arguments,
2024 * if we looked for a method.
2025 * @param typeargtypes The invocation's type arguments,
2026 * if we looked for a method.
2027 * @param logResolveHelper helper class used to log resolve errors
2028 */
2029 Symbol accessInternal(Symbol sym,
2030 DiagnosticPosition pos,
2031 Symbol location,
2032 Type site,
2033 Name name,
2034 boolean qualified,
2035 List<Type> argtypes,
2036 List<Type> typeargtypes,
2037 LogResolveHelper logResolveHelper) {
2038 if (sym.kind >= AMBIGUOUS) {
2039 ResolveError errSym = (ResolveError)sym;
2040 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
2041 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
2042 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
2043 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
2044 }
2045 }
2046 return sym;
2047 }
2049 /**
2050 * Variant of the generalized access routine, to be used for generating method
2051 * resolution diagnostics
2052 */
2053 Symbol accessMethod(Symbol sym,
2054 DiagnosticPosition pos,
2055 Symbol location,
2056 Type site,
2057 Name name,
2058 boolean qualified,
2059 List<Type> argtypes,
2060 List<Type> typeargtypes) {
2061 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
2062 }
2064 /** Same as original accessMethod(), but without location.
2065 */
2066 Symbol accessMethod(Symbol sym,
2067 DiagnosticPosition pos,
2068 Type site,
2069 Name name,
2070 boolean qualified,
2071 List<Type> argtypes,
2072 List<Type> typeargtypes) {
2073 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
2074 }
2076 /**
2077 * Variant of the generalized access routine, to be used for generating variable,
2078 * type resolution diagnostics
2079 */
2080 Symbol accessBase(Symbol sym,
2081 DiagnosticPosition pos,
2082 Symbol location,
2083 Type site,
2084 Name name,
2085 boolean qualified) {
2086 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
2087 }
2089 /** Same as original accessBase(), but without location.
2090 */
2091 Symbol accessBase(Symbol sym,
2092 DiagnosticPosition pos,
2093 Type site,
2094 Name name,
2095 boolean qualified) {
2096 return accessBase(sym, pos, site.tsym, site, name, qualified);
2097 }
2099 interface LogResolveHelper {
2100 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2101 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2102 }
2104 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2105 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2106 return !site.isErroneous();
2107 }
2108 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2109 return argtypes;
2110 }
2111 };
2113 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2114 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2115 return !site.isErroneous() &&
2116 !Type.isErroneous(argtypes) &&
2117 (typeargtypes == null || !Type.isErroneous(typeargtypes));
2118 }
2119 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2120 return (syms.operatorNames.contains(name)) ?
2121 argtypes :
2122 Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
2123 }
2125 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2127 public ResolveDeferredRecoveryMap(Symbol msym) {
2128 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
2129 }
2131 @Override
2132 protected Type typeOf(DeferredType dt) {
2133 Type res = super.typeOf(dt);
2134 if (!res.isErroneous()) {
2135 switch (TreeInfo.skipParens(dt.tree).getTag()) {
2136 case LAMBDA:
2137 case REFERENCE:
2138 return dt;
2139 case CONDEXPR:
2140 return res == Type.recoveryType ?
2141 dt : res;
2142 }
2143 }
2144 return res;
2145 }
2146 }
2147 };
2149 /** Check that sym is not an abstract method.
2150 */
2151 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2152 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2153 log.error(pos, "abstract.cant.be.accessed.directly",
2154 kindName(sym), sym, sym.location());
2155 }
2157 /* ***************************************************************************
2158 * Debugging
2159 ****************************************************************************/
2161 /** print all scopes starting with scope s and proceeding outwards.
2162 * used for debugging.
2163 */
2164 public void printscopes(Scope s) {
2165 while (s != null) {
2166 if (s.owner != null)
2167 System.err.print(s.owner + ": ");
2168 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
2169 if ((e.sym.flags() & ABSTRACT) != 0)
2170 System.err.print("abstract ");
2171 System.err.print(e.sym + " ");
2172 }
2173 System.err.println();
2174 s = s.next;
2175 }
2176 }
2178 void printscopes(Env<AttrContext> env) {
2179 while (env.outer != null) {
2180 System.err.println("------------------------------");
2181 printscopes(env.info.scope);
2182 env = env.outer;
2183 }
2184 }
2186 public void printscopes(Type t) {
2187 while (t.hasTag(CLASS)) {
2188 printscopes(t.tsym.members());
2189 t = types.supertype(t);
2190 }
2191 }
2193 /* ***************************************************************************
2194 * Name resolution
2195 * Naming conventions are as for symbol lookup
2196 * Unlike the find... methods these methods will report access errors
2197 ****************************************************************************/
2199 /** Resolve an unqualified (non-method) identifier.
2200 * @param pos The position to use for error reporting.
2201 * @param env The environment current at the identifier use.
2202 * @param name The identifier's name.
2203 * @param kind The set of admissible symbol kinds for the identifier.
2204 */
2205 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2206 Name name, int kind) {
2207 return accessBase(
2208 findIdent(env, name, kind),
2209 pos, env.enclClass.sym.type, name, false);
2210 }
2212 /** Resolve an unqualified method identifier.
2213 * @param pos The position to use for error reporting.
2214 * @param env The environment current at the method invocation.
2215 * @param name The identifier's name.
2216 * @param argtypes The types of the invocation's value arguments.
2217 * @param typeargtypes The types of the invocation's type arguments.
2218 */
2219 Symbol resolveMethod(DiagnosticPosition pos,
2220 Env<AttrContext> env,
2221 Name name,
2222 List<Type> argtypes,
2223 List<Type> typeargtypes) {
2224 return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
2225 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2226 @Override
2227 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2228 return findFun(env, name, argtypes, typeargtypes,
2229 phase.isBoxingRequired(),
2230 phase.isVarargsRequired());
2231 }});
2232 }
2234 /** Resolve a qualified method identifier
2235 * @param pos The position to use for error reporting.
2236 * @param env The environment current at the method invocation.
2237 * @param site The type of the qualifying expression, in which
2238 * identifier is searched.
2239 * @param name The identifier's name.
2240 * @param argtypes The types of the invocation's value arguments.
2241 * @param typeargtypes The types of the invocation's type arguments.
2242 */
2243 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2244 Type site, Name name, List<Type> argtypes,
2245 List<Type> typeargtypes) {
2246 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2247 }
2248 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2249 Symbol location, Type site, Name name, List<Type> argtypes,
2250 List<Type> typeargtypes) {
2251 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2252 }
2253 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2254 DiagnosticPosition pos, Env<AttrContext> env,
2255 Symbol location, Type site, Name name, List<Type> argtypes,
2256 List<Type> typeargtypes) {
2257 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2258 @Override
2259 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2260 return findMethod(env, site, name, argtypes, typeargtypes,
2261 phase.isBoxingRequired(),
2262 phase.isVarargsRequired(), false);
2263 }
2264 @Override
2265 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2266 if (sym.kind >= AMBIGUOUS) {
2267 sym = super.access(env, pos, location, sym);
2268 } else if (allowMethodHandles) {
2269 MethodSymbol msym = (MethodSymbol)sym;
2270 if (msym.isSignaturePolymorphic(types)) {
2271 return findPolymorphicSignatureInstance(env, sym, argtypes);
2272 }
2273 }
2274 return sym;
2275 }
2276 });
2277 }
2279 /** Find or create an implicit method of exactly the given type (after erasure).
2280 * Searches in a side table, not the main scope of the site.
2281 * This emulates the lookup process required by JSR 292 in JVM.
2282 * @param env Attribution environment
2283 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
2284 * @param argtypes The required argument types
2285 */
2286 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2287 final Symbol spMethod,
2288 List<Type> argtypes) {
2289 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2290 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2291 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
2292 if (types.isSameType(mtype, sym.type)) {
2293 return sym;
2294 }
2295 }
2297 // create the desired method
2298 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2299 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2300 @Override
2301 public Symbol baseSymbol() {
2302 return spMethod;
2303 }
2304 };
2305 polymorphicSignatureScope.enter(msym);
2306 return msym;
2307 }
2309 /** Resolve a qualified method identifier, throw a fatal error if not
2310 * found.
2311 * @param pos The position to use for error reporting.
2312 * @param env The environment current at the method invocation.
2313 * @param site The type of the qualifying expression, in which
2314 * identifier is searched.
2315 * @param name The identifier's name.
2316 * @param argtypes The types of the invocation's value arguments.
2317 * @param typeargtypes The types of the invocation's type arguments.
2318 */
2319 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2320 Type site, Name name,
2321 List<Type> argtypes,
2322 List<Type> typeargtypes) {
2323 MethodResolutionContext resolveContext = new MethodResolutionContext();
2324 resolveContext.internalResolution = true;
2325 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2326 site, name, argtypes, typeargtypes);
2327 if (sym.kind == MTH) return (MethodSymbol)sym;
2328 else throw new FatalError(
2329 diags.fragment("fatal.err.cant.locate.meth",
2330 name));
2331 }
2333 /** Resolve constructor.
2334 * @param pos The position to use for error reporting.
2335 * @param env The environment current at the constructor invocation.
2336 * @param site The type of class for which a constructor is searched.
2337 * @param argtypes The types of the constructor invocation's value
2338 * arguments.
2339 * @param typeargtypes The types of the constructor invocation's type
2340 * arguments.
2341 */
2342 Symbol resolveConstructor(DiagnosticPosition pos,
2343 Env<AttrContext> env,
2344 Type site,
2345 List<Type> argtypes,
2346 List<Type> typeargtypes) {
2347 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2348 }
2350 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2351 final DiagnosticPosition pos,
2352 Env<AttrContext> env,
2353 Type site,
2354 List<Type> argtypes,
2355 List<Type> typeargtypes) {
2356 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2357 @Override
2358 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2359 return findConstructor(pos, env, site, argtypes, typeargtypes,
2360 phase.isBoxingRequired(),
2361 phase.isVarargsRequired());
2362 }
2363 });
2364 }
2366 /** Resolve a constructor, throw a fatal error if not found.
2367 * @param pos The position to use for error reporting.
2368 * @param env The environment current at the method invocation.
2369 * @param site The type to be constructed.
2370 * @param argtypes The types of the invocation's value arguments.
2371 * @param typeargtypes The types of the invocation's type arguments.
2372 */
2373 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2374 Type site,
2375 List<Type> argtypes,
2376 List<Type> typeargtypes) {
2377 MethodResolutionContext resolveContext = new MethodResolutionContext();
2378 resolveContext.internalResolution = true;
2379 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2380 if (sym.kind == MTH) return (MethodSymbol)sym;
2381 else throw new FatalError(
2382 diags.fragment("fatal.err.cant.locate.ctor", site));
2383 }
2385 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2386 Type site, List<Type> argtypes,
2387 List<Type> typeargtypes,
2388 boolean allowBoxing,
2389 boolean useVarargs) {
2390 Symbol sym = findMethod(env, site,
2391 names.init, argtypes,
2392 typeargtypes, allowBoxing,
2393 useVarargs, false);
2394 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2395 return sym;
2396 }
2398 /** Resolve constructor using diamond inference.
2399 * @param pos The position to use for error reporting.
2400 * @param env The environment current at the constructor invocation.
2401 * @param site The type of class for which a constructor is searched.
2402 * The scope of this class has been touched in attribution.
2403 * @param argtypes The types of the constructor invocation's value
2404 * arguments.
2405 * @param typeargtypes The types of the constructor invocation's type
2406 * arguments.
2407 */
2408 Symbol resolveDiamond(DiagnosticPosition pos,
2409 Env<AttrContext> env,
2410 Type site,
2411 List<Type> argtypes,
2412 List<Type> typeargtypes) {
2413 return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2414 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2415 @Override
2416 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2417 return findDiamond(env, site, argtypes, typeargtypes,
2418 phase.isBoxingRequired(),
2419 phase.isVarargsRequired());
2420 }
2421 @Override
2422 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2423 if (sym.kind >= AMBIGUOUS) {
2424 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2425 ((InapplicableSymbolError)sym).errCandidate().details :
2426 null;
2427 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2428 @Override
2429 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2430 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2431 String key = details == null ?
2432 "cant.apply.diamond" :
2433 "cant.apply.diamond.1";
2434 return diags.create(dkind, log.currentSource(), pos, key,
2435 diags.fragment("diamond", site.tsym), details);
2436 }
2437 };
2438 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2439 env.info.pendingResolutionPhase = currentResolutionContext.step;
2440 }
2441 return sym;
2442 }});
2443 }
2445 /** This method scans all the constructor symbol in a given class scope -
2446 * assuming that the original scope contains a constructor of the kind:
2447 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2448 * a method check is executed against the modified constructor type:
2449 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2450 * inference. The inferred return type of the synthetic constructor IS
2451 * the inferred type for the diamond operator.
2452 */
2453 private Symbol findDiamond(Env<AttrContext> env,
2454 Type site,
2455 List<Type> argtypes,
2456 List<Type> typeargtypes,
2457 boolean allowBoxing,
2458 boolean useVarargs) {
2459 Symbol bestSoFar = methodNotFound;
2460 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2461 e.scope != null;
2462 e = e.next()) {
2463 final Symbol sym = e.sym;
2464 //- System.out.println(" e " + e.sym);
2465 if (sym.kind == MTH &&
2466 (sym.flags_field & SYNTHETIC) == 0) {
2467 List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
2468 ((ForAll)sym.type).tvars :
2469 List.<Type>nil();
2470 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2471 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2472 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2473 @Override
2474 public Symbol baseSymbol() {
2475 return sym;
2476 }
2477 };
2478 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2479 newConstr,
2480 bestSoFar,
2481 allowBoxing,
2482 useVarargs,
2483 false);
2484 }
2485 }
2486 return bestSoFar;
2487 }
2491 /** Resolve operator.
2492 * @param pos The position to use for error reporting.
2493 * @param optag The tag of the operation tree.
2494 * @param env The environment current at the operation.
2495 * @param argtypes The types of the operands.
2496 */
2497 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2498 Env<AttrContext> env, List<Type> argtypes) {
2499 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2500 try {
2501 currentResolutionContext = new MethodResolutionContext();
2502 Name name = treeinfo.operatorName(optag);
2503 return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
2504 new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
2505 @Override
2506 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2507 return findMethod(env, site, name, argtypes, typeargtypes,
2508 phase.isBoxingRequired(),
2509 phase.isVarargsRequired(), true);
2510 }
2511 @Override
2512 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2513 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2514 false, argtypes, null);
2515 }
2516 });
2517 } finally {
2518 currentResolutionContext = prevResolutionContext;
2519 }
2520 }
2522 /** Resolve operator.
2523 * @param pos The position to use for error reporting.
2524 * @param optag The tag of the operation tree.
2525 * @param env The environment current at the operation.
2526 * @param arg The type of the operand.
2527 */
2528 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2529 return resolveOperator(pos, optag, env, List.of(arg));
2530 }
2532 /** Resolve binary operator.
2533 * @param pos The position to use for error reporting.
2534 * @param optag The tag of the operation tree.
2535 * @param env The environment current at the operation.
2536 * @param left The types of the left operand.
2537 * @param right The types of the right operand.
2538 */
2539 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2540 JCTree.Tag optag,
2541 Env<AttrContext> env,
2542 Type left,
2543 Type right) {
2544 return resolveOperator(pos, optag, env, List.of(left, right));
2545 }
2547 /**
2548 * Resolution of member references is typically done as a single
2549 * overload resolution step, where the argument types A are inferred from
2550 * the target functional descriptor.
2551 *
2552 * If the member reference is a method reference with a type qualifier,
2553 * a two-step lookup process is performed. The first step uses the
2554 * expected argument list A, while the second step discards the first
2555 * type from A (which is treated as a receiver type).
2556 *
2557 * There are two cases in which inference is performed: (i) if the member
2558 * reference is a constructor reference and the qualifier type is raw - in
2559 * which case diamond inference is used to infer a parameterization for the
2560 * type qualifier; (ii) if the member reference is an unbound reference
2561 * where the type qualifier is raw - in that case, during the unbound lookup
2562 * the receiver argument type is used to infer an instantiation for the raw
2563 * qualifier type.
2564 *
2565 * When a multi-step resolution process is exploited, it is an error
2566 * if two candidates are found (ambiguity).
2567 *
2568 * This routine returns a pair (T,S), where S is the member reference symbol,
2569 * and T is the type of the class in which S is defined. This is necessary as
2570 * the type T might be dynamically inferred (i.e. if constructor reference
2571 * has a raw qualifier).
2572 */
2573 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
2574 Env<AttrContext> env,
2575 JCMemberReference referenceTree,
2576 Type site,
2577 Name name, List<Type> argtypes,
2578 List<Type> typeargtypes,
2579 boolean boxingAllowed,
2580 MethodCheck methodCheck) {
2581 MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
2583 ReferenceLookupHelper boundLookupHelper;
2584 if (!name.equals(names.init)) {
2585 //method reference
2586 boundLookupHelper =
2587 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2588 } else if (site.hasTag(ARRAY)) {
2589 //array constructor reference
2590 boundLookupHelper =
2591 new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2592 } else {
2593 //class constructor reference
2594 boundLookupHelper =
2595 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2596 }
2598 //step 1 - bound lookup
2599 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2600 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, methodCheck, boundLookupHelper);
2602 //step 2 - unbound lookup
2603 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
2604 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2605 Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, methodCheck, unboundLookupHelper);
2607 //merge results
2608 Pair<Symbol, ReferenceLookupHelper> res;
2609 if (!lookupSuccess(unboundSym)) {
2610 res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
2611 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2612 } else if (lookupSuccess(boundSym)) {
2613 res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
2614 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2615 } else {
2616 res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
2617 env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
2618 }
2620 return res;
2621 }
2622 //private
2623 boolean lookupSuccess(Symbol s) {
2624 return s.kind == MTH || s.kind == AMBIGUOUS;
2625 }
2627 /**
2628 * Helper for defining custom method-like lookup logic; a lookup helper
2629 * provides hooks for (i) the actual lookup logic and (ii) accessing the
2630 * lookup result (this step might result in compiler diagnostics to be generated)
2631 */
2632 abstract class LookupHelper {
2634 /** name of the symbol to lookup */
2635 Name name;
2637 /** location in which the lookup takes place */
2638 Type site;
2640 /** actual types used during the lookup */
2641 List<Type> argtypes;
2643 /** type arguments used during the lookup */
2644 List<Type> typeargtypes;
2646 /** Max overload resolution phase handled by this helper */
2647 MethodResolutionPhase maxPhase;
2649 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2650 this.name = name;
2651 this.site = site;
2652 this.argtypes = argtypes;
2653 this.typeargtypes = typeargtypes;
2654 this.maxPhase = maxPhase;
2655 }
2657 /**
2658 * Should lookup stop at given phase with given result
2659 */
2660 protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2661 return phase.ordinal() > maxPhase.ordinal() ||
2662 sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
2663 }
2665 /**
2666 * Search for a symbol under a given overload resolution phase - this method
2667 * is usually called several times, once per each overload resolution phase
2668 */
2669 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
2671 /**
2672 * Validate the result of the lookup
2673 */
2674 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
2675 }
2677 abstract class BasicLookupHelper extends LookupHelper {
2679 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
2680 this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
2681 }
2683 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2684 super(name, site, argtypes, typeargtypes, maxPhase);
2685 }
2687 @Override
2688 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2689 if (sym.kind == AMBIGUOUS) {
2690 AmbiguityError a_err = (AmbiguityError)sym;
2691 sym = a_err.mergeAbstracts(site);
2692 }
2693 if (sym.kind >= AMBIGUOUS) {
2694 //if nothing is found return the 'first' error
2695 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
2696 }
2697 return sym;
2698 }
2699 }
2701 /**
2702 * Helper class for member reference lookup. A reference lookup helper
2703 * defines the basic logic for member reference lookup; a method gives
2704 * access to an 'unbound' helper used to perform an unbound member
2705 * reference lookup.
2706 */
2707 abstract class ReferenceLookupHelper extends LookupHelper {
2709 /** The member reference tree */
2710 JCMemberReference referenceTree;
2712 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2713 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2714 super(name, site, argtypes, typeargtypes, maxPhase);
2715 this.referenceTree = referenceTree;
2717 }
2719 /**
2720 * Returns an unbound version of this lookup helper. By default, this
2721 * method returns an dummy lookup helper.
2722 */
2723 ReferenceLookupHelper unboundLookup() {
2724 //dummy loopkup helper that always return 'methodNotFound'
2725 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
2726 @Override
2727 ReferenceLookupHelper unboundLookup() {
2728 return this;
2729 }
2730 @Override
2731 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2732 return methodNotFound;
2733 }
2734 @Override
2735 ReferenceKind referenceKind(Symbol sym) {
2736 Assert.error();
2737 return null;
2738 }
2739 };
2740 }
2742 /**
2743 * Get the kind of the member reference
2744 */
2745 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
2747 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2748 if (sym.kind == AMBIGUOUS) {
2749 AmbiguityError a_err = (AmbiguityError)sym;
2750 sym = a_err.mergeAbstracts(site);
2751 }
2752 //skip error reporting
2753 return sym;
2754 }
2755 }
2757 /**
2758 * Helper class for method reference lookup. The lookup logic is based
2759 * upon Resolve.findMethod; in certain cases, this helper class has a
2760 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
2761 * In such cases, non-static lookup results are thrown away.
2762 */
2763 class MethodReferenceLookupHelper extends ReferenceLookupHelper {
2765 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2766 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2767 super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2768 }
2770 @Override
2771 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2772 return findMethod(env, site, name, argtypes, typeargtypes,
2773 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2774 }
2776 @Override
2777 ReferenceLookupHelper unboundLookup() {
2778 if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
2779 argtypes.nonEmpty() &&
2780 (argtypes.head.hasTag(NONE) || types.isSubtypeUnchecked(argtypes.head, site))) {
2781 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
2782 site, argtypes, typeargtypes, maxPhase);
2783 } else {
2784 return super.unboundLookup();
2785 }
2786 }
2788 @Override
2789 ReferenceKind referenceKind(Symbol sym) {
2790 if (sym.isStatic()) {
2791 return ReferenceKind.STATIC;
2792 } else {
2793 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
2794 return selName != null && selName == names._super ?
2795 ReferenceKind.SUPER :
2796 ReferenceKind.BOUND;
2797 }
2798 }
2799 }
2801 /**
2802 * Helper class for unbound method reference lookup. Essentially the same
2803 * as the basic method reference lookup helper; main difference is that static
2804 * lookup results are thrown away. If qualifier type is raw, an attempt to
2805 * infer a parameterized type is made using the first actual argument (that
2806 * would otherwise be ignored during the lookup).
2807 */
2808 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
2810 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2811 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2812 super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
2813 if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
2814 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
2815 this.site = asSuperSite;
2816 }
2817 }
2819 @Override
2820 ReferenceLookupHelper unboundLookup() {
2821 return this;
2822 }
2824 @Override
2825 ReferenceKind referenceKind(Symbol sym) {
2826 return ReferenceKind.UNBOUND;
2827 }
2828 }
2830 /**
2831 * Helper class for array constructor lookup; an array constructor lookup
2832 * is simulated by looking up a method that returns the array type specified
2833 * as qualifier, and that accepts a single int parameter (size of the array).
2834 */
2835 class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2837 ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2838 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2839 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2840 }
2842 @Override
2843 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2844 Scope sc = new Scope(syms.arrayClass);
2845 MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
2846 arrayConstr.type = new MethodType(List.of(syms.intType), site, List.<Type>nil(), syms.methodClass);
2847 sc.enter(arrayConstr);
2848 return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
2849 }
2851 @Override
2852 ReferenceKind referenceKind(Symbol sym) {
2853 return ReferenceKind.ARRAY_CTOR;
2854 }
2855 }
2857 /**
2858 * Helper class for constructor reference lookup. The lookup logic is based
2859 * upon either Resolve.findMethod or Resolve.findDiamond - depending on
2860 * whether the constructor reference needs diamond inference (this is the case
2861 * if the qualifier type is raw). A special erroneous symbol is returned
2862 * if the lookup returns the constructor of an inner class and there's no
2863 * enclosing instance in scope.
2864 */
2865 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2867 boolean needsInference;
2869 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2870 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2871 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2872 if (site.isRaw()) {
2873 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
2874 needsInference = true;
2875 }
2876 }
2878 @Override
2879 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2880 Symbol sym = needsInference ?
2881 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
2882 findMethod(env, site, name, argtypes, typeargtypes,
2883 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2884 return sym.kind != MTH ||
2885 site.getEnclosingType().hasTag(NONE) ||
2886 hasEnclosingInstance(env, site) ?
2887 sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
2888 @Override
2889 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2890 return diags.create(dkind, log.currentSource(), pos,
2891 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
2892 }
2893 };
2894 }
2896 @Override
2897 ReferenceKind referenceKind(Symbol sym) {
2898 return site.getEnclosingType().hasTag(NONE) ?
2899 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
2900 }
2901 }
2903 /**
2904 * Main overload resolution routine. On each overload resolution step, a
2905 * lookup helper class is used to perform the method/constructor lookup;
2906 * at the end of the lookup, the helper is used to validate the results
2907 * (this last step might trigger overload resolution diagnostics).
2908 */
2909 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
2910 MethodResolutionContext resolveContext = new MethodResolutionContext();
2911 resolveContext.methodCheck = methodCheck;
2912 return lookupMethod(env, pos, location, resolveContext, lookupHelper);
2913 }
2915 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
2916 MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
2917 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2918 try {
2919 Symbol bestSoFar = methodNotFound;
2920 currentResolutionContext = resolveContext;
2921 for (MethodResolutionPhase phase : methodResolutionSteps) {
2922 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
2923 lookupHelper.shouldStop(bestSoFar, phase)) break;
2924 MethodResolutionPhase prevPhase = currentResolutionContext.step;
2925 Symbol prevBest = bestSoFar;
2926 currentResolutionContext.step = phase;
2927 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
2928 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
2929 }
2930 return lookupHelper.access(env, pos, location, bestSoFar);
2931 } finally {
2932 currentResolutionContext = prevResolutionContext;
2933 }
2934 }
2936 /**
2937 * Resolve `c.name' where name == this or name == super.
2938 * @param pos The position to use for error reporting.
2939 * @param env The environment current at the expression.
2940 * @param c The qualifier.
2941 * @param name The identifier's name.
2942 */
2943 Symbol resolveSelf(DiagnosticPosition pos,
2944 Env<AttrContext> env,
2945 TypeSymbol c,
2946 Name name) {
2947 Env<AttrContext> env1 = env;
2948 boolean staticOnly = false;
2949 while (env1.outer != null) {
2950 if (isStatic(env1)) staticOnly = true;
2951 if (env1.enclClass.sym == c) {
2952 Symbol sym = env1.info.scope.lookup(name).sym;
2953 if (sym != null) {
2954 if (staticOnly) sym = new StaticError(sym);
2955 return accessBase(sym, pos, env.enclClass.sym.type,
2956 name, true);
2957 }
2958 }
2959 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2960 env1 = env1.outer;
2961 }
2962 if (allowDefaultMethods && c.isInterface() &&
2963 name == names._super && !isStatic(env) &&
2964 types.isDirectSuperInterface(c, env.enclClass.sym)) {
2965 //this might be a default super call if one of the superinterfaces is 'c'
2966 for (Type t : pruneInterfaces(env.enclClass.type)) {
2967 if (t.tsym == c) {
2968 env.info.defaultSuperCallSite = t;
2969 return new VarSymbol(0, names._super,
2970 types.asSuper(env.enclClass.type, c), env.enclClass.sym);
2971 }
2972 }
2973 //find a direct superinterface that is a subtype of 'c'
2974 for (Type i : types.interfaces(env.enclClass.type)) {
2975 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
2976 log.error(pos, "illegal.default.super.call", c,
2977 diags.fragment("redundant.supertype", c, i));
2978 return syms.errSymbol;
2979 }
2980 }
2981 Assert.error();
2982 }
2983 log.error(pos, "not.encl.class", c);
2984 return syms.errSymbol;
2985 }
2986 //where
2987 private List<Type> pruneInterfaces(Type t) {
2988 ListBuffer<Type> result = ListBuffer.lb();
2989 for (Type t1 : types.interfaces(t)) {
2990 boolean shouldAdd = true;
2991 for (Type t2 : types.interfaces(t)) {
2992 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
2993 shouldAdd = false;
2994 }
2995 }
2996 if (shouldAdd) {
2997 result.append(t1);
2998 }
2999 }
3000 return result.toList();
3001 }
3004 /**
3005 * Resolve `c.this' for an enclosing class c that contains the
3006 * named member.
3007 * @param pos The position to use for error reporting.
3008 * @param env The environment current at the expression.
3009 * @param member The member that must be contained in the result.
3010 */
3011 Symbol resolveSelfContaining(DiagnosticPosition pos,
3012 Env<AttrContext> env,
3013 Symbol member,
3014 boolean isSuperCall) {
3015 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
3016 if (sym == null) {
3017 log.error(pos, "encl.class.required", member);
3018 return syms.errSymbol;
3019 } else {
3020 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
3021 }
3022 }
3024 boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
3025 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
3026 return encl != null && encl.kind < ERRONEOUS;
3027 }
3029 private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
3030 Symbol member,
3031 boolean isSuperCall) {
3032 Name name = names._this;
3033 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
3034 boolean staticOnly = false;
3035 if (env1 != null) {
3036 while (env1 != null && env1.outer != null) {
3037 if (isStatic(env1)) staticOnly = true;
3038 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
3039 Symbol sym = env1.info.scope.lookup(name).sym;
3040 if (sym != null) {
3041 if (staticOnly) sym = new StaticError(sym);
3042 return sym;
3043 }
3044 }
3045 if ((env1.enclClass.sym.flags() & STATIC) != 0)
3046 staticOnly = true;
3047 env1 = env1.outer;
3048 }
3049 }
3050 return null;
3051 }
3053 /**
3054 * Resolve an appropriate implicit this instance for t's container.
3055 * JLS 8.8.5.1 and 15.9.2
3056 */
3057 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
3058 return resolveImplicitThis(pos, env, t, false);
3059 }
3061 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
3062 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
3063 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
3064 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
3065 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
3066 log.error(pos, "cant.ref.before.ctor.called", "this");
3067 return thisType;
3068 }
3070 /* ***************************************************************************
3071 * ResolveError classes, indicating error situations when accessing symbols
3072 ****************************************************************************/
3074 //used by TransTypes when checking target type of synthetic cast
3075 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
3076 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
3077 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
3078 }
3079 //where
3080 private void logResolveError(ResolveError error,
3081 DiagnosticPosition pos,
3082 Symbol location,
3083 Type site,
3084 Name name,
3085 List<Type> argtypes,
3086 List<Type> typeargtypes) {
3087 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3088 pos, location, site, name, argtypes, typeargtypes);
3089 if (d != null) {
3090 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
3091 log.report(d);
3092 }
3093 }
3095 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
3097 public Object methodArguments(List<Type> argtypes) {
3098 if (argtypes == null || argtypes.isEmpty()) {
3099 return noArgs;
3100 } else {
3101 ListBuffer<Object> diagArgs = ListBuffer.lb();
3102 for (Type t : argtypes) {
3103 if (t.hasTag(DEFERRED)) {
3104 diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3105 } else {
3106 diagArgs.append(t);
3107 }
3108 }
3109 return diagArgs;
3110 }
3111 }
3113 /**
3114 * Root class for resolution errors. Subclass of ResolveError
3115 * represent a different kinds of resolution error - as such they must
3116 * specify how they map into concrete compiler diagnostics.
3117 */
3118 abstract class ResolveError extends Symbol {
3120 /** The name of the kind of error, for debugging only. */
3121 final String debugName;
3123 ResolveError(int kind, String debugName) {
3124 super(kind, 0, null, null, null);
3125 this.debugName = debugName;
3126 }
3128 @Override
3129 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3130 throw new AssertionError();
3131 }
3133 @Override
3134 public String toString() {
3135 return debugName;
3136 }
3138 @Override
3139 public boolean exists() {
3140 return false;
3141 }
3143 /**
3144 * Create an external representation for this erroneous symbol to be
3145 * used during attribution - by default this returns the symbol of a
3146 * brand new error type which stores the original type found
3147 * during resolution.
3148 *
3149 * @param name the name used during resolution
3150 * @param location the location from which the symbol is accessed
3151 */
3152 protected Symbol access(Name name, TypeSymbol location) {
3153 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3154 }
3156 /**
3157 * Create a diagnostic representing this resolution error.
3158 *
3159 * @param dkind The kind of the diagnostic to be created (e.g error).
3160 * @param pos The position to be used for error reporting.
3161 * @param site The original type from where the selection took place.
3162 * @param name The name of the symbol to be resolved.
3163 * @param argtypes The invocation's value arguments,
3164 * if we looked for a method.
3165 * @param typeargtypes The invocation's type arguments,
3166 * if we looked for a method.
3167 */
3168 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3169 DiagnosticPosition pos,
3170 Symbol location,
3171 Type site,
3172 Name name,
3173 List<Type> argtypes,
3174 List<Type> typeargtypes);
3175 }
3177 /**
3178 * This class is the root class of all resolution errors caused by
3179 * an invalid symbol being found during resolution.
3180 */
3181 abstract class InvalidSymbolError extends ResolveError {
3183 /** The invalid symbol found during resolution */
3184 Symbol sym;
3186 InvalidSymbolError(int kind, Symbol sym, String debugName) {
3187 super(kind, debugName);
3188 this.sym = sym;
3189 }
3191 @Override
3192 public boolean exists() {
3193 return true;
3194 }
3196 @Override
3197 public String toString() {
3198 return super.toString() + " wrongSym=" + sym;
3199 }
3201 @Override
3202 public Symbol access(Name name, TypeSymbol location) {
3203 if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
3204 return types.createErrorType(name, location, sym.type).tsym;
3205 else
3206 return sym;
3207 }
3208 }
3210 /**
3211 * InvalidSymbolError error class indicating that a symbol matching a
3212 * given name does not exists in a given site.
3213 */
3214 class SymbolNotFoundError extends ResolveError {
3216 SymbolNotFoundError(int kind) {
3217 super(kind, "symbol not found error");
3218 }
3220 @Override
3221 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3222 DiagnosticPosition pos,
3223 Symbol location,
3224 Type site,
3225 Name name,
3226 List<Type> argtypes,
3227 List<Type> typeargtypes) {
3228 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3229 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3230 if (name == names.error)
3231 return null;
3233 if (syms.operatorNames.contains(name)) {
3234 boolean isUnaryOp = argtypes.size() == 1;
3235 String key = argtypes.size() == 1 ?
3236 "operator.cant.be.applied" :
3237 "operator.cant.be.applied.1";
3238 Type first = argtypes.head;
3239 Type second = !isUnaryOp ? argtypes.tail.head : null;
3240 return diags.create(dkind, log.currentSource(), pos,
3241 key, name, first, second);
3242 }
3243 boolean hasLocation = false;
3244 if (location == null) {
3245 location = site.tsym;
3246 }
3247 if (!location.name.isEmpty()) {
3248 if (location.kind == PCK && !site.tsym.exists()) {
3249 return diags.create(dkind, log.currentSource(), pos,
3250 "doesnt.exist", location);
3251 }
3252 hasLocation = !location.name.equals(names._this) &&
3253 !location.name.equals(names._super);
3254 }
3255 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
3256 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
3257 Name idname = isConstructor ? site.tsym.name : name;
3258 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3259 if (hasLocation) {
3260 return diags.create(dkind, log.currentSource(), pos,
3261 errKey, kindname, idname, //symbol kindname, name
3262 typeargtypes, args(argtypes), //type parameters and arguments (if any)
3263 getLocationDiag(location, site)); //location kindname, type
3264 }
3265 else {
3266 return diags.create(dkind, log.currentSource(), pos,
3267 errKey, kindname, idname, //symbol kindname, name
3268 typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3269 }
3270 }
3271 //where
3272 private Object args(List<Type> args) {
3273 return args.isEmpty() ? args : methodArguments(args);
3274 }
3276 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3277 String key = "cant.resolve";
3278 String suffix = hasLocation ? ".location" : "";
3279 switch (kindname) {
3280 case METHOD:
3281 case CONSTRUCTOR: {
3282 suffix += ".args";
3283 suffix += hasTypeArgs ? ".params" : "";
3284 }
3285 }
3286 return key + suffix;
3287 }
3288 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3289 if (location.kind == VAR) {
3290 return diags.fragment("location.1",
3291 kindName(location),
3292 location,
3293 location.type);
3294 } else {
3295 return diags.fragment("location",
3296 typeKindName(site),
3297 site,
3298 null);
3299 }
3300 }
3301 }
3303 /**
3304 * InvalidSymbolError error class indicating that a given symbol
3305 * (either a method, a constructor or an operand) is not applicable
3306 * given an actual arguments/type argument list.
3307 */
3308 class InapplicableSymbolError extends ResolveError {
3310 protected MethodResolutionContext resolveContext;
3312 InapplicableSymbolError(MethodResolutionContext context) {
3313 this(WRONG_MTH, "inapplicable symbol error", context);
3314 }
3316 protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
3317 super(kind, debugName);
3318 this.resolveContext = context;
3319 }
3321 @Override
3322 public String toString() {
3323 return super.toString();
3324 }
3326 @Override
3327 public boolean exists() {
3328 return true;
3329 }
3331 @Override
3332 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3333 DiagnosticPosition pos,
3334 Symbol location,
3335 Type site,
3336 Name name,
3337 List<Type> argtypes,
3338 List<Type> typeargtypes) {
3339 if (name == names.error)
3340 return null;
3342 if (syms.operatorNames.contains(name)) {
3343 boolean isUnaryOp = argtypes.size() == 1;
3344 String key = argtypes.size() == 1 ?
3345 "operator.cant.be.applied" :
3346 "operator.cant.be.applied.1";
3347 Type first = argtypes.head;
3348 Type second = !isUnaryOp ? argtypes.tail.head : null;
3349 return diags.create(dkind, log.currentSource(), pos,
3350 key, name, first, second);
3351 }
3352 else {
3353 Candidate c = errCandidate();
3354 if (compactMethodDiags) {
3355 for (Map.Entry<Template, DiagnosticRewriter> _entry :
3356 MethodResolutionDiagHelper.rewriters.entrySet()) {
3357 if (_entry.getKey().matches(c.details)) {
3358 JCDiagnostic simpleDiag =
3359 _entry.getValue().rewriteDiagnostic(diags, pos,
3360 log.currentSource(), dkind, c.details);
3361 simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
3362 return simpleDiag;
3363 }
3364 }
3365 }
3366 Symbol ws = c.sym.asMemberOf(site, types);
3367 return diags.create(dkind, log.currentSource(), pos,
3368 "cant.apply.symbol",
3369 kindName(ws),
3370 ws.name == names.init ? ws.owner.name : ws.name,
3371 methodArguments(ws.type.getParameterTypes()),
3372 methodArguments(argtypes),
3373 kindName(ws.owner),
3374 ws.owner.type,
3375 c.details);
3376 }
3377 }
3379 @Override
3380 public Symbol access(Name name, TypeSymbol location) {
3381 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3382 }
3384 private Candidate errCandidate() {
3385 Candidate bestSoFar = null;
3386 for (Candidate c : resolveContext.candidates) {
3387 if (c.isApplicable()) continue;
3388 bestSoFar = c;
3389 }
3390 Assert.checkNonNull(bestSoFar);
3391 return bestSoFar;
3392 }
3393 }
3395 /**
3396 * ResolveError error class indicating that a set of symbols
3397 * (either methods, constructors or operands) is not applicable
3398 * given an actual arguments/type argument list.
3399 */
3400 class InapplicableSymbolsError extends InapplicableSymbolError {
3402 InapplicableSymbolsError(MethodResolutionContext context) {
3403 super(WRONG_MTHS, "inapplicable symbols", context);
3404 }
3406 @Override
3407 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3408 DiagnosticPosition pos,
3409 Symbol location,
3410 Type site,
3411 Name name,
3412 List<Type> argtypes,
3413 List<Type> typeargtypes) {
3414 Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
3415 Map<Symbol, JCDiagnostic> filteredCandidates = filterCandidates(candidatesMap);
3416 if (filteredCandidates.isEmpty()) {
3417 filteredCandidates = candidatesMap;
3418 }
3419 boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
3420 if (filteredCandidates.size() > 1) {
3421 JCDiagnostic err = diags.create(dkind,
3422 null,
3423 truncatedDiag ?
3424 EnumSet.of(DiagnosticFlag.COMPRESSED) :
3425 EnumSet.noneOf(DiagnosticFlag.class),
3426 log.currentSource(),
3427 pos,
3428 "cant.apply.symbols",
3429 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
3430 name == names.init ? site.tsym.name : name,
3431 methodArguments(argtypes));
3432 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
3433 } else if (filteredCandidates.size() == 1) {
3434 JCDiagnostic d = new InapplicableSymbolError(resolveContext).getDiagnostic(dkind, pos,
3435 location, site, name, argtypes, typeargtypes);
3436 if (truncatedDiag) {
3437 d.setFlag(DiagnosticFlag.COMPRESSED);
3438 }
3439 return d;
3440 } else {
3441 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3442 location, site, name, argtypes, typeargtypes);
3443 }
3444 }
3445 //where
3446 private Map<Symbol, JCDiagnostic> mapCandidates() {
3447 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
3448 for (Candidate c : resolveContext.candidates) {
3449 if (c.isApplicable()) continue;
3450 candidates.put(c.sym, c.details);
3451 }
3452 return candidates;
3453 }
3455 Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
3456 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
3457 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3458 JCDiagnostic d = _entry.getValue();
3459 if (!compactMethodDiags ||
3460 !new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
3461 candidates.put(_entry.getKey(), d);
3462 }
3463 }
3464 return candidates;
3465 }
3467 private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
3468 List<JCDiagnostic> details = List.nil();
3469 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3470 Symbol sym = _entry.getKey();
3471 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3472 Kinds.kindName(sym),
3473 sym.location(site, types),
3474 sym.asMemberOf(site, types),
3475 _entry.getValue());
3476 details = details.prepend(detailDiag);
3477 }
3478 //typically members are visited in reverse order (see Scope)
3479 //so we need to reverse the candidate list so that candidates
3480 //conform to source order
3481 return details;
3482 }
3483 }
3485 /**
3486 * An InvalidSymbolError error class indicating that a symbol is not
3487 * accessible from a given site
3488 */
3489 class AccessError extends InvalidSymbolError {
3491 private Env<AttrContext> env;
3492 private Type site;
3494 AccessError(Symbol sym) {
3495 this(null, null, sym);
3496 }
3498 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3499 super(HIDDEN, sym, "access error");
3500 this.env = env;
3501 this.site = site;
3502 if (debugResolve)
3503 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3504 }
3506 @Override
3507 public boolean exists() {
3508 return false;
3509 }
3511 @Override
3512 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3513 DiagnosticPosition pos,
3514 Symbol location,
3515 Type site,
3516 Name name,
3517 List<Type> argtypes,
3518 List<Type> typeargtypes) {
3519 if (sym.owner.type.hasTag(ERROR))
3520 return null;
3522 if (sym.name == names.init && sym.owner != site.tsym) {
3523 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3524 pos, location, site, name, argtypes, typeargtypes);
3525 }
3526 else if ((sym.flags() & PUBLIC) != 0
3527 || (env != null && this.site != null
3528 && !isAccessible(env, this.site))) {
3529 return diags.create(dkind, log.currentSource(),
3530 pos, "not.def.access.class.intf.cant.access",
3531 sym, sym.location());
3532 }
3533 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3534 return diags.create(dkind, log.currentSource(),
3535 pos, "report.access", sym,
3536 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3537 sym.location());
3538 }
3539 else {
3540 return diags.create(dkind, log.currentSource(),
3541 pos, "not.def.public.cant.access", sym, sym.location());
3542 }
3543 }
3544 }
3546 /**
3547 * InvalidSymbolError error class indicating that an instance member
3548 * has erroneously been accessed from a static context.
3549 */
3550 class StaticError extends InvalidSymbolError {
3552 StaticError(Symbol sym) {
3553 super(STATICERR, sym, "static error");
3554 }
3556 @Override
3557 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3558 DiagnosticPosition pos,
3559 Symbol location,
3560 Type site,
3561 Name name,
3562 List<Type> argtypes,
3563 List<Type> typeargtypes) {
3564 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3565 ? types.erasure(sym.type).tsym
3566 : sym);
3567 return diags.create(dkind, log.currentSource(), pos,
3568 "non-static.cant.be.ref", kindName(sym), errSym);
3569 }
3570 }
3572 /**
3573 * InvalidSymbolError error class indicating that a pair of symbols
3574 * (either methods, constructors or operands) are ambiguous
3575 * given an actual arguments/type argument list.
3576 */
3577 class AmbiguityError extends ResolveError {
3579 /** The other maximally specific symbol */
3580 List<Symbol> ambiguousSyms = List.nil();
3582 @Override
3583 public boolean exists() {
3584 return true;
3585 }
3587 AmbiguityError(Symbol sym1, Symbol sym2) {
3588 super(AMBIGUOUS, "ambiguity error");
3589 ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3590 }
3592 private List<Symbol> flatten(Symbol sym) {
3593 if (sym.kind == AMBIGUOUS) {
3594 return ((AmbiguityError)sym).ambiguousSyms;
3595 } else {
3596 return List.of(sym);
3597 }
3598 }
3600 AmbiguityError addAmbiguousSymbol(Symbol s) {
3601 ambiguousSyms = ambiguousSyms.prepend(s);
3602 return this;
3603 }
3605 @Override
3606 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3607 DiagnosticPosition pos,
3608 Symbol location,
3609 Type site,
3610 Name name,
3611 List<Type> argtypes,
3612 List<Type> typeargtypes) {
3613 List<Symbol> diagSyms = ambiguousSyms.reverse();
3614 Symbol s1 = diagSyms.head;
3615 Symbol s2 = diagSyms.tail.head;
3616 Name sname = s1.name;
3617 if (sname == names.init) sname = s1.owner.name;
3618 return diags.create(dkind, log.currentSource(),
3619 pos, "ref.ambiguous", sname,
3620 kindName(s1),
3621 s1,
3622 s1.location(site, types),
3623 kindName(s2),
3624 s2,
3625 s2.location(site, types));
3626 }
3628 /**
3629 * If multiple applicable methods are found during overload and none of them
3630 * is more specific than the others, attempt to merge their signatures.
3631 */
3632 Symbol mergeAbstracts(Type site) {
3633 Symbol fst = ambiguousSyms.last();
3634 Symbol res = fst;
3635 for (Symbol s : ambiguousSyms.reverse()) {
3636 Type mt1 = types.memberType(site, res);
3637 Type mt2 = types.memberType(site, s);
3638 if ((s.flags() & ABSTRACT) == 0 ||
3639 !types.overrideEquivalent(mt1, mt2) ||
3640 !types.isSameTypes(fst.erasure(types).getParameterTypes(),
3641 s.erasure(types).getParameterTypes())) {
3642 //ambiguity cannot be resolved
3643 return this;
3644 } else {
3645 Type mst = mostSpecificReturnType(mt1, mt2);
3646 if (mst == null) {
3647 // Theoretically, this can't happen, but it is possible
3648 // due to error recovery or mixing incompatible class files
3649 return this;
3650 }
3651 Symbol mostSpecific = mst == mt1 ? res : s;
3652 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
3653 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
3654 res = new MethodSymbol(
3655 mostSpecific.flags(),
3656 mostSpecific.name,
3657 newSig,
3658 mostSpecific.owner);
3659 }
3660 }
3661 return res;
3662 }
3664 @Override
3665 protected Symbol access(Name name, TypeSymbol location) {
3666 Symbol firstAmbiguity = ambiguousSyms.last();
3667 return firstAmbiguity.kind == TYP ?
3668 types.createErrorType(name, location, firstAmbiguity.type).tsym :
3669 firstAmbiguity;
3670 }
3671 }
3673 class BadVarargsMethod extends ResolveError {
3675 ResolveError delegatedError;
3677 BadVarargsMethod(ResolveError delegatedError) {
3678 super(delegatedError.kind, "badVarargs");
3679 this.delegatedError = delegatedError;
3680 }
3682 @Override
3683 public Symbol baseSymbol() {
3684 return delegatedError.baseSymbol();
3685 }
3687 @Override
3688 protected Symbol access(Name name, TypeSymbol location) {
3689 return delegatedError.access(name, location);
3690 }
3692 @Override
3693 public boolean exists() {
3694 return true;
3695 }
3697 @Override
3698 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
3699 return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
3700 }
3701 }
3703 /**
3704 * Helper class for method resolution diagnostic simplification.
3705 * Certain resolution diagnostic are rewritten as simpler diagnostic
3706 * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
3707 * is stripped away, as it doesn't carry additional info. The logic
3708 * for matching a given diagnostic is given in terms of a template
3709 * hierarchy: a diagnostic template can be specified programmatically,
3710 * so that only certain diagnostics are matched. Each templete is then
3711 * associated with a rewriter object that carries out the task of rewtiting
3712 * the diagnostic to a simpler one.
3713 */
3714 static class MethodResolutionDiagHelper {
3716 /**
3717 * A diagnostic rewriter transforms a method resolution diagnostic
3718 * into a simpler one
3719 */
3720 interface DiagnosticRewriter {
3721 JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3722 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3723 DiagnosticType preferredKind, JCDiagnostic d);
3724 }
3726 /**
3727 * A diagnostic template is made up of two ingredients: (i) a regular
3728 * expression for matching a diagnostic key and (ii) a list of sub-templates
3729 * for matching diagnostic arguments.
3730 */
3731 static class Template {
3733 /** regex used to match diag key */
3734 String regex;
3736 /** templates used to match diagnostic args */
3737 Template[] subTemplates;
3739 Template(String key, Template... subTemplates) {
3740 this.regex = key;
3741 this.subTemplates = subTemplates;
3742 }
3744 /**
3745 * Returns true if the regex matches the diagnostic key and if
3746 * all diagnostic arguments are matches by corresponding sub-templates.
3747 */
3748 boolean matches(Object o) {
3749 JCDiagnostic d = (JCDiagnostic)o;
3750 Object[] args = d.getArgs();
3751 if (!d.getCode().matches(regex) ||
3752 subTemplates.length != d.getArgs().length) {
3753 return false;
3754 }
3755 for (int i = 0; i < args.length ; i++) {
3756 if (!subTemplates[i].matches(args[i])) {
3757 return false;
3758 }
3759 }
3760 return true;
3761 }
3762 }
3764 /** a dummy template that match any diagnostic argument */
3765 static final Template skip = new Template("") {
3766 @Override
3767 boolean matches(Object d) {
3768 return true;
3769 }
3770 };
3772 /** rewriter map used for method resolution simplification */
3773 static final Map<Template, DiagnosticRewriter> rewriters =
3774 new LinkedHashMap<Template, DiagnosticRewriter>();
3776 static {
3777 String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
3778 rewriters.put(new Template(argMismatchRegex, new Template("(.*)(bad.arg.types.in.lambda)", skip, skip)),
3779 new DiagnosticRewriter() {
3780 @Override
3781 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3782 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3783 DiagnosticType preferredKind, JCDiagnostic d) {
3784 return (JCDiagnostic)((JCDiagnostic)d.getArgs()[0]).getArgs()[1];
3785 }
3786 });
3788 rewriters.put(new Template(argMismatchRegex, skip),
3789 new DiagnosticRewriter() {
3790 @Override
3791 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3792 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3793 DiagnosticType preferredKind, JCDiagnostic d) {
3794 JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
3795 return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
3796 "prob.found.req", cause);
3797 }
3798 });
3799 }
3800 }
3802 enum MethodResolutionPhase {
3803 BASIC(false, false),
3804 BOX(true, false),
3805 VARARITY(true, true) {
3806 @Override
3807 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
3808 switch (sym.kind) {
3809 case WRONG_MTH:
3810 return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
3811 bestSoFar :
3812 sym;
3813 case ABSENT_MTH:
3814 return bestSoFar;
3815 default:
3816 return sym;
3817 }
3818 }
3819 };
3821 final boolean isBoxingRequired;
3822 final boolean isVarargsRequired;
3824 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
3825 this.isBoxingRequired = isBoxingRequired;
3826 this.isVarargsRequired = isVarargsRequired;
3827 }
3829 public boolean isBoxingRequired() {
3830 return isBoxingRequired;
3831 }
3833 public boolean isVarargsRequired() {
3834 return isVarargsRequired;
3835 }
3837 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
3838 return (varargsEnabled || !isVarargsRequired) &&
3839 (boxingEnabled || !isBoxingRequired);
3840 }
3842 public Symbol mergeResults(Symbol prev, Symbol sym) {
3843 return sym;
3844 }
3845 }
3847 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
3849 /**
3850 * A resolution context is used to keep track of intermediate results of
3851 * overload resolution, such as list of method that are not applicable
3852 * (used to generate more precise diagnostics) and so on. Resolution contexts
3853 * can be nested - this means that when each overload resolution routine should
3854 * work within the resolution context it created.
3855 */
3856 class MethodResolutionContext {
3858 private List<Candidate> candidates = List.nil();
3860 MethodResolutionPhase step = null;
3862 MethodCheck methodCheck = resolveMethodCheck;
3864 private boolean internalResolution = false;
3865 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
3867 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
3868 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
3869 candidates = candidates.append(c);
3870 }
3872 void addApplicableCandidate(Symbol sym, Type mtype) {
3873 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
3874 candidates = candidates.append(c);
3875 }
3877 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
3878 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
3879 }
3881 /**
3882 * This class represents an overload resolution candidate. There are two
3883 * kinds of candidates: applicable methods and inapplicable methods;
3884 * applicable methods have a pointer to the instantiated method type,
3885 * while inapplicable candidates contain further details about the
3886 * reason why the method has been considered inapplicable.
3887 */
3888 @SuppressWarnings("overrides")
3889 class Candidate {
3891 final MethodResolutionPhase step;
3892 final Symbol sym;
3893 final JCDiagnostic details;
3894 final Type mtype;
3896 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
3897 this.step = step;
3898 this.sym = sym;
3899 this.details = details;
3900 this.mtype = mtype;
3901 }
3903 @Override
3904 public boolean equals(Object o) {
3905 if (o instanceof Candidate) {
3906 Symbol s1 = this.sym;
3907 Symbol s2 = ((Candidate)o).sym;
3908 if ((s1 != s2 &&
3909 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
3910 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
3911 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
3912 return true;
3913 }
3914 return false;
3915 }
3917 boolean isApplicable() {
3918 return mtype != null;
3919 }
3920 }
3922 DeferredAttr.AttrMode attrMode() {
3923 return attrMode;
3924 }
3926 boolean internal() {
3927 return internalResolution;
3928 }
3929 }
3931 MethodResolutionContext currentResolutionContext = null;
3932 }