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