Mon, 26 Mar 2012 15:28:49 +0100
7133185: Update 292 overload resolution logic to match JLS
Summary: Re-implement special overload resolution support for method handles according to the JLS SE 7 definition
Reviewed-by: jjg, dlsmith, jrose
1 /*
2 * Copyright (c) 1999, 2012, 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.Type.*;
31 import com.sun.tools.javac.code.Symbol.*;
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.Resolve.MethodResolutionContext.Candidate;
35 import com.sun.tools.javac.jvm.*;
36 import com.sun.tools.javac.tree.*;
37 import com.sun.tools.javac.tree.JCTree.*;
38 import com.sun.tools.javac.util.*;
39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
40 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.EnumMap;
46 import java.util.EnumSet;
47 import java.util.HashSet;
48 import java.util.Map;
49 import java.util.Set;
51 import javax.lang.model.element.ElementVisitor;
53 import static com.sun.tools.javac.code.Flags.*;
54 import static com.sun.tools.javac.code.Flags.BLOCK;
55 import static com.sun.tools.javac.code.Kinds.*;
56 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
57 import static com.sun.tools.javac.code.TypeTags.*;
58 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
59 import static com.sun.tools.javac.tree.JCTree.Tag.*;
61 /** Helper class for name resolution, used mostly by the attribution phase.
62 *
63 * <p><b>This is NOT part of any supported API.
64 * If you write code that depends on this, you do so at your own risk.
65 * This code and its internal interfaces are subject to change or
66 * deletion without notice.</b>
67 */
68 public class Resolve {
69 protected static final Context.Key<Resolve> resolveKey =
70 new Context.Key<Resolve>();
72 Names names;
73 Log log;
74 Symtab syms;
75 Attr attr;
76 Check chk;
77 Infer infer;
78 ClassReader reader;
79 TreeInfo treeinfo;
80 Types types;
81 JCDiagnostic.Factory diags;
82 public final boolean boxingEnabled; // = source.allowBoxing();
83 public final boolean varargsEnabled; // = source.allowVarargs();
84 public final boolean allowMethodHandles;
85 private final boolean debugResolve;
86 final EnumSet<VerboseResolutionMode> verboseResolutionMode;
88 Scope polymorphicSignatureScope;
90 protected Resolve(Context context) {
91 context.put(resolveKey, this);
92 syms = Symtab.instance(context);
94 varNotFound = new
95 SymbolNotFoundError(ABSENT_VAR);
96 wrongMethod = new
97 InapplicableSymbolError();
98 wrongMethods = new
99 InapplicableSymbolsError();
100 methodNotFound = new
101 SymbolNotFoundError(ABSENT_MTH);
102 typeNotFound = new
103 SymbolNotFoundError(ABSENT_TYP);
105 names = Names.instance(context);
106 log = Log.instance(context);
107 attr = Attr.instance(context);
108 chk = Check.instance(context);
109 infer = Infer.instance(context);
110 reader = ClassReader.instance(context);
111 treeinfo = TreeInfo.instance(context);
112 types = Types.instance(context);
113 diags = JCDiagnostic.Factory.instance(context);
114 Source source = Source.instance(context);
115 boxingEnabled = source.allowBoxing();
116 varargsEnabled = source.allowVarargs();
117 Options options = Options.instance(context);
118 debugResolve = options.isSet("debugresolve");
119 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
120 Target target = Target.instance(context);
121 allowMethodHandles = target.hasMethodHandles();
122 polymorphicSignatureScope = new Scope(syms.noSymbol);
124 inapplicableMethodException = new InapplicableMethodException(diags);
125 }
127 /** error symbols, which are returned when resolution fails
128 */
129 private final SymbolNotFoundError varNotFound;
130 private final InapplicableSymbolError wrongMethod;
131 private final InapplicableSymbolsError wrongMethods;
132 private final SymbolNotFoundError methodNotFound;
133 private final SymbolNotFoundError typeNotFound;
135 public static Resolve instance(Context context) {
136 Resolve instance = context.get(resolveKey);
137 if (instance == null)
138 instance = new Resolve(context);
139 return instance;
140 }
142 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
143 enum VerboseResolutionMode {
144 SUCCESS("success"),
145 FAILURE("failure"),
146 APPLICABLE("applicable"),
147 INAPPLICABLE("inapplicable"),
148 DEFERRED_INST("deferred-inference"),
149 PREDEF("predef"),
150 OBJECT_INIT("object-init"),
151 INTERNAL("internal");
153 String opt;
155 private VerboseResolutionMode(String opt) {
156 this.opt = opt;
157 }
159 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
160 String s = opts.get("verboseResolution");
161 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
162 if (s == null) return res;
163 if (s.contains("all")) {
164 res = EnumSet.allOf(VerboseResolutionMode.class);
165 }
166 Collection<String> args = Arrays.asList(s.split(","));
167 for (VerboseResolutionMode mode : values()) {
168 if (args.contains(mode.opt)) {
169 res.add(mode);
170 } else if (args.contains("-" + mode.opt)) {
171 res.remove(mode);
172 }
173 }
174 return res;
175 }
176 }
178 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
179 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
180 boolean success = bestSoFar.kind < ERRONEOUS;
182 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
183 return;
184 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
185 return;
186 }
188 if (bestSoFar.name == names.init &&
189 bestSoFar.owner == syms.objectType.tsym &&
190 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
191 return; //skip diags for Object constructor resolution
192 } else if (site == syms.predefClass.type &&
193 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
194 return; //skip spurious diags for predef symbols (i.e. operators)
195 } else if (currentResolutionContext.internalResolution &&
196 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
197 return;
198 }
200 int pos = 0;
201 int mostSpecificPos = -1;
202 ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
203 for (Candidate c : currentResolutionContext.candidates) {
204 if (currentResolutionContext.step != c.step ||
205 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
206 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
207 continue;
208 } else {
209 subDiags.append(c.isApplicable() ?
210 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
211 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
212 if (c.sym == bestSoFar)
213 mostSpecificPos = pos;
214 pos++;
215 }
216 }
217 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
218 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
219 site.tsym, mostSpecificPos, currentResolutionContext.step,
220 methodArguments(argtypes), methodArguments(typeargtypes));
221 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
222 log.report(d);
223 }
225 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
226 JCDiagnostic subDiag = null;
227 if (inst.getReturnType().tag == FORALL) {
228 Type diagType = types.createMethodTypeWithReturn(inst.asMethodType(),
229 ((ForAll)inst.getReturnType()).qtype);
230 subDiag = diags.fragment("partial.inst.sig", diagType);
231 } else if (sym.type.tag == FORALL) {
232 subDiag = diags.fragment("full.inst.sig", inst.asMethodType());
233 }
235 String key = subDiag == null ?
236 "applicable.method.found" :
237 "applicable.method.found.1";
239 return diags.fragment(key, pos, sym, subDiag);
240 }
242 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
243 return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
244 }
245 // </editor-fold>
247 /* ************************************************************************
248 * Identifier resolution
249 *************************************************************************/
251 /** An environment is "static" if its static level is greater than
252 * the one of its outer environment
253 */
254 static boolean isStatic(Env<AttrContext> env) {
255 return env.info.staticLevel > env.outer.info.staticLevel;
256 }
258 /** An environment is an "initializer" if it is a constructor or
259 * an instance initializer.
260 */
261 static boolean isInitializer(Env<AttrContext> env) {
262 Symbol owner = env.info.scope.owner;
263 return owner.isConstructor() ||
264 owner.owner.kind == TYP &&
265 (owner.kind == VAR ||
266 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
267 (owner.flags() & STATIC) == 0;
268 }
270 /** Is class accessible in given evironment?
271 * @param env The current environment.
272 * @param c The class whose accessibility is checked.
273 */
274 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
275 return isAccessible(env, c, false);
276 }
278 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
279 boolean isAccessible = false;
280 switch ((short)(c.flags() & AccessFlags)) {
281 case PRIVATE:
282 isAccessible =
283 env.enclClass.sym.outermostClass() ==
284 c.owner.outermostClass();
285 break;
286 case 0:
287 isAccessible =
288 env.toplevel.packge == c.owner // fast special case
289 ||
290 env.toplevel.packge == c.packge()
291 ||
292 // Hack: this case is added since synthesized default constructors
293 // of anonymous classes should be allowed to access
294 // classes which would be inaccessible otherwise.
295 env.enclMethod != null &&
296 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
297 break;
298 default: // error recovery
299 case PUBLIC:
300 isAccessible = true;
301 break;
302 case PROTECTED:
303 isAccessible =
304 env.toplevel.packge == c.owner // fast special case
305 ||
306 env.toplevel.packge == c.packge()
307 ||
308 isInnerSubClass(env.enclClass.sym, c.owner);
309 break;
310 }
311 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
312 isAccessible :
313 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
314 }
315 //where
316 /** Is given class a subclass of given base class, or an inner class
317 * of a subclass?
318 * Return null if no such class exists.
319 * @param c The class which is the subclass or is contained in it.
320 * @param base The base class
321 */
322 private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
323 while (c != null && !c.isSubClass(base, types)) {
324 c = c.owner.enclClass();
325 }
326 return c != null;
327 }
329 boolean isAccessible(Env<AttrContext> env, Type t) {
330 return isAccessible(env, t, false);
331 }
333 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
334 return (t.tag == ARRAY)
335 ? isAccessible(env, types.elemtype(t))
336 : isAccessible(env, t.tsym, checkInner);
337 }
339 /** Is symbol accessible as a member of given type in given evironment?
340 * @param env The current environment.
341 * @param site The type of which the tested symbol is regarded
342 * as a member.
343 * @param sym The symbol.
344 */
345 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
346 return isAccessible(env, site, sym, false);
347 }
348 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
349 if (sym.name == names.init && sym.owner != site.tsym) return false;
350 switch ((short)(sym.flags() & AccessFlags)) {
351 case PRIVATE:
352 return
353 (env.enclClass.sym == sym.owner // fast special case
354 ||
355 env.enclClass.sym.outermostClass() ==
356 sym.owner.outermostClass())
357 &&
358 sym.isInheritedIn(site.tsym, types);
359 case 0:
360 return
361 (env.toplevel.packge == sym.owner.owner // fast special case
362 ||
363 env.toplevel.packge == sym.packge())
364 &&
365 isAccessible(env, site, checkInner)
366 &&
367 sym.isInheritedIn(site.tsym, types)
368 &&
369 notOverriddenIn(site, sym);
370 case PROTECTED:
371 return
372 (env.toplevel.packge == sym.owner.owner // fast special case
373 ||
374 env.toplevel.packge == sym.packge()
375 ||
376 isProtectedAccessible(sym, env.enclClass.sym, site)
377 ||
378 // OK to select instance method or field from 'super' or type name
379 // (but type names should be disallowed elsewhere!)
380 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
381 &&
382 isAccessible(env, site, checkInner)
383 &&
384 notOverriddenIn(site, sym);
385 default: // this case includes erroneous combinations as well
386 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
387 }
388 }
389 //where
390 /* `sym' is accessible only if not overridden by
391 * another symbol which is a member of `site'
392 * (because, if it is overridden, `sym' is not strictly
393 * speaking a member of `site'). A polymorphic signature method
394 * cannot be overridden (e.g. MH.invokeExact(Object[])).
395 */
396 private boolean notOverriddenIn(Type site, Symbol sym) {
397 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
398 return true;
399 else {
400 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
401 return (s2 == null || s2 == sym || sym.owner == s2.owner ||
402 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
403 }
404 }
405 //where
406 /** Is given protected symbol accessible if it is selected from given site
407 * and the selection takes place in given class?
408 * @param sym The symbol with protected access
409 * @param c The class where the access takes place
410 * @site The type of the qualifier
411 */
412 private
413 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
414 while (c != null &&
415 !(c.isSubClass(sym.owner, types) &&
416 (c.flags() & INTERFACE) == 0 &&
417 // In JLS 2e 6.6.2.1, the subclass restriction applies
418 // only to instance fields and methods -- types are excluded
419 // regardless of whether they are declared 'static' or not.
420 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
421 c = c.owner.enclClass();
422 return c != null;
423 }
425 /** Try to instantiate the type of a method so that it fits
426 * given type arguments and argument types. If succesful, return
427 * the method's instantiated type, else return null.
428 * The instantiation will take into account an additional leading
429 * formal parameter if the method is an instance method seen as a member
430 * of un underdetermined site In this case, we treat site as an additional
431 * parameter and the parameters of the class containing the method as
432 * additional type variables that get instantiated.
433 *
434 * @param env The current environment
435 * @param site The type of which the method is a member.
436 * @param m The method symbol.
437 * @param argtypes The invocation's given value arguments.
438 * @param typeargtypes The invocation's given type arguments.
439 * @param allowBoxing Allow boxing conversions of arguments.
440 * @param useVarargs Box trailing arguments into an array for varargs.
441 */
442 Type rawInstantiate(Env<AttrContext> env,
443 Type site,
444 Symbol m,
445 List<Type> argtypes,
446 List<Type> typeargtypes,
447 boolean allowBoxing,
448 boolean useVarargs,
449 Warner warn)
450 throws Infer.InferenceException {
451 if (useVarargs && (m.flags() & VARARGS) == 0)
452 throw inapplicableMethodException.setMessage();
453 Type mt = types.memberType(site, m);
455 // tvars is the list of formal type variables for which type arguments
456 // need to inferred.
457 List<Type> tvars = null;
458 if (env.info.tvars != null) {
459 tvars = types.newInstances(env.info.tvars);
460 mt = types.subst(mt, env.info.tvars, tvars);
461 }
462 if (typeargtypes == null) typeargtypes = List.nil();
463 if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
464 // This is not a polymorphic method, but typeargs are supplied
465 // which is fine, see JLS 15.12.2.1
466 } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
467 ForAll pmt = (ForAll) mt;
468 if (typeargtypes.length() != pmt.tvars.length())
469 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
470 // Check type arguments are within bounds
471 List<Type> formals = pmt.tvars;
472 List<Type> actuals = typeargtypes;
473 while (formals.nonEmpty() && actuals.nonEmpty()) {
474 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
475 pmt.tvars, typeargtypes);
476 for (; bounds.nonEmpty(); bounds = bounds.tail)
477 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
478 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
479 formals = formals.tail;
480 actuals = actuals.tail;
481 }
482 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
483 } else if (mt.tag == FORALL) {
484 ForAll pmt = (ForAll) mt;
485 List<Type> tvars1 = types.newInstances(pmt.tvars);
486 tvars = tvars.appendList(tvars1);
487 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
488 }
490 // find out whether we need to go the slow route via infer
491 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
492 for (List<Type> l = argtypes;
493 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
494 l = l.tail) {
495 if (l.head.tag == FORALL) instNeeded = true;
496 }
498 if (instNeeded)
499 return infer.instantiateMethod(env,
500 tvars,
501 (MethodType)mt,
502 m,
503 argtypes,
504 allowBoxing,
505 useVarargs,
506 warn);
508 checkRawArgumentsAcceptable(env, argtypes, mt.getParameterTypes(),
509 allowBoxing, useVarargs, warn);
510 return mt;
511 }
513 /** Same but returns null instead throwing a NoInstanceException
514 */
515 Type instantiate(Env<AttrContext> env,
516 Type site,
517 Symbol m,
518 List<Type> argtypes,
519 List<Type> typeargtypes,
520 boolean allowBoxing,
521 boolean useVarargs,
522 Warner warn) {
523 try {
524 return rawInstantiate(env, site, m, argtypes, typeargtypes,
525 allowBoxing, useVarargs, warn);
526 } catch (InapplicableMethodException ex) {
527 return null;
528 }
529 }
531 /** Check if a parameter list accepts a list of args.
532 */
533 boolean argumentsAcceptable(Env<AttrContext> env,
534 List<Type> argtypes,
535 List<Type> formals,
536 boolean allowBoxing,
537 boolean useVarargs,
538 Warner warn) {
539 try {
540 checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
541 return true;
542 } catch (InapplicableMethodException ex) {
543 return false;
544 }
545 }
546 /**
547 * A check handler is used by the main method applicability routine in order
548 * to handle specific method applicability failures. It is assumed that a class
549 * implementing this interface should throw exceptions that are a subtype of
550 * InapplicableMethodException (see below). Such exception will terminate the
551 * method applicability check and propagate important info outwards (for the
552 * purpose of generating better diagnostics).
553 */
554 interface MethodCheckHandler {
555 /* The number of actuals and formals differ */
556 InapplicableMethodException arityMismatch();
557 /* An actual argument type does not conform to the corresponding formal type */
558 InapplicableMethodException argumentMismatch(boolean varargs, Type found, Type expected);
559 /* The element type of a varargs is not accessible in the current context */
560 InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
561 }
563 /**
564 * Basic method check handler used within Resolve - all methods end up
565 * throwing InapplicableMethodException; a diagnostic fragment that describes
566 * the cause as to why the method is not applicable is set on the exception
567 * before it is thrown.
568 */
569 MethodCheckHandler resolveHandler = new MethodCheckHandler() {
570 public InapplicableMethodException arityMismatch() {
571 return inapplicableMethodException.setMessage("arg.length.mismatch");
572 }
573 public InapplicableMethodException argumentMismatch(boolean varargs, Type found, Type expected) {
574 String key = varargs ?
575 "varargs.argument.mismatch" :
576 "no.conforming.assignment.exists";
577 return inapplicableMethodException.setMessage(key,
578 found, expected);
579 }
580 public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
581 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
582 expected, Kinds.kindName(location), location);
583 }
584 };
586 void checkRawArgumentsAcceptable(Env<AttrContext> env,
587 List<Type> argtypes,
588 List<Type> formals,
589 boolean allowBoxing,
590 boolean useVarargs,
591 Warner warn) {
592 checkRawArgumentsAcceptable(env, List.<Type>nil(), argtypes, formals,
593 allowBoxing, useVarargs, warn, resolveHandler);
594 }
596 /**
597 * Main method applicability routine. Given a list of actual types A,
598 * a list of formal types F, determines whether the types in A are
599 * compatible (by method invocation conversion) with the types in F.
600 *
601 * Since this routine is shared between overload resolution and method
602 * type-inference, it is crucial that actual types are converted to the
603 * corresponding 'undet' form (i.e. where inference variables are replaced
604 * with undetvars) so that constraints can be propagated and collected.
605 *
606 * Moreover, if one or more types in A is a poly type, this routine calls
607 * Infer.instantiateArg in order to complete the poly type (this might involve
608 * deferred attribution).
609 *
610 * A method check handler (see above) is used in order to report errors.
611 */
612 List<Type> checkRawArgumentsAcceptable(Env<AttrContext> env,
613 List<Type> undetvars,
614 List<Type> argtypes,
615 List<Type> formals,
616 boolean allowBoxing,
617 boolean useVarargs,
618 Warner warn,
619 MethodCheckHandler handler) {
620 Type varargsFormal = useVarargs ? formals.last() : null;
621 ListBuffer<Type> checkedArgs = ListBuffer.lb();
623 if (varargsFormal == null &&
624 argtypes.size() != formals.size()) {
625 throw handler.arityMismatch(); // not enough args
626 }
628 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
629 ResultInfo resultInfo = methodCheckResult(formals.head, allowBoxing, false, undetvars, handler, warn);
630 checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
631 argtypes = argtypes.tail;
632 formals = formals.tail;
633 }
635 if (formals.head != varargsFormal) {
636 throw handler.arityMismatch(); // not enough args
637 }
639 if (useVarargs) {
640 //note: if applicability check is triggered by most specific test,
641 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
642 Type elt = types.elemtype(varargsFormal);
643 while (argtypes.nonEmpty()) {
644 ResultInfo resultInfo = methodCheckResult(elt, allowBoxing, true, undetvars, handler, warn);
645 checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
646 argtypes = argtypes.tail;
647 }
648 //check varargs element type accessibility
649 if (undetvars.isEmpty() && !isAccessible(env, elt)) {
650 Symbol location = env.enclClass.sym;
651 throw handler.inaccessibleVarargs(location, elt);
652 }
653 }
654 return checkedArgs.toList();
655 }
657 /**
658 * Check context to be used during method applicability checks. A method check
659 * context might contain inference variables.
660 */
661 abstract class MethodCheckContext implements CheckContext {
663 MethodCheckHandler handler;
664 boolean useVarargs;
665 List<Type> undetvars;
666 Warner rsWarner;
668 public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs, List<Type> undetvars, Warner rsWarner) {
669 this.handler = handler;
670 this.useVarargs = useVarargs;
671 this.undetvars = undetvars;
672 this.rsWarner = rsWarner;
673 }
675 public void report(DiagnosticPosition pos, Type found, Type req, JCDiagnostic details) {
676 throw handler.argumentMismatch(useVarargs, found, req);
677 }
679 public Type rawInstantiatePoly(ForAll found, Type req, Warner warn) {
680 throw new AssertionError("ForAll in argument position");
681 }
683 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
684 return rsWarner;
685 }
686 }
688 /**
689 * Subclass of method check context class that implements strict method conversion.
690 * Strict method conversion checks compatibility between types using subtyping tests.
691 */
692 class StrictMethodContext extends MethodCheckContext {
694 public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs, List<Type> undetvars, Warner rsWarner) {
695 super(handler, useVarargs, undetvars, rsWarner);
696 }
698 public boolean compatible(Type found, Type req, Warner warn) {
699 return types.isSubtypeUnchecked(found, infer.asUndetType(req, undetvars), warn);
700 }
701 }
703 /**
704 * Subclass of method check context class that implements loose method conversion.
705 * Loose method conversion checks compatibility between types using method conversion tests.
706 */
707 class LooseMethodContext extends MethodCheckContext {
709 public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs, List<Type> undetvars, Warner rsWarner) {
710 super(handler, useVarargs, undetvars, rsWarner);
711 }
713 public boolean compatible(Type found, Type req, Warner warn) {
714 return types.isConvertible(found, infer.asUndetType(req, undetvars), warn);
715 }
716 }
718 /**
719 * Create a method check context to be used during method applicability check
720 */
721 ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
722 List<Type> undetvars, MethodCheckHandler methodHandler, Warner rsWarner) {
723 MethodCheckContext checkContext = allowBoxing ?
724 new LooseMethodContext(methodHandler, useVarargs, undetvars, rsWarner) :
725 new StrictMethodContext(methodHandler, useVarargs, undetvars, rsWarner);
726 return attr.new ResultInfo(VAL, to, checkContext) {
727 @Override
728 protected Type check(DiagnosticPosition pos, Type found) {
729 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found))));
730 }
731 };
732 }
734 public static class InapplicableMethodException extends RuntimeException {
735 private static final long serialVersionUID = 0;
737 JCDiagnostic diagnostic;
738 JCDiagnostic.Factory diags;
740 InapplicableMethodException(JCDiagnostic.Factory diags) {
741 this.diagnostic = null;
742 this.diags = diags;
743 }
744 InapplicableMethodException setMessage() {
745 this.diagnostic = null;
746 return this;
747 }
748 InapplicableMethodException setMessage(String key) {
749 this.diagnostic = key != null ? diags.fragment(key) : null;
750 return this;
751 }
752 InapplicableMethodException setMessage(String key, Object... args) {
753 this.diagnostic = key != null ? diags.fragment(key, args) : null;
754 return this;
755 }
756 InapplicableMethodException setMessage(JCDiagnostic diag) {
757 this.diagnostic = diag;
758 return this;
759 }
761 public JCDiagnostic getDiagnostic() {
762 return diagnostic;
763 }
764 }
765 private final InapplicableMethodException inapplicableMethodException;
767 /* ***************************************************************************
768 * Symbol lookup
769 * the following naming conventions for arguments are used
770 *
771 * env is the environment where the symbol was mentioned
772 * site is the type of which the symbol is a member
773 * name is the symbol's name
774 * if no arguments are given
775 * argtypes are the value arguments, if we search for a method
776 *
777 * If no symbol was found, a ResolveError detailing the problem is returned.
778 ****************************************************************************/
780 /** Find field. Synthetic fields are always skipped.
781 * @param env The current environment.
782 * @param site The original type from where the selection takes place.
783 * @param name The name of the field.
784 * @param c The class to search for the field. This is always
785 * a superclass or implemented interface of site's class.
786 */
787 Symbol findField(Env<AttrContext> env,
788 Type site,
789 Name name,
790 TypeSymbol c) {
791 while (c.type.tag == TYPEVAR)
792 c = c.type.getUpperBound().tsym;
793 Symbol bestSoFar = varNotFound;
794 Symbol sym;
795 Scope.Entry e = c.members().lookup(name);
796 while (e.scope != null) {
797 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
798 return isAccessible(env, site, e.sym)
799 ? e.sym : new AccessError(env, site, e.sym);
800 }
801 e = e.next();
802 }
803 Type st = types.supertype(c.type);
804 if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
805 sym = findField(env, site, name, st.tsym);
806 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
807 }
808 for (List<Type> l = types.interfaces(c.type);
809 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
810 l = l.tail) {
811 sym = findField(env, site, name, l.head.tsym);
812 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
813 sym.owner != bestSoFar.owner)
814 bestSoFar = new AmbiguityError(bestSoFar, sym);
815 else if (sym.kind < bestSoFar.kind)
816 bestSoFar = sym;
817 }
818 return bestSoFar;
819 }
821 /** Resolve a field identifier, throw a fatal error if not found.
822 * @param pos The position to use for error reporting.
823 * @param env The environment current at the method invocation.
824 * @param site The type of the qualifying expression, in which
825 * identifier is searched.
826 * @param name The identifier's name.
827 */
828 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
829 Type site, Name name) {
830 Symbol sym = findField(env, site, name, site.tsym);
831 if (sym.kind == VAR) return (VarSymbol)sym;
832 else throw new FatalError(
833 diags.fragment("fatal.err.cant.locate.field",
834 name));
835 }
837 /** Find unqualified variable or field with given name.
838 * Synthetic fields always skipped.
839 * @param env The current environment.
840 * @param name The name of the variable or field.
841 */
842 Symbol findVar(Env<AttrContext> env, Name name) {
843 Symbol bestSoFar = varNotFound;
844 Symbol sym;
845 Env<AttrContext> env1 = env;
846 boolean staticOnly = false;
847 while (env1.outer != null) {
848 if (isStatic(env1)) staticOnly = true;
849 Scope.Entry e = env1.info.scope.lookup(name);
850 while (e.scope != null &&
851 (e.sym.kind != VAR ||
852 (e.sym.flags_field & SYNTHETIC) != 0))
853 e = e.next();
854 sym = (e.scope != null)
855 ? e.sym
856 : findField(
857 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
858 if (sym.exists()) {
859 if (staticOnly &&
860 sym.kind == VAR &&
861 sym.owner.kind == TYP &&
862 (sym.flags() & STATIC) == 0)
863 return new StaticError(sym);
864 else
865 return sym;
866 } else if (sym.kind < bestSoFar.kind) {
867 bestSoFar = sym;
868 }
870 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
871 env1 = env1.outer;
872 }
874 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
875 if (sym.exists())
876 return sym;
877 if (bestSoFar.exists())
878 return bestSoFar;
880 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
881 for (; e.scope != null; e = e.next()) {
882 sym = e.sym;
883 Type origin = e.getOrigin().owner.type;
884 if (sym.kind == VAR) {
885 if (e.sym.owner.type != origin)
886 sym = sym.clone(e.getOrigin().owner);
887 return isAccessible(env, origin, sym)
888 ? sym : new AccessError(env, origin, sym);
889 }
890 }
892 Symbol origin = null;
893 e = env.toplevel.starImportScope.lookup(name);
894 for (; e.scope != null; e = e.next()) {
895 sym = e.sym;
896 if (sym.kind != VAR)
897 continue;
898 // invariant: sym.kind == VAR
899 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
900 return new AmbiguityError(bestSoFar, sym);
901 else if (bestSoFar.kind >= VAR) {
902 origin = e.getOrigin().owner;
903 bestSoFar = isAccessible(env, origin.type, sym)
904 ? sym : new AccessError(env, origin.type, sym);
905 }
906 }
907 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
908 return bestSoFar.clone(origin);
909 else
910 return bestSoFar;
911 }
913 Warner noteWarner = new Warner();
915 /** Select the best method for a call site among two choices.
916 * @param env The current environment.
917 * @param site The original type from where the
918 * selection takes place.
919 * @param argtypes The invocation's value arguments,
920 * @param typeargtypes The invocation's type arguments,
921 * @param sym Proposed new best match.
922 * @param bestSoFar Previously found best match.
923 * @param allowBoxing Allow boxing conversions of arguments.
924 * @param useVarargs Box trailing arguments into an array for varargs.
925 */
926 @SuppressWarnings("fallthrough")
927 Symbol selectBest(Env<AttrContext> env,
928 Type site,
929 List<Type> argtypes,
930 List<Type> typeargtypes,
931 Symbol sym,
932 Symbol bestSoFar,
933 boolean allowBoxing,
934 boolean useVarargs,
935 boolean operator) {
936 if (sym.kind == ERR) return bestSoFar;
937 if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
938 Assert.check(sym.kind < AMBIGUOUS);
939 try {
940 Type mt = rawInstantiate(env, site, sym, argtypes, typeargtypes,
941 allowBoxing, useVarargs, Warner.noWarnings);
942 if (!operator)
943 currentResolutionContext.addApplicableCandidate(sym, mt);
944 } catch (InapplicableMethodException ex) {
945 if (!operator)
946 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
947 switch (bestSoFar.kind) {
948 case ABSENT_MTH:
949 return wrongMethod;
950 case WRONG_MTH:
951 if (operator) return bestSoFar;
952 case WRONG_MTHS:
953 return wrongMethods;
954 default:
955 return bestSoFar;
956 }
957 }
958 if (!isAccessible(env, site, sym)) {
959 return (bestSoFar.kind == ABSENT_MTH)
960 ? new AccessError(env, site, sym)
961 : bestSoFar;
962 }
963 return (bestSoFar.kind > AMBIGUOUS)
964 ? sym
965 : mostSpecific(sym, bestSoFar, env, site,
966 allowBoxing && operator, useVarargs);
967 }
969 /* Return the most specific of the two methods for a call,
970 * given that both are accessible and applicable.
971 * @param m1 A new candidate for most specific.
972 * @param m2 The previous most specific candidate.
973 * @param env The current environment.
974 * @param site The original type from where the selection
975 * takes place.
976 * @param allowBoxing Allow boxing conversions of arguments.
977 * @param useVarargs Box trailing arguments into an array for varargs.
978 */
979 Symbol mostSpecific(Symbol m1,
980 Symbol m2,
981 Env<AttrContext> env,
982 final Type site,
983 boolean allowBoxing,
984 boolean useVarargs) {
985 switch (m2.kind) {
986 case MTH:
987 if (m1 == m2) return m1;
988 boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
989 boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
990 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
991 Type mt1 = types.memberType(site, m1);
992 Type mt2 = types.memberType(site, m2);
993 if (!types.overrideEquivalent(mt1, mt2))
994 return ambiguityError(m1, m2);
996 // same signature; select (a) the non-bridge method, or
997 // (b) the one that overrides the other, or (c) the concrete
998 // one, or (d) merge both abstract signatures
999 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1000 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1002 // if one overrides or hides the other, use it
1003 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1004 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1005 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1006 ((m1.owner.flags_field & INTERFACE) == 0 ||
1007 (m2.owner.flags_field & INTERFACE) != 0) &&
1008 m1.overrides(m2, m1Owner, types, false))
1009 return m1;
1010 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1011 ((m2.owner.flags_field & INTERFACE) == 0 ||
1012 (m1.owner.flags_field & INTERFACE) != 0) &&
1013 m2.overrides(m1, m2Owner, types, false))
1014 return m2;
1015 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1016 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1017 if (m1Abstract && !m2Abstract) return m2;
1018 if (m2Abstract && !m1Abstract) return m1;
1019 // both abstract or both concrete
1020 if (!m1Abstract && !m2Abstract)
1021 return ambiguityError(m1, m2);
1022 // check that both signatures have the same erasure
1023 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
1024 m2.erasure(types).getParameterTypes()))
1025 return ambiguityError(m1, m2);
1026 // both abstract, neither overridden; merge throws clause and result type
1027 Type mst = mostSpecificReturnType(mt1, mt2);
1028 if (mst == null) {
1029 // Theoretically, this can't happen, but it is possible
1030 // due to error recovery or mixing incompatible class files
1031 return ambiguityError(m1, m2);
1032 }
1033 Symbol mostSpecific = mst == mt1 ? m1 : m2;
1034 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
1035 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
1036 MethodSymbol result = new MethodSymbol(
1037 mostSpecific.flags(),
1038 mostSpecific.name,
1039 newSig,
1040 mostSpecific.owner) {
1041 @Override
1042 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1043 if (origin == site.tsym)
1044 return this;
1045 else
1046 return super.implementation(origin, types, checkResult);
1047 }
1048 };
1049 return result;
1050 }
1051 if (m1SignatureMoreSpecific) return m1;
1052 if (m2SignatureMoreSpecific) return m2;
1053 return ambiguityError(m1, m2);
1054 case AMBIGUOUS:
1055 AmbiguityError e = (AmbiguityError)m2;
1056 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
1057 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
1058 if (err1 == err2) return err1;
1059 if (err1 == e.sym && err2 == e.sym2) return m2;
1060 if (err1 instanceof AmbiguityError &&
1061 err2 instanceof AmbiguityError &&
1062 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
1063 return ambiguityError(m1, m2);
1064 else
1065 return ambiguityError(err1, err2);
1066 default:
1067 throw new AssertionError();
1068 }
1069 }
1070 //where
1071 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1072 noteWarner.clear();
1073 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
1074 Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs),
1075 types.lowerBoundArgtypes(mtype1), null,
1076 allowBoxing, false, noteWarner);
1077 return mtype2 != null &&
1078 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1079 }
1080 //where
1081 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
1082 List<Type> fromArgs = from.type.getParameterTypes();
1083 List<Type> toArgs = to.type.getParameterTypes();
1084 if (useVarargs &&
1085 (from.flags() & VARARGS) != 0 &&
1086 (to.flags() & VARARGS) != 0) {
1087 Type varargsTypeFrom = fromArgs.last();
1088 Type varargsTypeTo = toArgs.last();
1089 ListBuffer<Type> args = ListBuffer.lb();
1090 if (toArgs.length() < fromArgs.length()) {
1091 //if we are checking a varargs method 'from' against another varargs
1092 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
1093 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
1094 //until 'to' signature has the same arity as 'from')
1095 while (fromArgs.head != varargsTypeFrom) {
1096 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
1097 fromArgs = fromArgs.tail;
1098 toArgs = toArgs.head == varargsTypeTo ?
1099 toArgs :
1100 toArgs.tail;
1101 }
1102 } else {
1103 //formal argument list is same as original list where last
1104 //argument (array type) is removed
1105 args.appendList(toArgs.reverse().tail.reverse());
1106 }
1107 //append varargs element type as last synthetic formal
1108 args.append(types.elemtype(varargsTypeTo));
1109 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
1110 return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
1111 } else {
1112 return to;
1113 }
1114 }
1115 //where
1116 Type mostSpecificReturnType(Type mt1, Type mt2) {
1117 Type rt1 = mt1.getReturnType();
1118 Type rt2 = mt2.getReturnType();
1120 if (mt1.tag == FORALL && mt2.tag == FORALL) {
1121 //if both are generic methods, adjust return type ahead of subtyping check
1122 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1123 }
1124 //first use subtyping, then return type substitutability
1125 if (types.isSubtype(rt1, rt2)) {
1126 return mt1;
1127 } else if (types.isSubtype(rt2, rt1)) {
1128 return mt2;
1129 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1130 return mt1;
1131 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1132 return mt2;
1133 } else {
1134 return null;
1135 }
1136 }
1137 //where
1138 Symbol ambiguityError(Symbol m1, Symbol m2) {
1139 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1140 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1141 } else {
1142 return new AmbiguityError(m1, m2);
1143 }
1144 }
1146 /** Find best qualified method matching given name, type and value
1147 * arguments.
1148 * @param env The current environment.
1149 * @param site The original type from where the selection
1150 * takes place.
1151 * @param name The method's name.
1152 * @param argtypes The method's value arguments.
1153 * @param typeargtypes The method's type arguments
1154 * @param allowBoxing Allow boxing conversions of arguments.
1155 * @param useVarargs Box trailing arguments into an array for varargs.
1156 */
1157 Symbol findMethod(Env<AttrContext> env,
1158 Type site,
1159 Name name,
1160 List<Type> argtypes,
1161 List<Type> typeargtypes,
1162 boolean allowBoxing,
1163 boolean useVarargs,
1164 boolean operator) {
1165 Symbol bestSoFar = methodNotFound;
1166 bestSoFar = findMethod(env,
1167 site,
1168 name,
1169 argtypes,
1170 typeargtypes,
1171 site.tsym.type,
1172 true,
1173 bestSoFar,
1174 allowBoxing,
1175 useVarargs,
1176 operator,
1177 new HashSet<TypeSymbol>());
1178 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1179 return bestSoFar;
1180 }
1181 // where
1182 private Symbol findMethod(Env<AttrContext> env,
1183 Type site,
1184 Name name,
1185 List<Type> argtypes,
1186 List<Type> typeargtypes,
1187 Type intype,
1188 boolean abstractok,
1189 Symbol bestSoFar,
1190 boolean allowBoxing,
1191 boolean useVarargs,
1192 boolean operator,
1193 Set<TypeSymbol> seen) {
1194 for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
1195 while (ct.tag == TYPEVAR)
1196 ct = ct.getUpperBound();
1197 ClassSymbol c = (ClassSymbol)ct.tsym;
1198 if (!seen.add(c)) return bestSoFar;
1199 if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
1200 abstractok = false;
1201 for (Scope.Entry e = c.members().lookup(name);
1202 e.scope != null;
1203 e = e.next()) {
1204 //- System.out.println(" e " + e.sym);
1205 if (e.sym.kind == MTH &&
1206 (e.sym.flags_field & SYNTHETIC) == 0) {
1207 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
1208 e.sym, bestSoFar,
1209 allowBoxing,
1210 useVarargs,
1211 operator);
1212 }
1213 }
1214 if (name == names.init)
1215 break;
1216 //- System.out.println(" - " + bestSoFar);
1217 if (abstractok) {
1218 Symbol concrete = methodNotFound;
1219 if ((bestSoFar.flags() & ABSTRACT) == 0)
1220 concrete = bestSoFar;
1221 for (List<Type> l = types.interfaces(c.type);
1222 l.nonEmpty();
1223 l = l.tail) {
1224 bestSoFar = findMethod(env, site, name, argtypes,
1225 typeargtypes,
1226 l.head, abstractok, bestSoFar,
1227 allowBoxing, useVarargs, operator, seen);
1228 }
1229 if (concrete != bestSoFar &&
1230 concrete.kind < ERR && bestSoFar.kind < ERR &&
1231 types.isSubSignature(concrete.type, bestSoFar.type))
1232 bestSoFar = concrete;
1233 }
1234 }
1235 return bestSoFar;
1236 }
1238 /** Find unqualified method matching given name, type and value arguments.
1239 * @param env The current environment.
1240 * @param name The method's name.
1241 * @param argtypes The method's value arguments.
1242 * @param typeargtypes The method's type arguments.
1243 * @param allowBoxing Allow boxing conversions of arguments.
1244 * @param useVarargs Box trailing arguments into an array for varargs.
1245 */
1246 Symbol findFun(Env<AttrContext> env, Name name,
1247 List<Type> argtypes, List<Type> typeargtypes,
1248 boolean allowBoxing, boolean useVarargs) {
1249 Symbol bestSoFar = methodNotFound;
1250 Symbol sym;
1251 Env<AttrContext> env1 = env;
1252 boolean staticOnly = false;
1253 while (env1.outer != null) {
1254 if (isStatic(env1)) staticOnly = true;
1255 sym = findMethod(
1256 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1257 allowBoxing, useVarargs, false);
1258 if (sym.exists()) {
1259 if (staticOnly &&
1260 sym.kind == MTH &&
1261 sym.owner.kind == TYP &&
1262 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1263 else return sym;
1264 } else if (sym.kind < bestSoFar.kind) {
1265 bestSoFar = sym;
1266 }
1267 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1268 env1 = env1.outer;
1269 }
1271 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1272 typeargtypes, allowBoxing, useVarargs, false);
1273 if (sym.exists())
1274 return sym;
1276 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1277 for (; e.scope != null; e = e.next()) {
1278 sym = e.sym;
1279 Type origin = e.getOrigin().owner.type;
1280 if (sym.kind == MTH) {
1281 if (e.sym.owner.type != origin)
1282 sym = sym.clone(e.getOrigin().owner);
1283 if (!isAccessible(env, origin, sym))
1284 sym = new AccessError(env, origin, sym);
1285 bestSoFar = selectBest(env, origin,
1286 argtypes, typeargtypes,
1287 sym, bestSoFar,
1288 allowBoxing, useVarargs, false);
1289 }
1290 }
1291 if (bestSoFar.exists())
1292 return bestSoFar;
1294 e = env.toplevel.starImportScope.lookup(name);
1295 for (; e.scope != null; e = e.next()) {
1296 sym = e.sym;
1297 Type origin = e.getOrigin().owner.type;
1298 if (sym.kind == MTH) {
1299 if (e.sym.owner.type != origin)
1300 sym = sym.clone(e.getOrigin().owner);
1301 if (!isAccessible(env, origin, sym))
1302 sym = new AccessError(env, origin, sym);
1303 bestSoFar = selectBest(env, origin,
1304 argtypes, typeargtypes,
1305 sym, bestSoFar,
1306 allowBoxing, useVarargs, false);
1307 }
1308 }
1309 return bestSoFar;
1310 }
1312 /** Load toplevel or member class with given fully qualified name and
1313 * verify that it is accessible.
1314 * @param env The current environment.
1315 * @param name The fully qualified name of the class to be loaded.
1316 */
1317 Symbol loadClass(Env<AttrContext> env, Name name) {
1318 try {
1319 ClassSymbol c = reader.loadClass(name);
1320 return isAccessible(env, c) ? c : new AccessError(c);
1321 } catch (ClassReader.BadClassFile err) {
1322 throw err;
1323 } catch (CompletionFailure ex) {
1324 return typeNotFound;
1325 }
1326 }
1328 /** Find qualified member type.
1329 * @param env The current environment.
1330 * @param site The original type from where the selection takes
1331 * place.
1332 * @param name The type's name.
1333 * @param c The class to search for the member type. This is
1334 * always a superclass or implemented interface of
1335 * site's class.
1336 */
1337 Symbol findMemberType(Env<AttrContext> env,
1338 Type site,
1339 Name name,
1340 TypeSymbol c) {
1341 Symbol bestSoFar = typeNotFound;
1342 Symbol sym;
1343 Scope.Entry e = c.members().lookup(name);
1344 while (e.scope != null) {
1345 if (e.sym.kind == TYP) {
1346 return isAccessible(env, site, e.sym)
1347 ? e.sym
1348 : new AccessError(env, site, e.sym);
1349 }
1350 e = e.next();
1351 }
1352 Type st = types.supertype(c.type);
1353 if (st != null && st.tag == CLASS) {
1354 sym = findMemberType(env, site, name, st.tsym);
1355 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1356 }
1357 for (List<Type> l = types.interfaces(c.type);
1358 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1359 l = l.tail) {
1360 sym = findMemberType(env, site, name, l.head.tsym);
1361 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1362 sym.owner != bestSoFar.owner)
1363 bestSoFar = new AmbiguityError(bestSoFar, sym);
1364 else if (sym.kind < bestSoFar.kind)
1365 bestSoFar = sym;
1366 }
1367 return bestSoFar;
1368 }
1370 /** Find a global type in given scope and load corresponding class.
1371 * @param env The current environment.
1372 * @param scope The scope in which to look for the type.
1373 * @param name The type's name.
1374 */
1375 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1376 Symbol bestSoFar = typeNotFound;
1377 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1378 Symbol sym = loadClass(env, e.sym.flatName());
1379 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1380 bestSoFar != sym)
1381 return new AmbiguityError(bestSoFar, sym);
1382 else if (sym.kind < bestSoFar.kind)
1383 bestSoFar = sym;
1384 }
1385 return bestSoFar;
1386 }
1388 /** Find an unqualified type symbol.
1389 * @param env The current environment.
1390 * @param name The type's name.
1391 */
1392 Symbol findType(Env<AttrContext> env, Name name) {
1393 Symbol bestSoFar = typeNotFound;
1394 Symbol sym;
1395 boolean staticOnly = false;
1396 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1397 if (isStatic(env1)) staticOnly = true;
1398 for (Scope.Entry e = env1.info.scope.lookup(name);
1399 e.scope != null;
1400 e = e.next()) {
1401 if (e.sym.kind == TYP) {
1402 if (staticOnly &&
1403 e.sym.type.tag == TYPEVAR &&
1404 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1405 return e.sym;
1406 }
1407 }
1409 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1410 env1.enclClass.sym);
1411 if (staticOnly && sym.kind == TYP &&
1412 sym.type.tag == CLASS &&
1413 sym.type.getEnclosingType().tag == CLASS &&
1414 env1.enclClass.sym.type.isParameterized() &&
1415 sym.type.getEnclosingType().isParameterized())
1416 return new StaticError(sym);
1417 else if (sym.exists()) return sym;
1418 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1420 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1421 if ((encl.sym.flags() & STATIC) != 0)
1422 staticOnly = true;
1423 }
1425 if (!env.tree.hasTag(IMPORT)) {
1426 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1427 if (sym.exists()) return sym;
1428 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1430 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1431 if (sym.exists()) return sym;
1432 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1434 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1435 if (sym.exists()) return sym;
1436 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1437 }
1439 return bestSoFar;
1440 }
1442 /** Find an unqualified identifier which matches a specified kind set.
1443 * @param env The current environment.
1444 * @param name The indentifier's name.
1445 * @param kind Indicates the possible symbol kinds
1446 * (a subset of VAL, TYP, PCK).
1447 */
1448 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1449 Symbol bestSoFar = typeNotFound;
1450 Symbol sym;
1452 if ((kind & VAR) != 0) {
1453 sym = findVar(env, name);
1454 if (sym.exists()) return sym;
1455 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1456 }
1458 if ((kind & TYP) != 0) {
1459 sym = findType(env, name);
1460 if (sym.exists()) return sym;
1461 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1462 }
1464 if ((kind & PCK) != 0) return reader.enterPackage(name);
1465 else return bestSoFar;
1466 }
1468 /** Find an identifier in a package which matches a specified kind set.
1469 * @param env The current environment.
1470 * @param name The identifier's name.
1471 * @param kind Indicates the possible symbol kinds
1472 * (a nonempty subset of TYP, PCK).
1473 */
1474 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1475 Name name, int kind) {
1476 Name fullname = TypeSymbol.formFullName(name, pck);
1477 Symbol bestSoFar = typeNotFound;
1478 PackageSymbol pack = null;
1479 if ((kind & PCK) != 0) {
1480 pack = reader.enterPackage(fullname);
1481 if (pack.exists()) return pack;
1482 }
1483 if ((kind & TYP) != 0) {
1484 Symbol sym = loadClass(env, fullname);
1485 if (sym.exists()) {
1486 // don't allow programs to use flatnames
1487 if (name == sym.name) return sym;
1488 }
1489 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1490 }
1491 return (pack != null) ? pack : bestSoFar;
1492 }
1494 /** Find an identifier among the members of a given type `site'.
1495 * @param env The current environment.
1496 * @param site The type containing the symbol to be found.
1497 * @param name The identifier's name.
1498 * @param kind Indicates the possible symbol kinds
1499 * (a subset of VAL, TYP).
1500 */
1501 Symbol findIdentInType(Env<AttrContext> env, Type site,
1502 Name name, int kind) {
1503 Symbol bestSoFar = typeNotFound;
1504 Symbol sym;
1505 if ((kind & VAR) != 0) {
1506 sym = findField(env, site, name, site.tsym);
1507 if (sym.exists()) return sym;
1508 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1509 }
1511 if ((kind & TYP) != 0) {
1512 sym = findMemberType(env, site, name, site.tsym);
1513 if (sym.exists()) return sym;
1514 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1515 }
1516 return bestSoFar;
1517 }
1519 /* ***************************************************************************
1520 * Access checking
1521 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1522 * an error message in the process
1523 ****************************************************************************/
1525 /** If `sym' is a bad symbol: report error and return errSymbol
1526 * else pass through unchanged,
1527 * additional arguments duplicate what has been used in trying to find the
1528 * symbol (--> flyweight pattern). This improves performance since we
1529 * expect misses to happen frequently.
1530 *
1531 * @param sym The symbol that was found, or a ResolveError.
1532 * @param pos The position to use for error reporting.
1533 * @param site The original type from where the selection took place.
1534 * @param name The symbol's name.
1535 * @param argtypes The invocation's value arguments,
1536 * if we looked for a method.
1537 * @param typeargtypes The invocation's type arguments,
1538 * if we looked for a method.
1539 */
1540 Symbol access(Symbol sym,
1541 DiagnosticPosition pos,
1542 Symbol location,
1543 Type site,
1544 Name name,
1545 boolean qualified,
1546 List<Type> argtypes,
1547 List<Type> typeargtypes) {
1548 if (sym.kind >= AMBIGUOUS) {
1549 ResolveError errSym = (ResolveError)sym;
1550 if (!site.isErroneous() &&
1551 !Type.isErroneous(argtypes) &&
1552 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
1553 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1554 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1555 }
1556 return sym;
1557 }
1559 /** Same as original access(), but without location.
1560 */
1561 Symbol access(Symbol sym,
1562 DiagnosticPosition pos,
1563 Type site,
1564 Name name,
1565 boolean qualified,
1566 List<Type> argtypes,
1567 List<Type> typeargtypes) {
1568 return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1569 }
1571 /** Same as original access(), but without type arguments and arguments.
1572 */
1573 Symbol access(Symbol sym,
1574 DiagnosticPosition pos,
1575 Symbol location,
1576 Type site,
1577 Name name,
1578 boolean qualified) {
1579 if (sym.kind >= AMBIGUOUS)
1580 return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
1581 else
1582 return sym;
1583 }
1585 /** Same as original access(), but without location, type arguments and arguments.
1586 */
1587 Symbol access(Symbol sym,
1588 DiagnosticPosition pos,
1589 Type site,
1590 Name name,
1591 boolean qualified) {
1592 return access(sym, pos, site.tsym, site, name, qualified);
1593 }
1595 /** Check that sym is not an abstract method.
1596 */
1597 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1598 if ((sym.flags() & ABSTRACT) != 0)
1599 log.error(pos, "abstract.cant.be.accessed.directly",
1600 kindName(sym), sym, sym.location());
1601 }
1603 /* ***************************************************************************
1604 * Debugging
1605 ****************************************************************************/
1607 /** print all scopes starting with scope s and proceeding outwards.
1608 * used for debugging.
1609 */
1610 public void printscopes(Scope s) {
1611 while (s != null) {
1612 if (s.owner != null)
1613 System.err.print(s.owner + ": ");
1614 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1615 if ((e.sym.flags() & ABSTRACT) != 0)
1616 System.err.print("abstract ");
1617 System.err.print(e.sym + " ");
1618 }
1619 System.err.println();
1620 s = s.next;
1621 }
1622 }
1624 void printscopes(Env<AttrContext> env) {
1625 while (env.outer != null) {
1626 System.err.println("------------------------------");
1627 printscopes(env.info.scope);
1628 env = env.outer;
1629 }
1630 }
1632 public void printscopes(Type t) {
1633 while (t.tag == CLASS) {
1634 printscopes(t.tsym.members());
1635 t = types.supertype(t);
1636 }
1637 }
1639 /* ***************************************************************************
1640 * Name resolution
1641 * Naming conventions are as for symbol lookup
1642 * Unlike the find... methods these methods will report access errors
1643 ****************************************************************************/
1645 /** Resolve an unqualified (non-method) identifier.
1646 * @param pos The position to use for error reporting.
1647 * @param env The environment current at the identifier use.
1648 * @param name The identifier's name.
1649 * @param kind The set of admissible symbol kinds for the identifier.
1650 */
1651 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1652 Name name, int kind) {
1653 return access(
1654 findIdent(env, name, kind),
1655 pos, env.enclClass.sym.type, name, false);
1656 }
1658 /** Resolve an unqualified method identifier.
1659 * @param pos The position to use for error reporting.
1660 * @param env The environment current at the method invocation.
1661 * @param name The identifier's name.
1662 * @param argtypes The types of the invocation's value arguments.
1663 * @param typeargtypes The types of the invocation's type arguments.
1664 */
1665 Symbol resolveMethod(DiagnosticPosition pos,
1666 Env<AttrContext> env,
1667 Name name,
1668 List<Type> argtypes,
1669 List<Type> typeargtypes) {
1670 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1671 try {
1672 currentResolutionContext = new MethodResolutionContext();
1673 Symbol sym = methodNotFound;
1674 List<MethodResolutionPhase> steps = methodResolutionSteps;
1675 while (steps.nonEmpty() &&
1676 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1677 sym.kind >= ERRONEOUS) {
1678 currentResolutionContext.step = steps.head;
1679 sym = findFun(env, name, argtypes, typeargtypes,
1680 steps.head.isBoxingRequired,
1681 env.info.varArgs = steps.head.isVarargsRequired);
1682 currentResolutionContext.resolutionCache.put(steps.head, sym);
1683 steps = steps.tail;
1684 }
1685 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1686 MethodResolutionPhase errPhase =
1687 currentResolutionContext.firstErroneousResolutionPhase();
1688 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1689 pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1690 env.info.varArgs = errPhase.isVarargsRequired;
1691 }
1692 return sym;
1693 }
1694 finally {
1695 currentResolutionContext = prevResolutionContext;
1696 }
1697 }
1699 /** Resolve a qualified method identifier
1700 * @param pos The position to use for error reporting.
1701 * @param env The environment current at the method invocation.
1702 * @param site The type of the qualifying expression, in which
1703 * identifier is searched.
1704 * @param name The identifier's name.
1705 * @param argtypes The types of the invocation's value arguments.
1706 * @param typeargtypes The types of the invocation's type arguments.
1707 */
1708 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1709 Type site, Name name, List<Type> argtypes,
1710 List<Type> typeargtypes) {
1711 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
1712 }
1713 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1714 Symbol location, Type site, Name name, List<Type> argtypes,
1715 List<Type> typeargtypes) {
1716 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
1717 }
1718 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
1719 DiagnosticPosition pos, Env<AttrContext> env,
1720 Symbol location, Type site, Name name, List<Type> argtypes,
1721 List<Type> typeargtypes) {
1722 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1723 try {
1724 currentResolutionContext = resolveContext;
1725 Symbol sym = methodNotFound;
1726 List<MethodResolutionPhase> steps = methodResolutionSteps;
1727 while (steps.nonEmpty() &&
1728 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1729 sym.kind >= ERRONEOUS) {
1730 currentResolutionContext.step = steps.head;
1731 sym = findMethod(env, site, name, argtypes, typeargtypes,
1732 steps.head.isBoxingRequired(),
1733 env.info.varArgs = steps.head.isVarargsRequired(), false);
1734 currentResolutionContext.resolutionCache.put(steps.head, sym);
1735 steps = steps.tail;
1736 }
1737 if (sym.kind >= AMBIGUOUS) {
1738 //if nothing is found return the 'first' error
1739 MethodResolutionPhase errPhase =
1740 currentResolutionContext.firstErroneousResolutionPhase();
1741 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1742 pos, location, site, name, true, argtypes, typeargtypes);
1743 env.info.varArgs = errPhase.isVarargsRequired;
1744 } else if (allowMethodHandles) {
1745 MethodSymbol msym = (MethodSymbol)sym;
1746 if (msym.isSignaturePolymorphic(types)) {
1747 env.info.varArgs = false;
1748 return findPolymorphicSignatureInstance(env, sym, argtypes);
1749 }
1750 }
1751 return sym;
1752 }
1753 finally {
1754 currentResolutionContext = prevResolutionContext;
1755 }
1756 }
1758 /** Find or create an implicit method of exactly the given type (after erasure).
1759 * Searches in a side table, not the main scope of the site.
1760 * This emulates the lookup process required by JSR 292 in JVM.
1761 * @param env Attribution environment
1762 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
1763 * @param argtypes The required argument types
1764 */
1765 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
1766 Symbol spMethod,
1767 List<Type> argtypes) {
1768 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
1769 (MethodSymbol)spMethod, argtypes);
1770 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
1771 if (types.isSameType(mtype, sym.type)) {
1772 return sym;
1773 }
1774 }
1776 // create the desired method
1777 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
1778 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
1779 polymorphicSignatureScope.enter(msym);
1780 return msym;
1781 }
1783 /** Resolve a qualified method identifier, throw a fatal error if not
1784 * found.
1785 * @param pos The position to use for error reporting.
1786 * @param env The environment current at the method invocation.
1787 * @param site The type of the qualifying expression, in which
1788 * identifier is searched.
1789 * @param name The identifier's name.
1790 * @param argtypes The types of the invocation's value arguments.
1791 * @param typeargtypes The types of the invocation's type arguments.
1792 */
1793 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
1794 Type site, Name name,
1795 List<Type> argtypes,
1796 List<Type> typeargtypes) {
1797 MethodResolutionContext resolveContext = new MethodResolutionContext();
1798 resolveContext.internalResolution = true;
1799 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
1800 site, name, argtypes, typeargtypes);
1801 if (sym.kind == MTH) return (MethodSymbol)sym;
1802 else throw new FatalError(
1803 diags.fragment("fatal.err.cant.locate.meth",
1804 name));
1805 }
1807 /** Resolve constructor.
1808 * @param pos The position to use for error reporting.
1809 * @param env The environment current at the constructor invocation.
1810 * @param site The type of class for which a constructor is searched.
1811 * @param argtypes The types of the constructor invocation's value
1812 * arguments.
1813 * @param typeargtypes The types of the constructor invocation's type
1814 * arguments.
1815 */
1816 Symbol resolveConstructor(DiagnosticPosition pos,
1817 Env<AttrContext> env,
1818 Type site,
1819 List<Type> argtypes,
1820 List<Type> typeargtypes) {
1821 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
1822 }
1823 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
1824 DiagnosticPosition pos,
1825 Env<AttrContext> env,
1826 Type site,
1827 List<Type> argtypes,
1828 List<Type> typeargtypes) {
1829 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1830 try {
1831 currentResolutionContext = resolveContext;
1832 Symbol sym = methodNotFound;
1833 List<MethodResolutionPhase> steps = methodResolutionSteps;
1834 while (steps.nonEmpty() &&
1835 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1836 sym.kind >= ERRONEOUS) {
1837 currentResolutionContext.step = steps.head;
1838 sym = findConstructor(pos, env, site, argtypes, typeargtypes,
1839 steps.head.isBoxingRequired(),
1840 env.info.varArgs = steps.head.isVarargsRequired());
1841 currentResolutionContext.resolutionCache.put(steps.head, sym);
1842 steps = steps.tail;
1843 }
1844 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1845 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
1846 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1847 pos, site, names.init, true, argtypes, typeargtypes);
1848 env.info.varArgs = errPhase.isVarargsRequired();
1849 }
1850 return sym;
1851 }
1852 finally {
1853 currentResolutionContext = prevResolutionContext;
1854 }
1855 }
1857 /** Resolve constructor using diamond inference.
1858 * @param pos The position to use for error reporting.
1859 * @param env The environment current at the constructor invocation.
1860 * @param site The type of class for which a constructor is searched.
1861 * The scope of this class has been touched in attribution.
1862 * @param argtypes The types of the constructor invocation's value
1863 * arguments.
1864 * @param typeargtypes The types of the constructor invocation's type
1865 * arguments.
1866 */
1867 Symbol resolveDiamond(DiagnosticPosition pos,
1868 Env<AttrContext> env,
1869 Type site,
1870 List<Type> argtypes,
1871 List<Type> typeargtypes) {
1872 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1873 try {
1874 currentResolutionContext = new MethodResolutionContext();
1875 Symbol sym = methodNotFound;
1876 List<MethodResolutionPhase> steps = methodResolutionSteps;
1877 while (steps.nonEmpty() &&
1878 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1879 sym.kind >= ERRONEOUS) {
1880 currentResolutionContext.step = steps.head;
1881 sym = findDiamond(env, site, argtypes, typeargtypes,
1882 steps.head.isBoxingRequired(),
1883 env.info.varArgs = steps.head.isVarargsRequired());
1884 currentResolutionContext.resolutionCache.put(steps.head, sym);
1885 steps = steps.tail;
1886 }
1887 if (sym.kind >= AMBIGUOUS) {
1888 final JCDiagnostic details = sym.kind == WRONG_MTH ?
1889 currentResolutionContext.candidates.head.details :
1890 null;
1891 Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
1892 @Override
1893 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
1894 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
1895 String key = details == null ?
1896 "cant.apply.diamond" :
1897 "cant.apply.diamond.1";
1898 return diags.create(dkind, log.currentSource(), pos, key,
1899 diags.fragment("diamond", site.tsym), details);
1900 }
1901 };
1902 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
1903 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
1904 env.info.varArgs = errPhase.isVarargsRequired();
1905 }
1906 return sym;
1907 }
1908 finally {
1909 currentResolutionContext = prevResolutionContext;
1910 }
1911 }
1913 /** This method scans all the constructor symbol in a given class scope -
1914 * assuming that the original scope contains a constructor of the kind:
1915 * Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1916 * a method check is executed against the modified constructor type:
1917 * <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1918 * inference. The inferred return type of the synthetic constructor IS
1919 * the inferred type for the diamond operator.
1920 */
1921 private Symbol findDiamond(Env<AttrContext> env,
1922 Type site,
1923 List<Type> argtypes,
1924 List<Type> typeargtypes,
1925 boolean allowBoxing,
1926 boolean useVarargs) {
1927 Symbol bestSoFar = methodNotFound;
1928 for (Scope.Entry e = site.tsym.members().lookup(names.init);
1929 e.scope != null;
1930 e = e.next()) {
1931 //- System.out.println(" e " + e.sym);
1932 if (e.sym.kind == MTH &&
1933 (e.sym.flags_field & SYNTHETIC) == 0) {
1934 List<Type> oldParams = e.sym.type.tag == FORALL ?
1935 ((ForAll)e.sym.type).tvars :
1936 List.<Type>nil();
1937 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
1938 types.createMethodTypeWithReturn(e.sym.type.asMethodType(), site));
1939 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
1940 new MethodSymbol(e.sym.flags(), names.init, constrType, site.tsym),
1941 bestSoFar,
1942 allowBoxing,
1943 useVarargs,
1944 false);
1945 }
1946 }
1947 return bestSoFar;
1948 }
1950 /** Resolve constructor.
1951 * @param pos The position to use for error reporting.
1952 * @param env The environment current at the constructor invocation.
1953 * @param site The type of class for which a constructor is searched.
1954 * @param argtypes The types of the constructor invocation's value
1955 * arguments.
1956 * @param typeargtypes The types of the constructor invocation's type
1957 * arguments.
1958 * @param allowBoxing Allow boxing and varargs conversions.
1959 * @param useVarargs Box trailing arguments into an array for varargs.
1960 */
1961 Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1962 Type site, List<Type> argtypes,
1963 List<Type> typeargtypes,
1964 boolean allowBoxing,
1965 boolean useVarargs) {
1966 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1967 try {
1968 currentResolutionContext = new MethodResolutionContext();
1969 return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
1970 }
1971 finally {
1972 currentResolutionContext = prevResolutionContext;
1973 }
1974 }
1976 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1977 Type site, List<Type> argtypes,
1978 List<Type> typeargtypes,
1979 boolean allowBoxing,
1980 boolean useVarargs) {
1981 Symbol sym = findMethod(env, site,
1982 names.init, argtypes,
1983 typeargtypes, allowBoxing,
1984 useVarargs, false);
1985 chk.checkDeprecated(pos, env.info.scope.owner, sym);
1986 return sym;
1987 }
1989 /** Resolve a constructor, throw a fatal error if not found.
1990 * @param pos The position to use for error reporting.
1991 * @param env The environment current at the method invocation.
1992 * @param site The type to be constructed.
1993 * @param argtypes The types of the invocation's value arguments.
1994 * @param typeargtypes The types of the invocation's type arguments.
1995 */
1996 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1997 Type site,
1998 List<Type> argtypes,
1999 List<Type> typeargtypes) {
2000 MethodResolutionContext resolveContext = new MethodResolutionContext();
2001 resolveContext.internalResolution = true;
2002 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2003 if (sym.kind == MTH) return (MethodSymbol)sym;
2004 else throw new FatalError(
2005 diags.fragment("fatal.err.cant.locate.ctor", site));
2006 }
2008 /** Resolve operator.
2009 * @param pos The position to use for error reporting.
2010 * @param optag The tag of the operation tree.
2011 * @param env The environment current at the operation.
2012 * @param argtypes The types of the operands.
2013 */
2014 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2015 Env<AttrContext> env, List<Type> argtypes) {
2016 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2017 try {
2018 currentResolutionContext = new MethodResolutionContext();
2019 Name name = treeinfo.operatorName(optag);
2020 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2021 null, false, false, true);
2022 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2023 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2024 null, true, false, true);
2025 return access(sym, pos, env.enclClass.sym.type, name,
2026 false, argtypes, null);
2027 }
2028 finally {
2029 currentResolutionContext = prevResolutionContext;
2030 }
2031 }
2033 /** Resolve operator.
2034 * @param pos The position to use for error reporting.
2035 * @param optag The tag of the operation tree.
2036 * @param env The environment current at the operation.
2037 * @param arg The type of the operand.
2038 */
2039 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2040 return resolveOperator(pos, optag, env, List.of(arg));
2041 }
2043 /** Resolve binary operator.
2044 * @param pos The position to use for error reporting.
2045 * @param optag The tag of the operation tree.
2046 * @param env The environment current at the operation.
2047 * @param left The types of the left operand.
2048 * @param right The types of the right operand.
2049 */
2050 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2051 JCTree.Tag optag,
2052 Env<AttrContext> env,
2053 Type left,
2054 Type right) {
2055 return resolveOperator(pos, optag, env, List.of(left, right));
2056 }
2058 /**
2059 * Resolve `c.name' where name == this or name == super.
2060 * @param pos The position to use for error reporting.
2061 * @param env The environment current at the expression.
2062 * @param c The qualifier.
2063 * @param name The identifier's name.
2064 */
2065 Symbol resolveSelf(DiagnosticPosition pos,
2066 Env<AttrContext> env,
2067 TypeSymbol c,
2068 Name name) {
2069 Env<AttrContext> env1 = env;
2070 boolean staticOnly = false;
2071 while (env1.outer != null) {
2072 if (isStatic(env1)) staticOnly = true;
2073 if (env1.enclClass.sym == c) {
2074 Symbol sym = env1.info.scope.lookup(name).sym;
2075 if (sym != null) {
2076 if (staticOnly) sym = new StaticError(sym);
2077 return access(sym, pos, env.enclClass.sym.type,
2078 name, true);
2079 }
2080 }
2081 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2082 env1 = env1.outer;
2083 }
2084 log.error(pos, "not.encl.class", c);
2085 return syms.errSymbol;
2086 }
2088 /**
2089 * Resolve `c.this' for an enclosing class c that contains the
2090 * named member.
2091 * @param pos The position to use for error reporting.
2092 * @param env The environment current at the expression.
2093 * @param member The member that must be contained in the result.
2094 */
2095 Symbol resolveSelfContaining(DiagnosticPosition pos,
2096 Env<AttrContext> env,
2097 Symbol member,
2098 boolean isSuperCall) {
2099 Name name = names._this;
2100 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2101 boolean staticOnly = false;
2102 if (env1 != null) {
2103 while (env1 != null && env1.outer != null) {
2104 if (isStatic(env1)) staticOnly = true;
2105 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2106 Symbol sym = env1.info.scope.lookup(name).sym;
2107 if (sym != null) {
2108 if (staticOnly) sym = new StaticError(sym);
2109 return access(sym, pos, env.enclClass.sym.type,
2110 name, true);
2111 }
2112 }
2113 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2114 staticOnly = true;
2115 env1 = env1.outer;
2116 }
2117 }
2118 log.error(pos, "encl.class.required", member);
2119 return syms.errSymbol;
2120 }
2122 /**
2123 * Resolve an appropriate implicit this instance for t's container.
2124 * JLS 8.8.5.1 and 15.9.2
2125 */
2126 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2127 return resolveImplicitThis(pos, env, t, false);
2128 }
2130 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2131 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2132 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2133 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2134 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2135 log.error(pos, "cant.ref.before.ctor.called", "this");
2136 return thisType;
2137 }
2139 /* ***************************************************************************
2140 * ResolveError classes, indicating error situations when accessing symbols
2141 ****************************************************************************/
2143 //used by TransTypes when checking target type of synthetic cast
2144 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2145 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2146 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2147 }
2148 //where
2149 private void logResolveError(ResolveError error,
2150 DiagnosticPosition pos,
2151 Symbol location,
2152 Type site,
2153 Name name,
2154 List<Type> argtypes,
2155 List<Type> typeargtypes) {
2156 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2157 pos, location, site, name, argtypes, typeargtypes);
2158 if (d != null) {
2159 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2160 log.report(d);
2161 }
2162 }
2164 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2166 public Object methodArguments(List<Type> argtypes) {
2167 return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
2168 }
2170 /**
2171 * Root class for resolution errors. Subclass of ResolveError
2172 * represent a different kinds of resolution error - as such they must
2173 * specify how they map into concrete compiler diagnostics.
2174 */
2175 private abstract class ResolveError extends Symbol {
2177 /** The name of the kind of error, for debugging only. */
2178 final String debugName;
2180 ResolveError(int kind, String debugName) {
2181 super(kind, 0, null, null, null);
2182 this.debugName = debugName;
2183 }
2185 @Override
2186 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2187 throw new AssertionError();
2188 }
2190 @Override
2191 public String toString() {
2192 return debugName;
2193 }
2195 @Override
2196 public boolean exists() {
2197 return false;
2198 }
2200 /**
2201 * Create an external representation for this erroneous symbol to be
2202 * used during attribution - by default this returns the symbol of a
2203 * brand new error type which stores the original type found
2204 * during resolution.
2205 *
2206 * @param name the name used during resolution
2207 * @param location the location from which the symbol is accessed
2208 */
2209 protected Symbol access(Name name, TypeSymbol location) {
2210 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2211 }
2213 /**
2214 * Create a diagnostic representing this resolution error.
2215 *
2216 * @param dkind The kind of the diagnostic to be created (e.g error).
2217 * @param pos The position to be used for error reporting.
2218 * @param site The original type from where the selection took place.
2219 * @param name The name of the symbol to be resolved.
2220 * @param argtypes The invocation's value arguments,
2221 * if we looked for a method.
2222 * @param typeargtypes The invocation's type arguments,
2223 * if we looked for a method.
2224 */
2225 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2226 DiagnosticPosition pos,
2227 Symbol location,
2228 Type site,
2229 Name name,
2230 List<Type> argtypes,
2231 List<Type> typeargtypes);
2233 /**
2234 * A name designates an operator if it consists
2235 * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
2236 */
2237 boolean isOperator(Name name) {
2238 int i = 0;
2239 while (i < name.getByteLength() &&
2240 "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
2241 return i > 0 && i == name.getByteLength();
2242 }
2243 }
2245 /**
2246 * This class is the root class of all resolution errors caused by
2247 * an invalid symbol being found during resolution.
2248 */
2249 abstract class InvalidSymbolError extends ResolveError {
2251 /** The invalid symbol found during resolution */
2252 Symbol sym;
2254 InvalidSymbolError(int kind, Symbol sym, String debugName) {
2255 super(kind, debugName);
2256 this.sym = sym;
2257 }
2259 @Override
2260 public boolean exists() {
2261 return true;
2262 }
2264 @Override
2265 public String toString() {
2266 return super.toString() + " wrongSym=" + sym;
2267 }
2269 @Override
2270 public Symbol access(Name name, TypeSymbol location) {
2271 if (sym.kind >= AMBIGUOUS)
2272 return ((ResolveError)sym).access(name, location);
2273 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
2274 return types.createErrorType(name, location, sym.type).tsym;
2275 else
2276 return sym;
2277 }
2278 }
2280 /**
2281 * InvalidSymbolError error class indicating that a symbol matching a
2282 * given name does not exists in a given site.
2283 */
2284 class SymbolNotFoundError extends ResolveError {
2286 SymbolNotFoundError(int kind) {
2287 super(kind, "symbol not found error");
2288 }
2290 @Override
2291 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2292 DiagnosticPosition pos,
2293 Symbol location,
2294 Type site,
2295 Name name,
2296 List<Type> argtypes,
2297 List<Type> typeargtypes) {
2298 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
2299 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
2300 if (name == names.error)
2301 return null;
2303 if (isOperator(name)) {
2304 boolean isUnaryOp = argtypes.size() == 1;
2305 String key = argtypes.size() == 1 ?
2306 "operator.cant.be.applied" :
2307 "operator.cant.be.applied.1";
2308 Type first = argtypes.head;
2309 Type second = !isUnaryOp ? argtypes.tail.head : null;
2310 return diags.create(dkind, log.currentSource(), pos,
2311 key, name, first, second);
2312 }
2313 boolean hasLocation = false;
2314 if (location == null) {
2315 location = site.tsym;
2316 }
2317 if (!location.name.isEmpty()) {
2318 if (location.kind == PCK && !site.tsym.exists()) {
2319 return diags.create(dkind, log.currentSource(), pos,
2320 "doesnt.exist", location);
2321 }
2322 hasLocation = !location.name.equals(names._this) &&
2323 !location.name.equals(names._super);
2324 }
2325 boolean isConstructor = kind == ABSENT_MTH &&
2326 name == names.table.names.init;
2327 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
2328 Name idname = isConstructor ? site.tsym.name : name;
2329 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
2330 if (hasLocation) {
2331 return diags.create(dkind, log.currentSource(), pos,
2332 errKey, kindname, idname, //symbol kindname, name
2333 typeargtypes, argtypes, //type parameters and arguments (if any)
2334 getLocationDiag(location, site)); //location kindname, type
2335 }
2336 else {
2337 return diags.create(dkind, log.currentSource(), pos,
2338 errKey, kindname, idname, //symbol kindname, name
2339 typeargtypes, argtypes); //type parameters and arguments (if any)
2340 }
2341 }
2342 //where
2343 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
2344 String key = "cant.resolve";
2345 String suffix = hasLocation ? ".location" : "";
2346 switch (kindname) {
2347 case METHOD:
2348 case CONSTRUCTOR: {
2349 suffix += ".args";
2350 suffix += hasTypeArgs ? ".params" : "";
2351 }
2352 }
2353 return key + suffix;
2354 }
2355 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
2356 if (location.kind == VAR) {
2357 return diags.fragment("location.1",
2358 kindName(location),
2359 location,
2360 location.type);
2361 } else {
2362 return diags.fragment("location",
2363 typeKindName(site),
2364 site,
2365 null);
2366 }
2367 }
2368 }
2370 /**
2371 * InvalidSymbolError error class indicating that a given symbol
2372 * (either a method, a constructor or an operand) is not applicable
2373 * given an actual arguments/type argument list.
2374 */
2375 class InapplicableSymbolError extends ResolveError {
2377 InapplicableSymbolError() {
2378 super(WRONG_MTH, "inapplicable symbol error");
2379 }
2381 protected InapplicableSymbolError(int kind, String debugName) {
2382 super(kind, debugName);
2383 }
2385 @Override
2386 public String toString() {
2387 return super.toString();
2388 }
2390 @Override
2391 public boolean exists() {
2392 return true;
2393 }
2395 @Override
2396 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2397 DiagnosticPosition pos,
2398 Symbol location,
2399 Type site,
2400 Name name,
2401 List<Type> argtypes,
2402 List<Type> typeargtypes) {
2403 if (name == names.error)
2404 return null;
2406 if (isOperator(name)) {
2407 boolean isUnaryOp = argtypes.size() == 1;
2408 String key = argtypes.size() == 1 ?
2409 "operator.cant.be.applied" :
2410 "operator.cant.be.applied.1";
2411 Type first = argtypes.head;
2412 Type second = !isUnaryOp ? argtypes.tail.head : null;
2413 return diags.create(dkind, log.currentSource(), pos,
2414 key, name, first, second);
2415 }
2416 else {
2417 Candidate c = errCandidate();
2418 Symbol ws = c.sym.asMemberOf(site, types);
2419 return diags.create(dkind, log.currentSource(), pos,
2420 "cant.apply.symbol" + (c.details != null ? ".1" : ""),
2421 kindName(ws),
2422 ws.name == names.init ? ws.owner.name : ws.name,
2423 methodArguments(ws.type.getParameterTypes()),
2424 methodArguments(argtypes),
2425 kindName(ws.owner),
2426 ws.owner.type,
2427 c.details);
2428 }
2429 }
2431 @Override
2432 public Symbol access(Name name, TypeSymbol location) {
2433 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2434 }
2436 protected boolean shouldReport(Candidate c) {
2437 return !c.isApplicable() &&
2438 (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
2439 (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
2440 }
2442 private Candidate errCandidate() {
2443 for (Candidate c : currentResolutionContext.candidates) {
2444 if (shouldReport(c)) {
2445 return c;
2446 }
2447 }
2448 Assert.error();
2449 return null;
2450 }
2451 }
2453 /**
2454 * ResolveError error class indicating that a set of symbols
2455 * (either methods, constructors or operands) is not applicable
2456 * given an actual arguments/type argument list.
2457 */
2458 class InapplicableSymbolsError extends InapplicableSymbolError {
2460 InapplicableSymbolsError() {
2461 super(WRONG_MTHS, "inapplicable symbols");
2462 }
2464 @Override
2465 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2466 DiagnosticPosition pos,
2467 Symbol location,
2468 Type site,
2469 Name name,
2470 List<Type> argtypes,
2471 List<Type> typeargtypes) {
2472 if (currentResolutionContext.candidates.nonEmpty()) {
2473 JCDiagnostic err = diags.create(dkind,
2474 log.currentSource(),
2475 pos,
2476 "cant.apply.symbols",
2477 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2478 getName(),
2479 argtypes);
2480 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2481 } else {
2482 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2483 location, site, name, argtypes, typeargtypes);
2484 }
2485 }
2487 //where
2488 List<JCDiagnostic> candidateDetails(Type site) {
2489 List<JCDiagnostic> details = List.nil();
2490 for (Candidate c : currentResolutionContext.candidates) {
2491 if (!shouldReport(c)) continue;
2492 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
2493 Kinds.kindName(c.sym),
2494 c.sym.location(site, types),
2495 c.sym.asMemberOf(site, types),
2496 c.details);
2497 details = details.prepend(detailDiag);
2498 }
2499 return details.reverse();
2500 }
2502 private Name getName() {
2503 Symbol sym = currentResolutionContext.candidates.head.sym;
2504 return sym.name == names.init ?
2505 sym.owner.name :
2506 sym.name;
2507 }
2508 }
2510 /**
2511 * An InvalidSymbolError error class indicating that a symbol is not
2512 * accessible from a given site
2513 */
2514 class AccessError extends InvalidSymbolError {
2516 private Env<AttrContext> env;
2517 private Type site;
2519 AccessError(Symbol sym) {
2520 this(null, null, sym);
2521 }
2523 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2524 super(HIDDEN, sym, "access error");
2525 this.env = env;
2526 this.site = site;
2527 if (debugResolve)
2528 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2529 }
2531 @Override
2532 public boolean exists() {
2533 return false;
2534 }
2536 @Override
2537 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2538 DiagnosticPosition pos,
2539 Symbol location,
2540 Type site,
2541 Name name,
2542 List<Type> argtypes,
2543 List<Type> typeargtypes) {
2544 if (sym.owner.type.tag == ERROR)
2545 return null;
2547 if (sym.name == names.init && sym.owner != site.tsym) {
2548 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2549 pos, location, site, name, argtypes, typeargtypes);
2550 }
2551 else if ((sym.flags() & PUBLIC) != 0
2552 || (env != null && this.site != null
2553 && !isAccessible(env, this.site))) {
2554 return diags.create(dkind, log.currentSource(),
2555 pos, "not.def.access.class.intf.cant.access",
2556 sym, sym.location());
2557 }
2558 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2559 return diags.create(dkind, log.currentSource(),
2560 pos, "report.access", sym,
2561 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2562 sym.location());
2563 }
2564 else {
2565 return diags.create(dkind, log.currentSource(),
2566 pos, "not.def.public.cant.access", sym, sym.location());
2567 }
2568 }
2569 }
2571 /**
2572 * InvalidSymbolError error class indicating that an instance member
2573 * has erroneously been accessed from a static context.
2574 */
2575 class StaticError extends InvalidSymbolError {
2577 StaticError(Symbol sym) {
2578 super(STATICERR, sym, "static error");
2579 }
2581 @Override
2582 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2583 DiagnosticPosition pos,
2584 Symbol location,
2585 Type site,
2586 Name name,
2587 List<Type> argtypes,
2588 List<Type> typeargtypes) {
2589 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2590 ? types.erasure(sym.type).tsym
2591 : sym);
2592 return diags.create(dkind, log.currentSource(), pos,
2593 "non-static.cant.be.ref", kindName(sym), errSym);
2594 }
2595 }
2597 /**
2598 * InvalidSymbolError error class indicating that a pair of symbols
2599 * (either methods, constructors or operands) are ambiguous
2600 * given an actual arguments/type argument list.
2601 */
2602 class AmbiguityError extends InvalidSymbolError {
2604 /** The other maximally specific symbol */
2605 Symbol sym2;
2607 AmbiguityError(Symbol sym1, Symbol sym2) {
2608 super(AMBIGUOUS, sym1, "ambiguity error");
2609 this.sym2 = sym2;
2610 }
2612 @Override
2613 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2614 DiagnosticPosition pos,
2615 Symbol location,
2616 Type site,
2617 Name name,
2618 List<Type> argtypes,
2619 List<Type> typeargtypes) {
2620 AmbiguityError pair = this;
2621 while (true) {
2622 if (pair.sym.kind == AMBIGUOUS)
2623 pair = (AmbiguityError)pair.sym;
2624 else if (pair.sym2.kind == AMBIGUOUS)
2625 pair = (AmbiguityError)pair.sym2;
2626 else break;
2627 }
2628 Name sname = pair.sym.name;
2629 if (sname == names.init) sname = pair.sym.owner.name;
2630 return diags.create(dkind, log.currentSource(),
2631 pos, "ref.ambiguous", sname,
2632 kindName(pair.sym),
2633 pair.sym,
2634 pair.sym.location(site, types),
2635 kindName(pair.sym2),
2636 pair.sym2,
2637 pair.sym2.location(site, types));
2638 }
2639 }
2641 enum MethodResolutionPhase {
2642 BASIC(false, false),
2643 BOX(true, false),
2644 VARARITY(true, true);
2646 boolean isBoxingRequired;
2647 boolean isVarargsRequired;
2649 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2650 this.isBoxingRequired = isBoxingRequired;
2651 this.isVarargsRequired = isVarargsRequired;
2652 }
2654 public boolean isBoxingRequired() {
2655 return isBoxingRequired;
2656 }
2658 public boolean isVarargsRequired() {
2659 return isVarargsRequired;
2660 }
2662 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2663 return (varargsEnabled || !isVarargsRequired) &&
2664 (boxingEnabled || !isBoxingRequired);
2665 }
2666 }
2668 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2670 /**
2671 * A resolution context is used to keep track of intermediate results of
2672 * overload resolution, such as list of method that are not applicable
2673 * (used to generate more precise diagnostics) and so on. Resolution contexts
2674 * can be nested - this means that when each overload resolution routine should
2675 * work within the resolution context it created.
2676 */
2677 class MethodResolutionContext {
2679 private List<Candidate> candidates = List.nil();
2681 private Map<MethodResolutionPhase, Symbol> resolutionCache =
2682 new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
2684 private MethodResolutionPhase step = null;
2686 private boolean internalResolution = false;
2688 private MethodResolutionPhase firstErroneousResolutionPhase() {
2689 MethodResolutionPhase bestSoFar = BASIC;
2690 Symbol sym = methodNotFound;
2691 List<MethodResolutionPhase> steps = methodResolutionSteps;
2692 while (steps.nonEmpty() &&
2693 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2694 sym.kind >= WRONG_MTHS) {
2695 sym = resolutionCache.get(steps.head);
2696 bestSoFar = steps.head;
2697 steps = steps.tail;
2698 }
2699 return bestSoFar;
2700 }
2702 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
2703 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
2704 if (!candidates.contains(c))
2705 candidates = candidates.append(c);
2706 }
2708 void addApplicableCandidate(Symbol sym, Type mtype) {
2709 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
2710 candidates = candidates.append(c);
2711 }
2713 /**
2714 * This class represents an overload resolution candidate. There are two
2715 * kinds of candidates: applicable methods and inapplicable methods;
2716 * applicable methods have a pointer to the instantiated method type,
2717 * while inapplicable candidates contain further details about the
2718 * reason why the method has been considered inapplicable.
2719 */
2720 class Candidate {
2722 final MethodResolutionPhase step;
2723 final Symbol sym;
2724 final JCDiagnostic details;
2725 final Type mtype;
2727 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
2728 this.step = step;
2729 this.sym = sym;
2730 this.details = details;
2731 this.mtype = mtype;
2732 }
2734 @Override
2735 public boolean equals(Object o) {
2736 if (o instanceof Candidate) {
2737 Symbol s1 = this.sym;
2738 Symbol s2 = ((Candidate)o).sym;
2739 if ((s1 != s2 &&
2740 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2741 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2742 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2743 return true;
2744 }
2745 return false;
2746 }
2748 boolean isApplicable() {
2749 return mtype != null;
2750 }
2751 }
2752 }
2754 MethodResolutionContext currentResolutionContext = null;
2755 }