Thu, 31 May 2012 17:42:14 +0100
7166552: Inference: cleanup usage of Type.ForAll
Summary: Remove hack to callback into type-inference from assignment context
Reviewed-by: dlsmith, jjg
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, Type found, Type expected);
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, Type found, Type expected) {
569 String key = varargs ?
570 "varargs.argument.mismatch" :
571 "no.conforming.assignment.exists";
572 return inapplicableMethodException.setMessage(key,
573 found, expected);
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, Type found, Type req, JCDiagnostic details) {
671 throw handler.argumentMismatch(useVarargs, found, req);
672 }
674 public Type rawInstantiatePoly(ForAll found, Type req, Warner warn) {
675 throw new AssertionError("ForAll in argument position");
676 }
678 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
679 return rsWarner;
680 }
681 }
683 /**
684 * Subclass of method check context class that implements strict method conversion.
685 * Strict method conversion checks compatibility between types using subtyping tests.
686 */
687 class StrictMethodContext extends MethodCheckContext {
689 public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs, List<Type> undetvars, Warner rsWarner) {
690 super(handler, useVarargs, undetvars, rsWarner);
691 }
693 public boolean compatible(Type found, Type req, Warner warn) {
694 return types.isSubtypeUnchecked(found, infer.asUndetType(req, undetvars), warn);
695 }
696 }
698 /**
699 * Subclass of method check context class that implements loose method conversion.
700 * Loose method conversion checks compatibility between types using method conversion tests.
701 */
702 class LooseMethodContext extends MethodCheckContext {
704 public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs, List<Type> undetvars, Warner rsWarner) {
705 super(handler, useVarargs, undetvars, rsWarner);
706 }
708 public boolean compatible(Type found, Type req, Warner warn) {
709 return types.isConvertible(found, infer.asUndetType(req, undetvars), warn);
710 }
711 }
713 /**
714 * Create a method check context to be used during method applicability check
715 */
716 ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
717 List<Type> undetvars, MethodCheckHandler methodHandler, Warner rsWarner) {
718 MethodCheckContext checkContext = allowBoxing ?
719 new LooseMethodContext(methodHandler, useVarargs, undetvars, rsWarner) :
720 new StrictMethodContext(methodHandler, useVarargs, undetvars, rsWarner);
721 return attr.new ResultInfo(VAL, to, checkContext) {
722 @Override
723 protected Type check(DiagnosticPosition pos, Type found) {
724 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found))));
725 }
726 };
727 }
729 public static class InapplicableMethodException extends RuntimeException {
730 private static final long serialVersionUID = 0;
732 JCDiagnostic diagnostic;
733 JCDiagnostic.Factory diags;
735 InapplicableMethodException(JCDiagnostic.Factory diags) {
736 this.diagnostic = null;
737 this.diags = diags;
738 }
739 InapplicableMethodException setMessage() {
740 this.diagnostic = null;
741 return this;
742 }
743 InapplicableMethodException setMessage(String key) {
744 this.diagnostic = key != null ? diags.fragment(key) : null;
745 return this;
746 }
747 InapplicableMethodException setMessage(String key, Object... args) {
748 this.diagnostic = key != null ? diags.fragment(key, args) : null;
749 return this;
750 }
751 InapplicableMethodException setMessage(JCDiagnostic diag) {
752 this.diagnostic = diag;
753 return this;
754 }
756 public JCDiagnostic getDiagnostic() {
757 return diagnostic;
758 }
759 }
760 private final InapplicableMethodException inapplicableMethodException;
762 /* ***************************************************************************
763 * Symbol lookup
764 * the following naming conventions for arguments are used
765 *
766 * env is the environment where the symbol was mentioned
767 * site is the type of which the symbol is a member
768 * name is the symbol's name
769 * if no arguments are given
770 * argtypes are the value arguments, if we search for a method
771 *
772 * If no symbol was found, a ResolveError detailing the problem is returned.
773 ****************************************************************************/
775 /** Find field. Synthetic fields are always skipped.
776 * @param env The current environment.
777 * @param site The original type from where the selection takes place.
778 * @param name The name of the field.
779 * @param c The class to search for the field. This is always
780 * a superclass or implemented interface of site's class.
781 */
782 Symbol findField(Env<AttrContext> env,
783 Type site,
784 Name name,
785 TypeSymbol c) {
786 while (c.type.tag == TYPEVAR)
787 c = c.type.getUpperBound().tsym;
788 Symbol bestSoFar = varNotFound;
789 Symbol sym;
790 Scope.Entry e = c.members().lookup(name);
791 while (e.scope != null) {
792 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
793 return isAccessible(env, site, e.sym)
794 ? e.sym : new AccessError(env, site, e.sym);
795 }
796 e = e.next();
797 }
798 Type st = types.supertype(c.type);
799 if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
800 sym = findField(env, site, name, st.tsym);
801 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
802 }
803 for (List<Type> l = types.interfaces(c.type);
804 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
805 l = l.tail) {
806 sym = findField(env, site, name, l.head.tsym);
807 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
808 sym.owner != bestSoFar.owner)
809 bestSoFar = new AmbiguityError(bestSoFar, sym);
810 else if (sym.kind < bestSoFar.kind)
811 bestSoFar = sym;
812 }
813 return bestSoFar;
814 }
816 /** Resolve a field identifier, throw a fatal error if not found.
817 * @param pos The position to use for error reporting.
818 * @param env The environment current at the method invocation.
819 * @param site The type of the qualifying expression, in which
820 * identifier is searched.
821 * @param name The identifier's name.
822 */
823 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
824 Type site, Name name) {
825 Symbol sym = findField(env, site, name, site.tsym);
826 if (sym.kind == VAR) return (VarSymbol)sym;
827 else throw new FatalError(
828 diags.fragment("fatal.err.cant.locate.field",
829 name));
830 }
832 /** Find unqualified variable or field with given name.
833 * Synthetic fields always skipped.
834 * @param env The current environment.
835 * @param name The name of the variable or field.
836 */
837 Symbol findVar(Env<AttrContext> env, Name name) {
838 Symbol bestSoFar = varNotFound;
839 Symbol sym;
840 Env<AttrContext> env1 = env;
841 boolean staticOnly = false;
842 while (env1.outer != null) {
843 if (isStatic(env1)) staticOnly = true;
844 Scope.Entry e = env1.info.scope.lookup(name);
845 while (e.scope != null &&
846 (e.sym.kind != VAR ||
847 (e.sym.flags_field & SYNTHETIC) != 0))
848 e = e.next();
849 sym = (e.scope != null)
850 ? e.sym
851 : findField(
852 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
853 if (sym.exists()) {
854 if (staticOnly &&
855 sym.kind == VAR &&
856 sym.owner.kind == TYP &&
857 (sym.flags() & STATIC) == 0)
858 return new StaticError(sym);
859 else
860 return sym;
861 } else if (sym.kind < bestSoFar.kind) {
862 bestSoFar = sym;
863 }
865 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
866 env1 = env1.outer;
867 }
869 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
870 if (sym.exists())
871 return sym;
872 if (bestSoFar.exists())
873 return bestSoFar;
875 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
876 for (; e.scope != null; e = e.next()) {
877 sym = e.sym;
878 Type origin = e.getOrigin().owner.type;
879 if (sym.kind == VAR) {
880 if (e.sym.owner.type != origin)
881 sym = sym.clone(e.getOrigin().owner);
882 return isAccessible(env, origin, sym)
883 ? sym : new AccessError(env, origin, sym);
884 }
885 }
887 Symbol origin = null;
888 e = env.toplevel.starImportScope.lookup(name);
889 for (; e.scope != null; e = e.next()) {
890 sym = e.sym;
891 if (sym.kind != VAR)
892 continue;
893 // invariant: sym.kind == VAR
894 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
895 return new AmbiguityError(bestSoFar, sym);
896 else if (bestSoFar.kind >= VAR) {
897 origin = e.getOrigin().owner;
898 bestSoFar = isAccessible(env, origin.type, sym)
899 ? sym : new AccessError(env, origin.type, sym);
900 }
901 }
902 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
903 return bestSoFar.clone(origin);
904 else
905 return bestSoFar;
906 }
908 Warner noteWarner = new Warner();
910 /** Select the best method for a call site among two choices.
911 * @param env The current environment.
912 * @param site The original type from where the
913 * selection takes place.
914 * @param argtypes The invocation's value arguments,
915 * @param typeargtypes The invocation's type arguments,
916 * @param sym Proposed new best match.
917 * @param bestSoFar Previously found best match.
918 * @param allowBoxing Allow boxing conversions of arguments.
919 * @param useVarargs Box trailing arguments into an array for varargs.
920 */
921 @SuppressWarnings("fallthrough")
922 Symbol selectBest(Env<AttrContext> env,
923 Type site,
924 List<Type> argtypes,
925 List<Type> typeargtypes,
926 Symbol sym,
927 Symbol bestSoFar,
928 boolean allowBoxing,
929 boolean useVarargs,
930 boolean operator) {
931 if (sym.kind == ERR) return bestSoFar;
932 if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
933 Assert.check(sym.kind < AMBIGUOUS);
934 try {
935 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
936 allowBoxing, useVarargs, Warner.noWarnings);
937 if (!operator)
938 currentResolutionContext.addApplicableCandidate(sym, mt);
939 } catch (InapplicableMethodException ex) {
940 if (!operator)
941 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
942 switch (bestSoFar.kind) {
943 case ABSENT_MTH:
944 return wrongMethod;
945 case WRONG_MTH:
946 if (operator) return bestSoFar;
947 case WRONG_MTHS:
948 return wrongMethods;
949 default:
950 return bestSoFar;
951 }
952 }
953 if (!isAccessible(env, site, sym)) {
954 return (bestSoFar.kind == ABSENT_MTH)
955 ? new AccessError(env, site, sym)
956 : bestSoFar;
957 }
958 return (bestSoFar.kind > AMBIGUOUS)
959 ? sym
960 : mostSpecific(sym, bestSoFar, env, site,
961 allowBoxing && operator, useVarargs);
962 }
964 /* Return the most specific of the two methods for a call,
965 * given that both are accessible and applicable.
966 * @param m1 A new candidate for most specific.
967 * @param m2 The previous most specific candidate.
968 * @param env The current environment.
969 * @param site The original type from where the selection
970 * takes place.
971 * @param allowBoxing Allow boxing conversions of arguments.
972 * @param useVarargs Box trailing arguments into an array for varargs.
973 */
974 Symbol mostSpecific(Symbol m1,
975 Symbol m2,
976 Env<AttrContext> env,
977 final Type site,
978 boolean allowBoxing,
979 boolean useVarargs) {
980 switch (m2.kind) {
981 case MTH:
982 if (m1 == m2) return m1;
983 boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
984 boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
985 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
986 Type mt1 = types.memberType(site, m1);
987 Type mt2 = types.memberType(site, m2);
988 if (!types.overrideEquivalent(mt1, mt2))
989 return ambiguityError(m1, m2);
991 // same signature; select (a) the non-bridge method, or
992 // (b) the one that overrides the other, or (c) the concrete
993 // one, or (d) merge both abstract signatures
994 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
995 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
997 // if one overrides or hides the other, use it
998 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
999 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1000 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1001 ((m1.owner.flags_field & INTERFACE) == 0 ||
1002 (m2.owner.flags_field & INTERFACE) != 0) &&
1003 m1.overrides(m2, m1Owner, types, false))
1004 return m1;
1005 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1006 ((m2.owner.flags_field & INTERFACE) == 0 ||
1007 (m1.owner.flags_field & INTERFACE) != 0) &&
1008 m2.overrides(m1, m2Owner, types, false))
1009 return m2;
1010 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1011 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1012 if (m1Abstract && !m2Abstract) return m2;
1013 if (m2Abstract && !m1Abstract) return m1;
1014 // both abstract or both concrete
1015 if (!m1Abstract && !m2Abstract)
1016 return ambiguityError(m1, m2);
1017 // check that both signatures have the same erasure
1018 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
1019 m2.erasure(types).getParameterTypes()))
1020 return ambiguityError(m1, m2);
1021 // both abstract, neither overridden; merge throws clause and result type
1022 Type mst = mostSpecificReturnType(mt1, mt2);
1023 if (mst == null) {
1024 // Theoretically, this can't happen, but it is possible
1025 // due to error recovery or mixing incompatible class files
1026 return ambiguityError(m1, m2);
1027 }
1028 Symbol mostSpecific = mst == mt1 ? m1 : m2;
1029 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
1030 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
1031 MethodSymbol result = new MethodSymbol(
1032 mostSpecific.flags(),
1033 mostSpecific.name,
1034 newSig,
1035 mostSpecific.owner) {
1036 @Override
1037 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1038 if (origin == site.tsym)
1039 return this;
1040 else
1041 return super.implementation(origin, types, checkResult);
1042 }
1043 };
1044 return result;
1045 }
1046 if (m1SignatureMoreSpecific) return m1;
1047 if (m2SignatureMoreSpecific) return m2;
1048 return ambiguityError(m1, m2);
1049 case AMBIGUOUS:
1050 AmbiguityError e = (AmbiguityError)m2;
1051 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
1052 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
1053 if (err1 == err2) return err1;
1054 if (err1 == e.sym && err2 == e.sym2) return m2;
1055 if (err1 instanceof AmbiguityError &&
1056 err2 instanceof AmbiguityError &&
1057 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
1058 return ambiguityError(m1, m2);
1059 else
1060 return ambiguityError(err1, err2);
1061 default:
1062 throw new AssertionError();
1063 }
1064 }
1065 //where
1066 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1067 noteWarner.clear();
1068 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
1069 Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs), null,
1070 types.lowerBoundArgtypes(mtype1), null,
1071 allowBoxing, false, noteWarner);
1072 return mtype2 != null &&
1073 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1074 }
1075 //where
1076 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
1077 List<Type> fromArgs = from.type.getParameterTypes();
1078 List<Type> toArgs = to.type.getParameterTypes();
1079 if (useVarargs &&
1080 (from.flags() & VARARGS) != 0 &&
1081 (to.flags() & VARARGS) != 0) {
1082 Type varargsTypeFrom = fromArgs.last();
1083 Type varargsTypeTo = toArgs.last();
1084 ListBuffer<Type> args = ListBuffer.lb();
1085 if (toArgs.length() < fromArgs.length()) {
1086 //if we are checking a varargs method 'from' against another varargs
1087 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
1088 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
1089 //until 'to' signature has the same arity as 'from')
1090 while (fromArgs.head != varargsTypeFrom) {
1091 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
1092 fromArgs = fromArgs.tail;
1093 toArgs = toArgs.head == varargsTypeTo ?
1094 toArgs :
1095 toArgs.tail;
1096 }
1097 } else {
1098 //formal argument list is same as original list where last
1099 //argument (array type) is removed
1100 args.appendList(toArgs.reverse().tail.reverse());
1101 }
1102 //append varargs element type as last synthetic formal
1103 args.append(types.elemtype(varargsTypeTo));
1104 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
1105 return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
1106 } else {
1107 return to;
1108 }
1109 }
1110 //where
1111 Type mostSpecificReturnType(Type mt1, Type mt2) {
1112 Type rt1 = mt1.getReturnType();
1113 Type rt2 = mt2.getReturnType();
1115 if (mt1.tag == FORALL && mt2.tag == FORALL) {
1116 //if both are generic methods, adjust return type ahead of subtyping check
1117 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1118 }
1119 //first use subtyping, then return type substitutability
1120 if (types.isSubtype(rt1, rt2)) {
1121 return mt1;
1122 } else if (types.isSubtype(rt2, rt1)) {
1123 return mt2;
1124 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1125 return mt1;
1126 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1127 return mt2;
1128 } else {
1129 return null;
1130 }
1131 }
1132 //where
1133 Symbol ambiguityError(Symbol m1, Symbol m2) {
1134 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1135 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1136 } else {
1137 return new AmbiguityError(m1, m2);
1138 }
1139 }
1141 /** Find best qualified method matching given name, type and value
1142 * arguments.
1143 * @param env The current environment.
1144 * @param site The original type from where the selection
1145 * takes place.
1146 * @param name The method's name.
1147 * @param argtypes The method's value arguments.
1148 * @param typeargtypes The method's type arguments
1149 * @param allowBoxing Allow boxing conversions of arguments.
1150 * @param useVarargs Box trailing arguments into an array for varargs.
1151 */
1152 Symbol findMethod(Env<AttrContext> env,
1153 Type site,
1154 Name name,
1155 List<Type> argtypes,
1156 List<Type> typeargtypes,
1157 boolean allowBoxing,
1158 boolean useVarargs,
1159 boolean operator) {
1160 Symbol bestSoFar = methodNotFound;
1161 bestSoFar = findMethod(env,
1162 site,
1163 name,
1164 argtypes,
1165 typeargtypes,
1166 site.tsym.type,
1167 true,
1168 bestSoFar,
1169 allowBoxing,
1170 useVarargs,
1171 operator,
1172 new HashSet<TypeSymbol>());
1173 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1174 return bestSoFar;
1175 }
1176 // where
1177 private Symbol findMethod(Env<AttrContext> env,
1178 Type site,
1179 Name name,
1180 List<Type> argtypes,
1181 List<Type> typeargtypes,
1182 Type intype,
1183 boolean abstractok,
1184 Symbol bestSoFar,
1185 boolean allowBoxing,
1186 boolean useVarargs,
1187 boolean operator,
1188 Set<TypeSymbol> seen) {
1189 for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
1190 while (ct.tag == TYPEVAR)
1191 ct = ct.getUpperBound();
1192 ClassSymbol c = (ClassSymbol)ct.tsym;
1193 if (!seen.add(c)) return bestSoFar;
1194 if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
1195 abstractok = false;
1196 for (Scope.Entry e = c.members().lookup(name);
1197 e.scope != null;
1198 e = e.next()) {
1199 //- System.out.println(" e " + e.sym);
1200 if (e.sym.kind == MTH &&
1201 (e.sym.flags_field & SYNTHETIC) == 0) {
1202 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
1203 e.sym, bestSoFar,
1204 allowBoxing,
1205 useVarargs,
1206 operator);
1207 }
1208 }
1209 if (name == names.init)
1210 break;
1211 //- System.out.println(" - " + bestSoFar);
1212 if (abstractok) {
1213 Symbol concrete = methodNotFound;
1214 if ((bestSoFar.flags() & ABSTRACT) == 0)
1215 concrete = bestSoFar;
1216 for (List<Type> l = types.interfaces(c.type);
1217 l.nonEmpty();
1218 l = l.tail) {
1219 bestSoFar = findMethod(env, site, name, argtypes,
1220 typeargtypes,
1221 l.head, abstractok, bestSoFar,
1222 allowBoxing, useVarargs, operator, seen);
1223 }
1224 if (concrete != bestSoFar &&
1225 concrete.kind < ERR && bestSoFar.kind < ERR &&
1226 types.isSubSignature(concrete.type, bestSoFar.type))
1227 bestSoFar = concrete;
1228 }
1229 }
1230 return bestSoFar;
1231 }
1233 /** Find unqualified method matching given name, type and value arguments.
1234 * @param env The current environment.
1235 * @param name The method's name.
1236 * @param argtypes The method's value arguments.
1237 * @param typeargtypes The method's type arguments.
1238 * @param allowBoxing Allow boxing conversions of arguments.
1239 * @param useVarargs Box trailing arguments into an array for varargs.
1240 */
1241 Symbol findFun(Env<AttrContext> env, Name name,
1242 List<Type> argtypes, List<Type> typeargtypes,
1243 boolean allowBoxing, boolean useVarargs) {
1244 Symbol bestSoFar = methodNotFound;
1245 Symbol sym;
1246 Env<AttrContext> env1 = env;
1247 boolean staticOnly = false;
1248 while (env1.outer != null) {
1249 if (isStatic(env1)) staticOnly = true;
1250 sym = findMethod(
1251 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1252 allowBoxing, useVarargs, false);
1253 if (sym.exists()) {
1254 if (staticOnly &&
1255 sym.kind == MTH &&
1256 sym.owner.kind == TYP &&
1257 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1258 else return sym;
1259 } else if (sym.kind < bestSoFar.kind) {
1260 bestSoFar = sym;
1261 }
1262 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1263 env1 = env1.outer;
1264 }
1266 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1267 typeargtypes, allowBoxing, useVarargs, false);
1268 if (sym.exists())
1269 return sym;
1271 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1272 for (; e.scope != null; e = e.next()) {
1273 sym = e.sym;
1274 Type origin = e.getOrigin().owner.type;
1275 if (sym.kind == MTH) {
1276 if (e.sym.owner.type != origin)
1277 sym = sym.clone(e.getOrigin().owner);
1278 if (!isAccessible(env, origin, sym))
1279 sym = new AccessError(env, origin, sym);
1280 bestSoFar = selectBest(env, origin,
1281 argtypes, typeargtypes,
1282 sym, bestSoFar,
1283 allowBoxing, useVarargs, false);
1284 }
1285 }
1286 if (bestSoFar.exists())
1287 return bestSoFar;
1289 e = env.toplevel.starImportScope.lookup(name);
1290 for (; e.scope != null; e = e.next()) {
1291 sym = e.sym;
1292 Type origin = e.getOrigin().owner.type;
1293 if (sym.kind == MTH) {
1294 if (e.sym.owner.type != origin)
1295 sym = sym.clone(e.getOrigin().owner);
1296 if (!isAccessible(env, origin, sym))
1297 sym = new AccessError(env, origin, sym);
1298 bestSoFar = selectBest(env, origin,
1299 argtypes, typeargtypes,
1300 sym, bestSoFar,
1301 allowBoxing, useVarargs, false);
1302 }
1303 }
1304 return bestSoFar;
1305 }
1307 /** Load toplevel or member class with given fully qualified name and
1308 * verify that it is accessible.
1309 * @param env The current environment.
1310 * @param name The fully qualified name of the class to be loaded.
1311 */
1312 Symbol loadClass(Env<AttrContext> env, Name name) {
1313 try {
1314 ClassSymbol c = reader.loadClass(name);
1315 return isAccessible(env, c) ? c : new AccessError(c);
1316 } catch (ClassReader.BadClassFile err) {
1317 throw err;
1318 } catch (CompletionFailure ex) {
1319 return typeNotFound;
1320 }
1321 }
1323 /** Find qualified member type.
1324 * @param env The current environment.
1325 * @param site The original type from where the selection takes
1326 * place.
1327 * @param name The type's name.
1328 * @param c The class to search for the member type. This is
1329 * always a superclass or implemented interface of
1330 * site's class.
1331 */
1332 Symbol findMemberType(Env<AttrContext> env,
1333 Type site,
1334 Name name,
1335 TypeSymbol c) {
1336 Symbol bestSoFar = typeNotFound;
1337 Symbol sym;
1338 Scope.Entry e = c.members().lookup(name);
1339 while (e.scope != null) {
1340 if (e.sym.kind == TYP) {
1341 return isAccessible(env, site, e.sym)
1342 ? e.sym
1343 : new AccessError(env, site, e.sym);
1344 }
1345 e = e.next();
1346 }
1347 Type st = types.supertype(c.type);
1348 if (st != null && st.tag == CLASS) {
1349 sym = findMemberType(env, site, name, st.tsym);
1350 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1351 }
1352 for (List<Type> l = types.interfaces(c.type);
1353 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1354 l = l.tail) {
1355 sym = findMemberType(env, site, name, l.head.tsym);
1356 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1357 sym.owner != bestSoFar.owner)
1358 bestSoFar = new AmbiguityError(bestSoFar, sym);
1359 else if (sym.kind < bestSoFar.kind)
1360 bestSoFar = sym;
1361 }
1362 return bestSoFar;
1363 }
1365 /** Find a global type in given scope and load corresponding class.
1366 * @param env The current environment.
1367 * @param scope The scope in which to look for the type.
1368 * @param name The type's name.
1369 */
1370 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1371 Symbol bestSoFar = typeNotFound;
1372 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1373 Symbol sym = loadClass(env, e.sym.flatName());
1374 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1375 bestSoFar != sym)
1376 return new AmbiguityError(bestSoFar, sym);
1377 else if (sym.kind < bestSoFar.kind)
1378 bestSoFar = sym;
1379 }
1380 return bestSoFar;
1381 }
1383 /** Find an unqualified type symbol.
1384 * @param env The current environment.
1385 * @param name The type's name.
1386 */
1387 Symbol findType(Env<AttrContext> env, Name name) {
1388 Symbol bestSoFar = typeNotFound;
1389 Symbol sym;
1390 boolean staticOnly = false;
1391 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1392 if (isStatic(env1)) staticOnly = true;
1393 for (Scope.Entry e = env1.info.scope.lookup(name);
1394 e.scope != null;
1395 e = e.next()) {
1396 if (e.sym.kind == TYP) {
1397 if (staticOnly &&
1398 e.sym.type.tag == TYPEVAR &&
1399 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1400 return e.sym;
1401 }
1402 }
1404 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1405 env1.enclClass.sym);
1406 if (staticOnly && sym.kind == TYP &&
1407 sym.type.tag == CLASS &&
1408 sym.type.getEnclosingType().tag == CLASS &&
1409 env1.enclClass.sym.type.isParameterized() &&
1410 sym.type.getEnclosingType().isParameterized())
1411 return new StaticError(sym);
1412 else if (sym.exists()) return sym;
1413 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1415 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1416 if ((encl.sym.flags() & STATIC) != 0)
1417 staticOnly = true;
1418 }
1420 if (!env.tree.hasTag(IMPORT)) {
1421 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1422 if (sym.exists()) return sym;
1423 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1425 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1426 if (sym.exists()) return sym;
1427 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1429 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1430 if (sym.exists()) return sym;
1431 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1432 }
1434 return bestSoFar;
1435 }
1437 /** Find an unqualified identifier which matches a specified kind set.
1438 * @param env The current environment.
1439 * @param name The indentifier's name.
1440 * @param kind Indicates the possible symbol kinds
1441 * (a subset of VAL, TYP, PCK).
1442 */
1443 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1444 Symbol bestSoFar = typeNotFound;
1445 Symbol sym;
1447 if ((kind & VAR) != 0) {
1448 sym = findVar(env, name);
1449 if (sym.exists()) return sym;
1450 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1451 }
1453 if ((kind & TYP) != 0) {
1454 sym = findType(env, name);
1455 if (sym.exists()) return sym;
1456 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1457 }
1459 if ((kind & PCK) != 0) return reader.enterPackage(name);
1460 else return bestSoFar;
1461 }
1463 /** Find an identifier in a package which matches a specified kind set.
1464 * @param env The current environment.
1465 * @param name The identifier's name.
1466 * @param kind Indicates the possible symbol kinds
1467 * (a nonempty subset of TYP, PCK).
1468 */
1469 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1470 Name name, int kind) {
1471 Name fullname = TypeSymbol.formFullName(name, pck);
1472 Symbol bestSoFar = typeNotFound;
1473 PackageSymbol pack = null;
1474 if ((kind & PCK) != 0) {
1475 pack = reader.enterPackage(fullname);
1476 if (pack.exists()) return pack;
1477 }
1478 if ((kind & TYP) != 0) {
1479 Symbol sym = loadClass(env, fullname);
1480 if (sym.exists()) {
1481 // don't allow programs to use flatnames
1482 if (name == sym.name) return sym;
1483 }
1484 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1485 }
1486 return (pack != null) ? pack : bestSoFar;
1487 }
1489 /** Find an identifier among the members of a given type `site'.
1490 * @param env The current environment.
1491 * @param site The type containing the symbol to be found.
1492 * @param name The identifier's name.
1493 * @param kind Indicates the possible symbol kinds
1494 * (a subset of VAL, TYP).
1495 */
1496 Symbol findIdentInType(Env<AttrContext> env, Type site,
1497 Name name, int kind) {
1498 Symbol bestSoFar = typeNotFound;
1499 Symbol sym;
1500 if ((kind & VAR) != 0) {
1501 sym = findField(env, site, name, site.tsym);
1502 if (sym.exists()) return sym;
1503 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1504 }
1506 if ((kind & TYP) != 0) {
1507 sym = findMemberType(env, site, name, site.tsym);
1508 if (sym.exists()) return sym;
1509 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1510 }
1511 return bestSoFar;
1512 }
1514 /* ***************************************************************************
1515 * Access checking
1516 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1517 * an error message in the process
1518 ****************************************************************************/
1520 /** If `sym' is a bad symbol: report error and return errSymbol
1521 * else pass through unchanged,
1522 * additional arguments duplicate what has been used in trying to find the
1523 * symbol (--> flyweight pattern). This improves performance since we
1524 * expect misses to happen frequently.
1525 *
1526 * @param sym The symbol that was found, or a ResolveError.
1527 * @param pos The position to use for error reporting.
1528 * @param site The original type from where the selection took place.
1529 * @param name The symbol's name.
1530 * @param argtypes The invocation's value arguments,
1531 * if we looked for a method.
1532 * @param typeargtypes The invocation's type arguments,
1533 * if we looked for a method.
1534 */
1535 Symbol access(Symbol sym,
1536 DiagnosticPosition pos,
1537 Symbol location,
1538 Type site,
1539 Name name,
1540 boolean qualified,
1541 List<Type> argtypes,
1542 List<Type> typeargtypes) {
1543 if (sym.kind >= AMBIGUOUS) {
1544 ResolveError errSym = (ResolveError)sym;
1545 if (!site.isErroneous() &&
1546 !Type.isErroneous(argtypes) &&
1547 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
1548 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1549 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1550 }
1551 return sym;
1552 }
1554 /** Same as original access(), but without location.
1555 */
1556 Symbol access(Symbol sym,
1557 DiagnosticPosition pos,
1558 Type site,
1559 Name name,
1560 boolean qualified,
1561 List<Type> argtypes,
1562 List<Type> typeargtypes) {
1563 return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1564 }
1566 /** Same as original access(), but without type arguments and arguments.
1567 */
1568 Symbol access(Symbol sym,
1569 DiagnosticPosition pos,
1570 Symbol location,
1571 Type site,
1572 Name name,
1573 boolean qualified) {
1574 if (sym.kind >= AMBIGUOUS)
1575 return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
1576 else
1577 return sym;
1578 }
1580 /** Same as original access(), but without location, type arguments and arguments.
1581 */
1582 Symbol access(Symbol sym,
1583 DiagnosticPosition pos,
1584 Type site,
1585 Name name,
1586 boolean qualified) {
1587 return access(sym, pos, site.tsym, site, name, qualified);
1588 }
1590 /** Check that sym is not an abstract method.
1591 */
1592 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1593 if ((sym.flags() & ABSTRACT) != 0)
1594 log.error(pos, "abstract.cant.be.accessed.directly",
1595 kindName(sym), sym, sym.location());
1596 }
1598 /* ***************************************************************************
1599 * Debugging
1600 ****************************************************************************/
1602 /** print all scopes starting with scope s and proceeding outwards.
1603 * used for debugging.
1604 */
1605 public void printscopes(Scope s) {
1606 while (s != null) {
1607 if (s.owner != null)
1608 System.err.print(s.owner + ": ");
1609 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1610 if ((e.sym.flags() & ABSTRACT) != 0)
1611 System.err.print("abstract ");
1612 System.err.print(e.sym + " ");
1613 }
1614 System.err.println();
1615 s = s.next;
1616 }
1617 }
1619 void printscopes(Env<AttrContext> env) {
1620 while (env.outer != null) {
1621 System.err.println("------------------------------");
1622 printscopes(env.info.scope);
1623 env = env.outer;
1624 }
1625 }
1627 public void printscopes(Type t) {
1628 while (t.tag == CLASS) {
1629 printscopes(t.tsym.members());
1630 t = types.supertype(t);
1631 }
1632 }
1634 /* ***************************************************************************
1635 * Name resolution
1636 * Naming conventions are as for symbol lookup
1637 * Unlike the find... methods these methods will report access errors
1638 ****************************************************************************/
1640 /** Resolve an unqualified (non-method) identifier.
1641 * @param pos The position to use for error reporting.
1642 * @param env The environment current at the identifier use.
1643 * @param name The identifier's name.
1644 * @param kind The set of admissible symbol kinds for the identifier.
1645 */
1646 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1647 Name name, int kind) {
1648 return access(
1649 findIdent(env, name, kind),
1650 pos, env.enclClass.sym.type, name, false);
1651 }
1653 /** Resolve an unqualified method identifier.
1654 * @param pos The position to use for error reporting.
1655 * @param env The environment current at the method invocation.
1656 * @param name The identifier's name.
1657 * @param argtypes The types of the invocation's value arguments.
1658 * @param typeargtypes The types of the invocation's type arguments.
1659 */
1660 Symbol resolveMethod(DiagnosticPosition pos,
1661 Env<AttrContext> env,
1662 Name name,
1663 List<Type> argtypes,
1664 List<Type> typeargtypes) {
1665 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1666 try {
1667 currentResolutionContext = new MethodResolutionContext();
1668 Symbol sym = methodNotFound;
1669 List<MethodResolutionPhase> steps = methodResolutionSteps;
1670 while (steps.nonEmpty() &&
1671 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1672 sym.kind >= ERRONEOUS) {
1673 currentResolutionContext.step = steps.head;
1674 sym = findFun(env, name, argtypes, typeargtypes,
1675 steps.head.isBoxingRequired,
1676 env.info.varArgs = steps.head.isVarargsRequired);
1677 currentResolutionContext.resolutionCache.put(steps.head, sym);
1678 steps = steps.tail;
1679 }
1680 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1681 MethodResolutionPhase errPhase =
1682 currentResolutionContext.firstErroneousResolutionPhase();
1683 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1684 pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1685 env.info.varArgs = errPhase.isVarargsRequired;
1686 }
1687 return sym;
1688 }
1689 finally {
1690 currentResolutionContext = prevResolutionContext;
1691 }
1692 }
1694 /** Resolve a qualified method identifier
1695 * @param pos The position to use for error reporting.
1696 * @param env The environment current at the method invocation.
1697 * @param site The type of the qualifying expression, in which
1698 * identifier is searched.
1699 * @param name The identifier's name.
1700 * @param argtypes The types of the invocation's value arguments.
1701 * @param typeargtypes The types of the invocation's type arguments.
1702 */
1703 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1704 Type site, Name name, List<Type> argtypes,
1705 List<Type> typeargtypes) {
1706 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
1707 }
1708 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1709 Symbol location, Type site, Name name, List<Type> argtypes,
1710 List<Type> typeargtypes) {
1711 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
1712 }
1713 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
1714 DiagnosticPosition pos, Env<AttrContext> env,
1715 Symbol location, Type site, Name name, List<Type> argtypes,
1716 List<Type> typeargtypes) {
1717 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1718 try {
1719 currentResolutionContext = resolveContext;
1720 Symbol sym = methodNotFound;
1721 List<MethodResolutionPhase> steps = methodResolutionSteps;
1722 while (steps.nonEmpty() &&
1723 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1724 sym.kind >= ERRONEOUS) {
1725 currentResolutionContext.step = steps.head;
1726 sym = findMethod(env, site, name, argtypes, typeargtypes,
1727 steps.head.isBoxingRequired(),
1728 env.info.varArgs = steps.head.isVarargsRequired(), false);
1729 currentResolutionContext.resolutionCache.put(steps.head, sym);
1730 steps = steps.tail;
1731 }
1732 if (sym.kind >= AMBIGUOUS) {
1733 //if nothing is found return the 'first' error
1734 MethodResolutionPhase errPhase =
1735 currentResolutionContext.firstErroneousResolutionPhase();
1736 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1737 pos, location, site, name, true, argtypes, typeargtypes);
1738 env.info.varArgs = errPhase.isVarargsRequired;
1739 } else if (allowMethodHandles) {
1740 MethodSymbol msym = (MethodSymbol)sym;
1741 if (msym.isSignaturePolymorphic(types)) {
1742 env.info.varArgs = false;
1743 return findPolymorphicSignatureInstance(env, sym, argtypes);
1744 }
1745 }
1746 return sym;
1747 }
1748 finally {
1749 currentResolutionContext = prevResolutionContext;
1750 }
1751 }
1753 /** Find or create an implicit method of exactly the given type (after erasure).
1754 * Searches in a side table, not the main scope of the site.
1755 * This emulates the lookup process required by JSR 292 in JVM.
1756 * @param env Attribution environment
1757 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
1758 * @param argtypes The required argument types
1759 */
1760 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
1761 Symbol spMethod,
1762 List<Type> argtypes) {
1763 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
1764 (MethodSymbol)spMethod, argtypes);
1765 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
1766 if (types.isSameType(mtype, sym.type)) {
1767 return sym;
1768 }
1769 }
1771 // create the desired method
1772 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
1773 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
1774 polymorphicSignatureScope.enter(msym);
1775 return msym;
1776 }
1778 /** Resolve a qualified method identifier, throw a fatal error if not
1779 * found.
1780 * @param pos The position to use for error reporting.
1781 * @param env The environment current at the method invocation.
1782 * @param site The type of the qualifying expression, in which
1783 * identifier is searched.
1784 * @param name The identifier's name.
1785 * @param argtypes The types of the invocation's value arguments.
1786 * @param typeargtypes The types of the invocation's type arguments.
1787 */
1788 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
1789 Type site, Name name,
1790 List<Type> argtypes,
1791 List<Type> typeargtypes) {
1792 MethodResolutionContext resolveContext = new MethodResolutionContext();
1793 resolveContext.internalResolution = true;
1794 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
1795 site, name, argtypes, typeargtypes);
1796 if (sym.kind == MTH) return (MethodSymbol)sym;
1797 else throw new FatalError(
1798 diags.fragment("fatal.err.cant.locate.meth",
1799 name));
1800 }
1802 /** Resolve constructor.
1803 * @param pos The position to use for error reporting.
1804 * @param env The environment current at the constructor invocation.
1805 * @param site The type of class for which a constructor is searched.
1806 * @param argtypes The types of the constructor invocation's value
1807 * arguments.
1808 * @param typeargtypes The types of the constructor invocation's type
1809 * arguments.
1810 */
1811 Symbol resolveConstructor(DiagnosticPosition pos,
1812 Env<AttrContext> env,
1813 Type site,
1814 List<Type> argtypes,
1815 List<Type> typeargtypes) {
1816 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
1817 }
1818 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
1819 DiagnosticPosition pos,
1820 Env<AttrContext> env,
1821 Type site,
1822 List<Type> argtypes,
1823 List<Type> typeargtypes) {
1824 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1825 try {
1826 currentResolutionContext = resolveContext;
1827 Symbol sym = methodNotFound;
1828 List<MethodResolutionPhase> steps = methodResolutionSteps;
1829 while (steps.nonEmpty() &&
1830 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1831 sym.kind >= ERRONEOUS) {
1832 currentResolutionContext.step = steps.head;
1833 sym = findConstructor(pos, env, site, argtypes, typeargtypes,
1834 steps.head.isBoxingRequired(),
1835 env.info.varArgs = steps.head.isVarargsRequired());
1836 currentResolutionContext.resolutionCache.put(steps.head, sym);
1837 steps = steps.tail;
1838 }
1839 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1840 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
1841 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
1842 pos, site, names.init, true, argtypes, typeargtypes);
1843 env.info.varArgs = errPhase.isVarargsRequired();
1844 }
1845 return sym;
1846 }
1847 finally {
1848 currentResolutionContext = prevResolutionContext;
1849 }
1850 }
1852 /** Resolve constructor using diamond inference.
1853 * @param pos The position to use for error reporting.
1854 * @param env The environment current at the constructor invocation.
1855 * @param site The type of class for which a constructor is searched.
1856 * The scope of this class has been touched in attribution.
1857 * @param argtypes The types of the constructor invocation's value
1858 * arguments.
1859 * @param typeargtypes The types of the constructor invocation's type
1860 * arguments.
1861 */
1862 Symbol resolveDiamond(DiagnosticPosition pos,
1863 Env<AttrContext> env,
1864 Type site,
1865 List<Type> argtypes,
1866 List<Type> typeargtypes) {
1867 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1868 try {
1869 currentResolutionContext = new MethodResolutionContext();
1870 Symbol sym = methodNotFound;
1871 List<MethodResolutionPhase> steps = methodResolutionSteps;
1872 while (steps.nonEmpty() &&
1873 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1874 sym.kind >= ERRONEOUS) {
1875 currentResolutionContext.step = steps.head;
1876 sym = findDiamond(env, site, argtypes, typeargtypes,
1877 steps.head.isBoxingRequired(),
1878 env.info.varArgs = steps.head.isVarargsRequired());
1879 currentResolutionContext.resolutionCache.put(steps.head, sym);
1880 steps = steps.tail;
1881 }
1882 if (sym.kind >= AMBIGUOUS) {
1883 final JCDiagnostic details = sym.kind == WRONG_MTH ?
1884 currentResolutionContext.candidates.head.details :
1885 null;
1886 Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
1887 @Override
1888 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
1889 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
1890 String key = details == null ?
1891 "cant.apply.diamond" :
1892 "cant.apply.diamond.1";
1893 return diags.create(dkind, log.currentSource(), pos, key,
1894 diags.fragment("diamond", site.tsym), details);
1895 }
1896 };
1897 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
1898 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
1899 env.info.varArgs = errPhase.isVarargsRequired();
1900 }
1901 return sym;
1902 }
1903 finally {
1904 currentResolutionContext = prevResolutionContext;
1905 }
1906 }
1908 /** This method scans all the constructor symbol in a given class scope -
1909 * assuming that the original scope contains a constructor of the kind:
1910 * Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1911 * a method check is executed against the modified constructor type:
1912 * <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1913 * inference. The inferred return type of the synthetic constructor IS
1914 * the inferred type for the diamond operator.
1915 */
1916 private Symbol findDiamond(Env<AttrContext> env,
1917 Type site,
1918 List<Type> argtypes,
1919 List<Type> typeargtypes,
1920 boolean allowBoxing,
1921 boolean useVarargs) {
1922 Symbol bestSoFar = methodNotFound;
1923 for (Scope.Entry e = site.tsym.members().lookup(names.init);
1924 e.scope != null;
1925 e = e.next()) {
1926 //- System.out.println(" e " + e.sym);
1927 if (e.sym.kind == MTH &&
1928 (e.sym.flags_field & SYNTHETIC) == 0) {
1929 List<Type> oldParams = e.sym.type.tag == FORALL ?
1930 ((ForAll)e.sym.type).tvars :
1931 List.<Type>nil();
1932 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
1933 types.createMethodTypeWithReturn(e.sym.type.asMethodType(), site));
1934 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
1935 new MethodSymbol(e.sym.flags(), names.init, constrType, site.tsym),
1936 bestSoFar,
1937 allowBoxing,
1938 useVarargs,
1939 false);
1940 }
1941 }
1942 return bestSoFar;
1943 }
1945 /** Resolve constructor.
1946 * @param pos The position to use for error reporting.
1947 * @param env The environment current at the constructor invocation.
1948 * @param site The type of class for which a constructor is searched.
1949 * @param argtypes The types of the constructor invocation's value
1950 * arguments.
1951 * @param typeargtypes The types of the constructor invocation's type
1952 * arguments.
1953 * @param allowBoxing Allow boxing and varargs conversions.
1954 * @param useVarargs Box trailing arguments into an array for varargs.
1955 */
1956 Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1957 Type site, List<Type> argtypes,
1958 List<Type> typeargtypes,
1959 boolean allowBoxing,
1960 boolean useVarargs) {
1961 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1962 try {
1963 currentResolutionContext = new MethodResolutionContext();
1964 return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
1965 }
1966 finally {
1967 currentResolutionContext = prevResolutionContext;
1968 }
1969 }
1971 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1972 Type site, List<Type> argtypes,
1973 List<Type> typeargtypes,
1974 boolean allowBoxing,
1975 boolean useVarargs) {
1976 Symbol sym = findMethod(env, site,
1977 names.init, argtypes,
1978 typeargtypes, allowBoxing,
1979 useVarargs, false);
1980 chk.checkDeprecated(pos, env.info.scope.owner, sym);
1981 return sym;
1982 }
1984 /** Resolve a constructor, throw a fatal error if not found.
1985 * @param pos The position to use for error reporting.
1986 * @param env The environment current at the method invocation.
1987 * @param site The type to be constructed.
1988 * @param argtypes The types of the invocation's value arguments.
1989 * @param typeargtypes The types of the invocation's type arguments.
1990 */
1991 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1992 Type site,
1993 List<Type> argtypes,
1994 List<Type> typeargtypes) {
1995 MethodResolutionContext resolveContext = new MethodResolutionContext();
1996 resolveContext.internalResolution = true;
1997 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
1998 if (sym.kind == MTH) return (MethodSymbol)sym;
1999 else throw new FatalError(
2000 diags.fragment("fatal.err.cant.locate.ctor", site));
2001 }
2003 /** Resolve operator.
2004 * @param pos The position to use for error reporting.
2005 * @param optag The tag of the operation tree.
2006 * @param env The environment current at the operation.
2007 * @param argtypes The types of the operands.
2008 */
2009 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2010 Env<AttrContext> env, List<Type> argtypes) {
2011 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2012 try {
2013 currentResolutionContext = new MethodResolutionContext();
2014 Name name = treeinfo.operatorName(optag);
2015 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2016 null, false, false, true);
2017 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2018 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2019 null, true, false, true);
2020 return access(sym, pos, env.enclClass.sym.type, name,
2021 false, argtypes, null);
2022 }
2023 finally {
2024 currentResolutionContext = prevResolutionContext;
2025 }
2026 }
2028 /** Resolve operator.
2029 * @param pos The position to use for error reporting.
2030 * @param optag The tag of the operation tree.
2031 * @param env The environment current at the operation.
2032 * @param arg The type of the operand.
2033 */
2034 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2035 return resolveOperator(pos, optag, env, List.of(arg));
2036 }
2038 /** Resolve binary operator.
2039 * @param pos The position to use for error reporting.
2040 * @param optag The tag of the operation tree.
2041 * @param env The environment current at the operation.
2042 * @param left The types of the left operand.
2043 * @param right The types of the right operand.
2044 */
2045 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2046 JCTree.Tag optag,
2047 Env<AttrContext> env,
2048 Type left,
2049 Type right) {
2050 return resolveOperator(pos, optag, env, List.of(left, right));
2051 }
2053 /**
2054 * Resolve `c.name' where name == this or name == super.
2055 * @param pos The position to use for error reporting.
2056 * @param env The environment current at the expression.
2057 * @param c The qualifier.
2058 * @param name The identifier's name.
2059 */
2060 Symbol resolveSelf(DiagnosticPosition pos,
2061 Env<AttrContext> env,
2062 TypeSymbol c,
2063 Name name) {
2064 Env<AttrContext> env1 = env;
2065 boolean staticOnly = false;
2066 while (env1.outer != null) {
2067 if (isStatic(env1)) staticOnly = true;
2068 if (env1.enclClass.sym == c) {
2069 Symbol sym = env1.info.scope.lookup(name).sym;
2070 if (sym != null) {
2071 if (staticOnly) sym = new StaticError(sym);
2072 return access(sym, pos, env.enclClass.sym.type,
2073 name, true);
2074 }
2075 }
2076 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2077 env1 = env1.outer;
2078 }
2079 log.error(pos, "not.encl.class", c);
2080 return syms.errSymbol;
2081 }
2083 /**
2084 * Resolve `c.this' for an enclosing class c that contains the
2085 * named member.
2086 * @param pos The position to use for error reporting.
2087 * @param env The environment current at the expression.
2088 * @param member The member that must be contained in the result.
2089 */
2090 Symbol resolveSelfContaining(DiagnosticPosition pos,
2091 Env<AttrContext> env,
2092 Symbol member,
2093 boolean isSuperCall) {
2094 Name name = names._this;
2095 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2096 boolean staticOnly = false;
2097 if (env1 != null) {
2098 while (env1 != null && env1.outer != null) {
2099 if (isStatic(env1)) staticOnly = true;
2100 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2101 Symbol sym = env1.info.scope.lookup(name).sym;
2102 if (sym != null) {
2103 if (staticOnly) sym = new StaticError(sym);
2104 return access(sym, pos, env.enclClass.sym.type,
2105 name, true);
2106 }
2107 }
2108 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2109 staticOnly = true;
2110 env1 = env1.outer;
2111 }
2112 }
2113 log.error(pos, "encl.class.required", member);
2114 return syms.errSymbol;
2115 }
2117 /**
2118 * Resolve an appropriate implicit this instance for t's container.
2119 * JLS 8.8.5.1 and 15.9.2
2120 */
2121 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2122 return resolveImplicitThis(pos, env, t, false);
2123 }
2125 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2126 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2127 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2128 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2129 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2130 log.error(pos, "cant.ref.before.ctor.called", "this");
2131 return thisType;
2132 }
2134 /* ***************************************************************************
2135 * ResolveError classes, indicating error situations when accessing symbols
2136 ****************************************************************************/
2138 //used by TransTypes when checking target type of synthetic cast
2139 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2140 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2141 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2142 }
2143 //where
2144 private void logResolveError(ResolveError error,
2145 DiagnosticPosition pos,
2146 Symbol location,
2147 Type site,
2148 Name name,
2149 List<Type> argtypes,
2150 List<Type> typeargtypes) {
2151 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2152 pos, location, site, name, argtypes, typeargtypes);
2153 if (d != null) {
2154 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2155 log.report(d);
2156 }
2157 }
2159 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2161 public Object methodArguments(List<Type> argtypes) {
2162 return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
2163 }
2165 /**
2166 * Root class for resolution errors. Subclass of ResolveError
2167 * represent a different kinds of resolution error - as such they must
2168 * specify how they map into concrete compiler diagnostics.
2169 */
2170 private abstract class ResolveError extends Symbol {
2172 /** The name of the kind of error, for debugging only. */
2173 final String debugName;
2175 ResolveError(int kind, String debugName) {
2176 super(kind, 0, null, null, null);
2177 this.debugName = debugName;
2178 }
2180 @Override
2181 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2182 throw new AssertionError();
2183 }
2185 @Override
2186 public String toString() {
2187 return debugName;
2188 }
2190 @Override
2191 public boolean exists() {
2192 return false;
2193 }
2195 /**
2196 * Create an external representation for this erroneous symbol to be
2197 * used during attribution - by default this returns the symbol of a
2198 * brand new error type which stores the original type found
2199 * during resolution.
2200 *
2201 * @param name the name used during resolution
2202 * @param location the location from which the symbol is accessed
2203 */
2204 protected Symbol access(Name name, TypeSymbol location) {
2205 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2206 }
2208 /**
2209 * Create a diagnostic representing this resolution error.
2210 *
2211 * @param dkind The kind of the diagnostic to be created (e.g error).
2212 * @param pos The position to be used for error reporting.
2213 * @param site The original type from where the selection took place.
2214 * @param name The name of the symbol to be resolved.
2215 * @param argtypes The invocation's value arguments,
2216 * if we looked for a method.
2217 * @param typeargtypes The invocation's type arguments,
2218 * if we looked for a method.
2219 */
2220 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2221 DiagnosticPosition pos,
2222 Symbol location,
2223 Type site,
2224 Name name,
2225 List<Type> argtypes,
2226 List<Type> typeargtypes);
2228 /**
2229 * A name designates an operator if it consists
2230 * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
2231 */
2232 boolean isOperator(Name name) {
2233 int i = 0;
2234 while (i < name.getByteLength() &&
2235 "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
2236 return i > 0 && i == name.getByteLength();
2237 }
2238 }
2240 /**
2241 * This class is the root class of all resolution errors caused by
2242 * an invalid symbol being found during resolution.
2243 */
2244 abstract class InvalidSymbolError extends ResolveError {
2246 /** The invalid symbol found during resolution */
2247 Symbol sym;
2249 InvalidSymbolError(int kind, Symbol sym, String debugName) {
2250 super(kind, debugName);
2251 this.sym = sym;
2252 }
2254 @Override
2255 public boolean exists() {
2256 return true;
2257 }
2259 @Override
2260 public String toString() {
2261 return super.toString() + " wrongSym=" + sym;
2262 }
2264 @Override
2265 public Symbol access(Name name, TypeSymbol location) {
2266 if (sym.kind >= AMBIGUOUS)
2267 return ((ResolveError)sym).access(name, location);
2268 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
2269 return types.createErrorType(name, location, sym.type).tsym;
2270 else
2271 return sym;
2272 }
2273 }
2275 /**
2276 * InvalidSymbolError error class indicating that a symbol matching a
2277 * given name does not exists in a given site.
2278 */
2279 class SymbolNotFoundError extends ResolveError {
2281 SymbolNotFoundError(int kind) {
2282 super(kind, "symbol not found error");
2283 }
2285 @Override
2286 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2287 DiagnosticPosition pos,
2288 Symbol location,
2289 Type site,
2290 Name name,
2291 List<Type> argtypes,
2292 List<Type> typeargtypes) {
2293 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
2294 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
2295 if (name == names.error)
2296 return null;
2298 if (isOperator(name)) {
2299 boolean isUnaryOp = argtypes.size() == 1;
2300 String key = argtypes.size() == 1 ?
2301 "operator.cant.be.applied" :
2302 "operator.cant.be.applied.1";
2303 Type first = argtypes.head;
2304 Type second = !isUnaryOp ? argtypes.tail.head : null;
2305 return diags.create(dkind, log.currentSource(), pos,
2306 key, name, first, second);
2307 }
2308 boolean hasLocation = false;
2309 if (location == null) {
2310 location = site.tsym;
2311 }
2312 if (!location.name.isEmpty()) {
2313 if (location.kind == PCK && !site.tsym.exists()) {
2314 return diags.create(dkind, log.currentSource(), pos,
2315 "doesnt.exist", location);
2316 }
2317 hasLocation = !location.name.equals(names._this) &&
2318 !location.name.equals(names._super);
2319 }
2320 boolean isConstructor = kind == ABSENT_MTH &&
2321 name == names.table.names.init;
2322 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
2323 Name idname = isConstructor ? site.tsym.name : name;
2324 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
2325 if (hasLocation) {
2326 return diags.create(dkind, log.currentSource(), pos,
2327 errKey, kindname, idname, //symbol kindname, name
2328 typeargtypes, argtypes, //type parameters and arguments (if any)
2329 getLocationDiag(location, site)); //location kindname, type
2330 }
2331 else {
2332 return diags.create(dkind, log.currentSource(), pos,
2333 errKey, kindname, idname, //symbol kindname, name
2334 typeargtypes, argtypes); //type parameters and arguments (if any)
2335 }
2336 }
2337 //where
2338 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
2339 String key = "cant.resolve";
2340 String suffix = hasLocation ? ".location" : "";
2341 switch (kindname) {
2342 case METHOD:
2343 case CONSTRUCTOR: {
2344 suffix += ".args";
2345 suffix += hasTypeArgs ? ".params" : "";
2346 }
2347 }
2348 return key + suffix;
2349 }
2350 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
2351 if (location.kind == VAR) {
2352 return diags.fragment("location.1",
2353 kindName(location),
2354 location,
2355 location.type);
2356 } else {
2357 return diags.fragment("location",
2358 typeKindName(site),
2359 site,
2360 null);
2361 }
2362 }
2363 }
2365 /**
2366 * InvalidSymbolError error class indicating that a given symbol
2367 * (either a method, a constructor or an operand) is not applicable
2368 * given an actual arguments/type argument list.
2369 */
2370 class InapplicableSymbolError extends ResolveError {
2372 InapplicableSymbolError() {
2373 super(WRONG_MTH, "inapplicable symbol error");
2374 }
2376 protected InapplicableSymbolError(int kind, String debugName) {
2377 super(kind, debugName);
2378 }
2380 @Override
2381 public String toString() {
2382 return super.toString();
2383 }
2385 @Override
2386 public boolean exists() {
2387 return true;
2388 }
2390 @Override
2391 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2392 DiagnosticPosition pos,
2393 Symbol location,
2394 Type site,
2395 Name name,
2396 List<Type> argtypes,
2397 List<Type> typeargtypes) {
2398 if (name == names.error)
2399 return null;
2401 if (isOperator(name)) {
2402 boolean isUnaryOp = argtypes.size() == 1;
2403 String key = argtypes.size() == 1 ?
2404 "operator.cant.be.applied" :
2405 "operator.cant.be.applied.1";
2406 Type first = argtypes.head;
2407 Type second = !isUnaryOp ? argtypes.tail.head : null;
2408 return diags.create(dkind, log.currentSource(), pos,
2409 key, name, first, second);
2410 }
2411 else {
2412 Candidate c = errCandidate();
2413 Symbol ws = c.sym.asMemberOf(site, types);
2414 return diags.create(dkind, log.currentSource(), pos,
2415 "cant.apply.symbol" + (c.details != null ? ".1" : ""),
2416 kindName(ws),
2417 ws.name == names.init ? ws.owner.name : ws.name,
2418 methodArguments(ws.type.getParameterTypes()),
2419 methodArguments(argtypes),
2420 kindName(ws.owner),
2421 ws.owner.type,
2422 c.details);
2423 }
2424 }
2426 @Override
2427 public Symbol access(Name name, TypeSymbol location) {
2428 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2429 }
2431 protected boolean shouldReport(Candidate c) {
2432 return !c.isApplicable() &&
2433 (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
2434 (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
2435 }
2437 private Candidate errCandidate() {
2438 for (Candidate c : currentResolutionContext.candidates) {
2439 if (shouldReport(c)) {
2440 return c;
2441 }
2442 }
2443 Assert.error();
2444 return null;
2445 }
2446 }
2448 /**
2449 * ResolveError error class indicating that a set of symbols
2450 * (either methods, constructors or operands) is not applicable
2451 * given an actual arguments/type argument list.
2452 */
2453 class InapplicableSymbolsError extends InapplicableSymbolError {
2455 InapplicableSymbolsError() {
2456 super(WRONG_MTHS, "inapplicable symbols");
2457 }
2459 @Override
2460 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2461 DiagnosticPosition pos,
2462 Symbol location,
2463 Type site,
2464 Name name,
2465 List<Type> argtypes,
2466 List<Type> typeargtypes) {
2467 if (currentResolutionContext.candidates.nonEmpty()) {
2468 JCDiagnostic err = diags.create(dkind,
2469 log.currentSource(),
2470 pos,
2471 "cant.apply.symbols",
2472 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2473 getName(),
2474 argtypes);
2475 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2476 } else {
2477 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2478 location, site, name, argtypes, typeargtypes);
2479 }
2480 }
2482 //where
2483 List<JCDiagnostic> candidateDetails(Type site) {
2484 List<JCDiagnostic> details = List.nil();
2485 for (Candidate c : currentResolutionContext.candidates) {
2486 if (!shouldReport(c)) continue;
2487 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
2488 Kinds.kindName(c.sym),
2489 c.sym.location(site, types),
2490 c.sym.asMemberOf(site, types),
2491 c.details);
2492 details = details.prepend(detailDiag);
2493 }
2494 return details.reverse();
2495 }
2497 private Name getName() {
2498 Symbol sym = currentResolutionContext.candidates.head.sym;
2499 return sym.name == names.init ?
2500 sym.owner.name :
2501 sym.name;
2502 }
2503 }
2505 /**
2506 * An InvalidSymbolError error class indicating that a symbol is not
2507 * accessible from a given site
2508 */
2509 class AccessError extends InvalidSymbolError {
2511 private Env<AttrContext> env;
2512 private Type site;
2514 AccessError(Symbol sym) {
2515 this(null, null, sym);
2516 }
2518 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2519 super(HIDDEN, sym, "access error");
2520 this.env = env;
2521 this.site = site;
2522 if (debugResolve)
2523 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2524 }
2526 @Override
2527 public boolean exists() {
2528 return false;
2529 }
2531 @Override
2532 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2533 DiagnosticPosition pos,
2534 Symbol location,
2535 Type site,
2536 Name name,
2537 List<Type> argtypes,
2538 List<Type> typeargtypes) {
2539 if (sym.owner.type.tag == ERROR)
2540 return null;
2542 if (sym.name == names.init && sym.owner != site.tsym) {
2543 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2544 pos, location, site, name, argtypes, typeargtypes);
2545 }
2546 else if ((sym.flags() & PUBLIC) != 0
2547 || (env != null && this.site != null
2548 && !isAccessible(env, this.site))) {
2549 return diags.create(dkind, log.currentSource(),
2550 pos, "not.def.access.class.intf.cant.access",
2551 sym, sym.location());
2552 }
2553 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2554 return diags.create(dkind, log.currentSource(),
2555 pos, "report.access", sym,
2556 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2557 sym.location());
2558 }
2559 else {
2560 return diags.create(dkind, log.currentSource(),
2561 pos, "not.def.public.cant.access", sym, sym.location());
2562 }
2563 }
2564 }
2566 /**
2567 * InvalidSymbolError error class indicating that an instance member
2568 * has erroneously been accessed from a static context.
2569 */
2570 class StaticError extends InvalidSymbolError {
2572 StaticError(Symbol sym) {
2573 super(STATICERR, sym, "static error");
2574 }
2576 @Override
2577 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2578 DiagnosticPosition pos,
2579 Symbol location,
2580 Type site,
2581 Name name,
2582 List<Type> argtypes,
2583 List<Type> typeargtypes) {
2584 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2585 ? types.erasure(sym.type).tsym
2586 : sym);
2587 return diags.create(dkind, log.currentSource(), pos,
2588 "non-static.cant.be.ref", kindName(sym), errSym);
2589 }
2590 }
2592 /**
2593 * InvalidSymbolError error class indicating that a pair of symbols
2594 * (either methods, constructors or operands) are ambiguous
2595 * given an actual arguments/type argument list.
2596 */
2597 class AmbiguityError extends InvalidSymbolError {
2599 /** The other maximally specific symbol */
2600 Symbol sym2;
2602 AmbiguityError(Symbol sym1, Symbol sym2) {
2603 super(AMBIGUOUS, sym1, "ambiguity error");
2604 this.sym2 = sym2;
2605 }
2607 @Override
2608 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2609 DiagnosticPosition pos,
2610 Symbol location,
2611 Type site,
2612 Name name,
2613 List<Type> argtypes,
2614 List<Type> typeargtypes) {
2615 AmbiguityError pair = this;
2616 while (true) {
2617 if (pair.sym.kind == AMBIGUOUS)
2618 pair = (AmbiguityError)pair.sym;
2619 else if (pair.sym2.kind == AMBIGUOUS)
2620 pair = (AmbiguityError)pair.sym2;
2621 else break;
2622 }
2623 Name sname = pair.sym.name;
2624 if (sname == names.init) sname = pair.sym.owner.name;
2625 return diags.create(dkind, log.currentSource(),
2626 pos, "ref.ambiguous", sname,
2627 kindName(pair.sym),
2628 pair.sym,
2629 pair.sym.location(site, types),
2630 kindName(pair.sym2),
2631 pair.sym2,
2632 pair.sym2.location(site, types));
2633 }
2634 }
2636 enum MethodResolutionPhase {
2637 BASIC(false, false),
2638 BOX(true, false),
2639 VARARITY(true, true);
2641 boolean isBoxingRequired;
2642 boolean isVarargsRequired;
2644 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2645 this.isBoxingRequired = isBoxingRequired;
2646 this.isVarargsRequired = isVarargsRequired;
2647 }
2649 public boolean isBoxingRequired() {
2650 return isBoxingRequired;
2651 }
2653 public boolean isVarargsRequired() {
2654 return isVarargsRequired;
2655 }
2657 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2658 return (varargsEnabled || !isVarargsRequired) &&
2659 (boxingEnabled || !isBoxingRequired);
2660 }
2661 }
2663 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2665 /**
2666 * A resolution context is used to keep track of intermediate results of
2667 * overload resolution, such as list of method that are not applicable
2668 * (used to generate more precise diagnostics) and so on. Resolution contexts
2669 * can be nested - this means that when each overload resolution routine should
2670 * work within the resolution context it created.
2671 */
2672 class MethodResolutionContext {
2674 private List<Candidate> candidates = List.nil();
2676 private Map<MethodResolutionPhase, Symbol> resolutionCache =
2677 new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
2679 private MethodResolutionPhase step = null;
2681 private boolean internalResolution = false;
2683 private MethodResolutionPhase firstErroneousResolutionPhase() {
2684 MethodResolutionPhase bestSoFar = BASIC;
2685 Symbol sym = methodNotFound;
2686 List<MethodResolutionPhase> steps = methodResolutionSteps;
2687 while (steps.nonEmpty() &&
2688 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2689 sym.kind >= WRONG_MTHS) {
2690 sym = resolutionCache.get(steps.head);
2691 bestSoFar = steps.head;
2692 steps = steps.tail;
2693 }
2694 return bestSoFar;
2695 }
2697 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
2698 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
2699 if (!candidates.contains(c))
2700 candidates = candidates.append(c);
2701 }
2703 void addApplicableCandidate(Symbol sym, Type mtype) {
2704 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
2705 candidates = candidates.append(c);
2706 }
2708 /**
2709 * This class represents an overload resolution candidate. There are two
2710 * kinds of candidates: applicable methods and inapplicable methods;
2711 * applicable methods have a pointer to the instantiated method type,
2712 * while inapplicable candidates contain further details about the
2713 * reason why the method has been considered inapplicable.
2714 */
2715 class Candidate {
2717 final MethodResolutionPhase step;
2718 final Symbol sym;
2719 final JCDiagnostic details;
2720 final Type mtype;
2722 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
2723 this.step = step;
2724 this.sym = sym;
2725 this.details = details;
2726 this.mtype = mtype;
2727 }
2729 @Override
2730 public boolean equals(Object o) {
2731 if (o instanceof Candidate) {
2732 Symbol s1 = this.sym;
2733 Symbol s2 = ((Candidate)o).sym;
2734 if ((s1 != s2 &&
2735 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2736 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2737 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2738 return true;
2739 }
2740 return false;
2741 }
2743 boolean isApplicable() {
2744 return mtype != null;
2745 }
2746 }
2747 }
2749 MethodResolutionContext currentResolutionContext = null;
2750 }