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