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