Mon, 06 Dec 2010 11:51:02 +0000
5088429: varargs overloading problem
Summary: compiler implementation for overload resolution w/ varargs method does not match 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 Type elt = types.elemtype(varargsFormal);
474 while (argtypes.nonEmpty()) {
475 if (!types.isConvertible(argtypes.head, elt, warn))
476 throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
477 argtypes.head,
478 elt);
479 argtypes = argtypes.tail;
480 }
481 }
482 return;
483 }
484 // where
485 public static class InapplicableMethodException extends RuntimeException {
486 private static final long serialVersionUID = 0;
488 JCDiagnostic diagnostic;
489 JCDiagnostic.Factory diags;
491 InapplicableMethodException(JCDiagnostic.Factory diags) {
492 this.diagnostic = null;
493 this.diags = diags;
494 }
495 InapplicableMethodException setMessage(String key) {
496 this.diagnostic = key != null ? diags.fragment(key) : null;
497 return this;
498 }
499 InapplicableMethodException setMessage(String key, Object... args) {
500 this.diagnostic = key != null ? diags.fragment(key, args) : null;
501 return this;
502 }
504 public JCDiagnostic getDiagnostic() {
505 return diagnostic;
506 }
507 }
508 private final InapplicableMethodException inapplicableMethodException;
510 /* ***************************************************************************
511 * Symbol lookup
512 * the following naming conventions for arguments are used
513 *
514 * env is the environment where the symbol was mentioned
515 * site is the type of which the symbol is a member
516 * name is the symbol's name
517 * if no arguments are given
518 * argtypes are the value arguments, if we search for a method
519 *
520 * If no symbol was found, a ResolveError detailing the problem is returned.
521 ****************************************************************************/
523 /** Find field. Synthetic fields are always skipped.
524 * @param env The current environment.
525 * @param site The original type from where the selection takes place.
526 * @param name The name of the field.
527 * @param c The class to search for the field. This is always
528 * a superclass or implemented interface of site's class.
529 */
530 Symbol findField(Env<AttrContext> env,
531 Type site,
532 Name name,
533 TypeSymbol c) {
534 while (c.type.tag == TYPEVAR)
535 c = c.type.getUpperBound().tsym;
536 Symbol bestSoFar = varNotFound;
537 Symbol sym;
538 Scope.Entry e = c.members().lookup(name);
539 while (e.scope != null) {
540 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
541 return isAccessible(env, site, e.sym)
542 ? e.sym : new AccessError(env, site, e.sym);
543 }
544 e = e.next();
545 }
546 Type st = types.supertype(c.type);
547 if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
548 sym = findField(env, site, name, st.tsym);
549 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
550 }
551 for (List<Type> l = types.interfaces(c.type);
552 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
553 l = l.tail) {
554 sym = findField(env, site, name, l.head.tsym);
555 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
556 sym.owner != bestSoFar.owner)
557 bestSoFar = new AmbiguityError(bestSoFar, sym);
558 else if (sym.kind < bestSoFar.kind)
559 bestSoFar = sym;
560 }
561 return bestSoFar;
562 }
564 /** Resolve a field identifier, throw a fatal error if not found.
565 * @param pos The position to use for error reporting.
566 * @param env The environment current at the method invocation.
567 * @param site The type of the qualifying expression, in which
568 * identifier is searched.
569 * @param name The identifier's name.
570 */
571 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
572 Type site, Name name) {
573 Symbol sym = findField(env, site, name, site.tsym);
574 if (sym.kind == VAR) return (VarSymbol)sym;
575 else throw new FatalError(
576 diags.fragment("fatal.err.cant.locate.field",
577 name));
578 }
580 /** Find unqualified variable or field with given name.
581 * Synthetic fields always skipped.
582 * @param env The current environment.
583 * @param name The name of the variable or field.
584 */
585 Symbol findVar(Env<AttrContext> env, Name name) {
586 Symbol bestSoFar = varNotFound;
587 Symbol sym;
588 Env<AttrContext> env1 = env;
589 boolean staticOnly = false;
590 while (env1.outer != null) {
591 if (isStatic(env1)) staticOnly = true;
592 Scope.Entry e = env1.info.scope.lookup(name);
593 while (e.scope != null &&
594 (e.sym.kind != VAR ||
595 (e.sym.flags_field & SYNTHETIC) != 0))
596 e = e.next();
597 sym = (e.scope != null)
598 ? e.sym
599 : findField(
600 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
601 if (sym.exists()) {
602 if (staticOnly &&
603 sym.kind == VAR &&
604 sym.owner.kind == TYP &&
605 (sym.flags() & STATIC) == 0)
606 return new StaticError(sym);
607 else
608 return sym;
609 } else if (sym.kind < bestSoFar.kind) {
610 bestSoFar = sym;
611 }
613 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
614 env1 = env1.outer;
615 }
617 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
618 if (sym.exists())
619 return sym;
620 if (bestSoFar.exists())
621 return bestSoFar;
623 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
624 for (; e.scope != null; e = e.next()) {
625 sym = e.sym;
626 Type origin = e.getOrigin().owner.type;
627 if (sym.kind == VAR) {
628 if (e.sym.owner.type != origin)
629 sym = sym.clone(e.getOrigin().owner);
630 return isAccessible(env, origin, sym)
631 ? sym : new AccessError(env, origin, sym);
632 }
633 }
635 Symbol origin = null;
636 e = env.toplevel.starImportScope.lookup(name);
637 for (; e.scope != null; e = e.next()) {
638 sym = e.sym;
639 if (sym.kind != VAR)
640 continue;
641 // invariant: sym.kind == VAR
642 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
643 return new AmbiguityError(bestSoFar, sym);
644 else if (bestSoFar.kind >= VAR) {
645 origin = e.getOrigin().owner;
646 bestSoFar = isAccessible(env, origin.type, sym)
647 ? sym : new AccessError(env, origin.type, sym);
648 }
649 }
650 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
651 return bestSoFar.clone(origin);
652 else
653 return bestSoFar;
654 }
656 Warner noteWarner = new Warner();
658 /** Select the best method for a call site among two choices.
659 * @param env The current environment.
660 * @param site The original type from where the
661 * selection takes place.
662 * @param argtypes The invocation's value arguments,
663 * @param typeargtypes The invocation's type arguments,
664 * @param sym Proposed new best match.
665 * @param bestSoFar Previously found best match.
666 * @param allowBoxing Allow boxing conversions of arguments.
667 * @param useVarargs Box trailing arguments into an array for varargs.
668 */
669 @SuppressWarnings("fallthrough")
670 Symbol selectBest(Env<AttrContext> env,
671 Type site,
672 List<Type> argtypes,
673 List<Type> typeargtypes,
674 Symbol sym,
675 Symbol bestSoFar,
676 boolean allowBoxing,
677 boolean useVarargs,
678 boolean operator) {
679 if (sym.kind == ERR) return bestSoFar;
680 if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
681 assert sym.kind < AMBIGUOUS;
682 try {
683 rawInstantiate(env, site, sym, argtypes, typeargtypes,
684 allowBoxing, useVarargs, Warner.noWarnings);
685 } catch (InapplicableMethodException ex) {
686 switch (bestSoFar.kind) {
687 case ABSENT_MTH:
688 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
689 case WRONG_MTH:
690 wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
691 case WRONG_MTHS:
692 return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
693 default:
694 return bestSoFar;
695 }
696 }
697 if (!isAccessible(env, site, sym)) {
698 return (bestSoFar.kind == ABSENT_MTH)
699 ? new AccessError(env, site, sym)
700 : bestSoFar;
701 }
702 return (bestSoFar.kind > AMBIGUOUS)
703 ? sym
704 : mostSpecific(sym, bestSoFar, env, site,
705 allowBoxing && operator, useVarargs);
706 }
708 /* Return the most specific of the two methods for a call,
709 * given that both are accessible and applicable.
710 * @param m1 A new candidate for most specific.
711 * @param m2 The previous most specific candidate.
712 * @param env The current environment.
713 * @param site The original type from where the selection
714 * takes place.
715 * @param allowBoxing Allow boxing conversions of arguments.
716 * @param useVarargs Box trailing arguments into an array for varargs.
717 */
718 Symbol mostSpecific(Symbol m1,
719 Symbol m2,
720 Env<AttrContext> env,
721 final Type site,
722 boolean allowBoxing,
723 boolean useVarargs) {
724 switch (m2.kind) {
725 case MTH:
726 if (m1 == m2) return m1;
727 boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
728 boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
729 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
730 Type mt1 = types.memberType(site, m1);
731 Type mt2 = types.memberType(site, m2);
732 if (!types.overrideEquivalent(mt1, mt2))
733 return new AmbiguityError(m1, m2);
734 // same signature; select (a) the non-bridge method, or
735 // (b) the one that overrides the other, or (c) the concrete
736 // one, or (d) merge both abstract signatures
737 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
738 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
739 }
740 // if one overrides or hides the other, use it
741 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
742 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
743 if (types.asSuper(m1Owner.type, m2Owner) != null &&
744 ((m1.owner.flags_field & INTERFACE) == 0 ||
745 (m2.owner.flags_field & INTERFACE) != 0) &&
746 m1.overrides(m2, m1Owner, types, false))
747 return m1;
748 if (types.asSuper(m2Owner.type, m1Owner) != null &&
749 ((m2.owner.flags_field & INTERFACE) == 0 ||
750 (m1.owner.flags_field & INTERFACE) != 0) &&
751 m2.overrides(m1, m2Owner, types, false))
752 return m2;
753 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
754 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
755 if (m1Abstract && !m2Abstract) return m2;
756 if (m2Abstract && !m1Abstract) return m1;
757 // both abstract or both concrete
758 if (!m1Abstract && !m2Abstract)
759 return new AmbiguityError(m1, m2);
760 // check that both signatures have the same erasure
761 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
762 m2.erasure(types).getParameterTypes()))
763 return new AmbiguityError(m1, m2);
764 // both abstract, neither overridden; merge throws clause and result type
765 Symbol mostSpecific;
766 Type result2 = mt2.getReturnType();
767 if (mt2.tag == FORALL)
768 result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
769 if (types.isSubtype(mt1.getReturnType(), result2)) {
770 mostSpecific = m1;
771 } else if (types.isSubtype(result2, mt1.getReturnType())) {
772 mostSpecific = m2;
773 } else {
774 // Theoretically, this can't happen, but it is possible
775 // due to error recovery or mixing incompatible class files
776 return new AmbiguityError(m1, m2);
777 }
778 MethodSymbol result = new MethodSymbol(
779 mostSpecific.flags(),
780 mostSpecific.name,
781 null,
782 mostSpecific.owner) {
783 @Override
784 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
785 if (origin == site.tsym)
786 return this;
787 else
788 return super.implementation(origin, types, checkResult);
789 }
790 };
791 result.type = (Type)mostSpecific.type.clone();
792 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
793 mt2.getThrownTypes()));
794 return result;
795 }
796 if (m1SignatureMoreSpecific) return m1;
797 if (m2SignatureMoreSpecific) return m2;
798 return new AmbiguityError(m1, m2);
799 case AMBIGUOUS:
800 AmbiguityError e = (AmbiguityError)m2;
801 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
802 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
803 if (err1 == err2) return err1;
804 if (err1 == e.sym && err2 == e.sym2) return m2;
805 if (err1 instanceof AmbiguityError &&
806 err2 instanceof AmbiguityError &&
807 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
808 return new AmbiguityError(m1, m2);
809 else
810 return new AmbiguityError(err1, err2);
811 default:
812 throw new AssertionError();
813 }
814 }
815 //where
816 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
817 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
818 noteWarner.unchecked = false;
819 return (instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
820 allowBoxing, false, noteWarner) != null ||
821 useVarargs && instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
822 allowBoxing, true, noteWarner) != null) &&
823 !noteWarner.unchecked;
824 }
825 //where
826 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
827 List<Type> fromArgs = from.type.getParameterTypes();
828 List<Type> toArgs = to.type.getParameterTypes();
829 if (useVarargs &&
830 toArgs.length() < fromArgs.length() &&
831 (from.flags() & VARARGS) != 0 &&
832 (to.flags() & VARARGS) != 0) {
833 //if we are checking a varargs method 'from' against another varargs
834 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
835 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
836 //until 'to' signature has the same arity as 'from')
837 ListBuffer<Type> args = ListBuffer.lb();
838 Type varargsTypeFrom = fromArgs.last();
839 Type varargsTypeTo = toArgs.last();
840 while (fromArgs.head != varargsTypeFrom) {
841 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
842 fromArgs = fromArgs.tail;
843 toArgs = toArgs.head == varargsTypeTo ?
844 toArgs :
845 toArgs.tail;
846 }
847 args.append(varargsTypeTo);
848 MethodSymbol msym = new MethodSymbol(to.flags_field,
849 to.name,
850 (Type)to.type.clone(), //see: 6990136
851 to.owner);
852 MethodType mtype = msym.type.asMethodType();
853 mtype.argtypes = args.toList();
854 return msym;
855 } else {
856 return to;
857 }
858 }
860 /** Find best qualified method matching given name, type and value
861 * arguments.
862 * @param env The current environment.
863 * @param site The original type from where the selection
864 * takes place.
865 * @param name The method's name.
866 * @param argtypes The method's value arguments.
867 * @param typeargtypes The method's type arguments
868 * @param allowBoxing Allow boxing conversions of arguments.
869 * @param useVarargs Box trailing arguments into an array for varargs.
870 */
871 Symbol findMethod(Env<AttrContext> env,
872 Type site,
873 Name name,
874 List<Type> argtypes,
875 List<Type> typeargtypes,
876 boolean allowBoxing,
877 boolean useVarargs,
878 boolean operator) {
879 Symbol bestSoFar = methodNotFound;
880 return findMethod(env,
881 site,
882 name,
883 argtypes,
884 typeargtypes,
885 site.tsym.type,
886 true,
887 bestSoFar,
888 allowBoxing,
889 useVarargs,
890 operator);
891 }
892 // where
893 private Symbol findMethod(Env<AttrContext> env,
894 Type site,
895 Name name,
896 List<Type> argtypes,
897 List<Type> typeargtypes,
898 Type intype,
899 boolean abstractok,
900 Symbol bestSoFar,
901 boolean allowBoxing,
902 boolean useVarargs,
903 boolean operator) {
904 for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
905 while (ct.tag == TYPEVAR)
906 ct = ct.getUpperBound();
907 ClassSymbol c = (ClassSymbol)ct.tsym;
908 if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
909 abstractok = false;
910 for (Scope.Entry e = c.members().lookup(name);
911 e.scope != null;
912 e = e.next()) {
913 //- System.out.println(" e " + e.sym);
914 if (e.sym.kind == MTH &&
915 (e.sym.flags_field & SYNTHETIC) == 0) {
916 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
917 e.sym, bestSoFar,
918 allowBoxing,
919 useVarargs,
920 operator);
921 }
922 }
923 if (name == names.init)
924 break;
925 //- System.out.println(" - " + bestSoFar);
926 if (abstractok) {
927 Symbol concrete = methodNotFound;
928 if ((bestSoFar.flags() & ABSTRACT) == 0)
929 concrete = bestSoFar;
930 for (List<Type> l = types.interfaces(c.type);
931 l.nonEmpty();
932 l = l.tail) {
933 bestSoFar = findMethod(env, site, name, argtypes,
934 typeargtypes,
935 l.head, abstractok, bestSoFar,
936 allowBoxing, useVarargs, operator);
937 }
938 if (concrete != bestSoFar &&
939 concrete.kind < ERR && bestSoFar.kind < ERR &&
940 types.isSubSignature(concrete.type, bestSoFar.type))
941 bestSoFar = concrete;
942 }
943 }
944 return bestSoFar;
945 }
947 /** Find unqualified method matching given name, type and value arguments.
948 * @param env The current environment.
949 * @param name The method's name.
950 * @param argtypes The method's value arguments.
951 * @param typeargtypes The method's type arguments.
952 * @param allowBoxing Allow boxing conversions of arguments.
953 * @param useVarargs Box trailing arguments into an array for varargs.
954 */
955 Symbol findFun(Env<AttrContext> env, Name name,
956 List<Type> argtypes, List<Type> typeargtypes,
957 boolean allowBoxing, boolean useVarargs) {
958 Symbol bestSoFar = methodNotFound;
959 Symbol sym;
960 Env<AttrContext> env1 = env;
961 boolean staticOnly = false;
962 while (env1.outer != null) {
963 if (isStatic(env1)) staticOnly = true;
964 sym = findMethod(
965 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
966 allowBoxing, useVarargs, false);
967 if (sym.exists()) {
968 if (staticOnly &&
969 sym.kind == MTH &&
970 sym.owner.kind == TYP &&
971 (sym.flags() & STATIC) == 0) return new StaticError(sym);
972 else return sym;
973 } else if (sym.kind < bestSoFar.kind) {
974 bestSoFar = sym;
975 }
976 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
977 env1 = env1.outer;
978 }
980 sym = findMethod(env, syms.predefClass.type, name, argtypes,
981 typeargtypes, allowBoxing, useVarargs, false);
982 if (sym.exists())
983 return sym;
985 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
986 for (; e.scope != null; e = e.next()) {
987 sym = e.sym;
988 Type origin = e.getOrigin().owner.type;
989 if (sym.kind == MTH) {
990 if (e.sym.owner.type != origin)
991 sym = sym.clone(e.getOrigin().owner);
992 if (!isAccessible(env, origin, sym))
993 sym = new AccessError(env, origin, sym);
994 bestSoFar = selectBest(env, origin,
995 argtypes, typeargtypes,
996 sym, bestSoFar,
997 allowBoxing, useVarargs, false);
998 }
999 }
1000 if (bestSoFar.exists())
1001 return bestSoFar;
1003 e = env.toplevel.starImportScope.lookup(name);
1004 for (; e.scope != null; e = e.next()) {
1005 sym = e.sym;
1006 Type origin = e.getOrigin().owner.type;
1007 if (sym.kind == MTH) {
1008 if (e.sym.owner.type != origin)
1009 sym = sym.clone(e.getOrigin().owner);
1010 if (!isAccessible(env, origin, sym))
1011 sym = new AccessError(env, origin, sym);
1012 bestSoFar = selectBest(env, origin,
1013 argtypes, typeargtypes,
1014 sym, bestSoFar,
1015 allowBoxing, useVarargs, false);
1016 }
1017 }
1018 return bestSoFar;
1019 }
1021 /** Load toplevel or member class with given fully qualified name and
1022 * verify that it is accessible.
1023 * @param env The current environment.
1024 * @param name The fully qualified name of the class to be loaded.
1025 */
1026 Symbol loadClass(Env<AttrContext> env, Name name) {
1027 try {
1028 ClassSymbol c = reader.loadClass(name);
1029 return isAccessible(env, c) ? c : new AccessError(c);
1030 } catch (ClassReader.BadClassFile err) {
1031 throw err;
1032 } catch (CompletionFailure ex) {
1033 return typeNotFound;
1034 }
1035 }
1037 /** Find qualified member type.
1038 * @param env The current environment.
1039 * @param site The original type from where the selection takes
1040 * place.
1041 * @param name The type's name.
1042 * @param c The class to search for the member type. This is
1043 * always a superclass or implemented interface of
1044 * site's class.
1045 */
1046 Symbol findMemberType(Env<AttrContext> env,
1047 Type site,
1048 Name name,
1049 TypeSymbol c) {
1050 Symbol bestSoFar = typeNotFound;
1051 Symbol sym;
1052 Scope.Entry e = c.members().lookup(name);
1053 while (e.scope != null) {
1054 if (e.sym.kind == TYP) {
1055 return isAccessible(env, site, e.sym)
1056 ? e.sym
1057 : new AccessError(env, site, e.sym);
1058 }
1059 e = e.next();
1060 }
1061 Type st = types.supertype(c.type);
1062 if (st != null && st.tag == CLASS) {
1063 sym = findMemberType(env, site, name, st.tsym);
1064 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1065 }
1066 for (List<Type> l = types.interfaces(c.type);
1067 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1068 l = l.tail) {
1069 sym = findMemberType(env, site, name, l.head.tsym);
1070 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1071 sym.owner != bestSoFar.owner)
1072 bestSoFar = new AmbiguityError(bestSoFar, sym);
1073 else if (sym.kind < bestSoFar.kind)
1074 bestSoFar = sym;
1075 }
1076 return bestSoFar;
1077 }
1079 /** Find a global type in given scope and load corresponding class.
1080 * @param env The current environment.
1081 * @param scope The scope in which to look for the type.
1082 * @param name The type's name.
1083 */
1084 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1085 Symbol bestSoFar = typeNotFound;
1086 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1087 Symbol sym = loadClass(env, e.sym.flatName());
1088 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1089 bestSoFar != sym)
1090 return new AmbiguityError(bestSoFar, sym);
1091 else if (sym.kind < bestSoFar.kind)
1092 bestSoFar = sym;
1093 }
1094 return bestSoFar;
1095 }
1097 /** Find an unqualified type symbol.
1098 * @param env The current environment.
1099 * @param name The type's name.
1100 */
1101 Symbol findType(Env<AttrContext> env, Name name) {
1102 Symbol bestSoFar = typeNotFound;
1103 Symbol sym;
1104 boolean staticOnly = false;
1105 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1106 if (isStatic(env1)) staticOnly = true;
1107 for (Scope.Entry e = env1.info.scope.lookup(name);
1108 e.scope != null;
1109 e = e.next()) {
1110 if (e.sym.kind == TYP) {
1111 if (staticOnly &&
1112 e.sym.type.tag == TYPEVAR &&
1113 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1114 return e.sym;
1115 }
1116 }
1118 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1119 env1.enclClass.sym);
1120 if (staticOnly && sym.kind == TYP &&
1121 sym.type.tag == CLASS &&
1122 sym.type.getEnclosingType().tag == CLASS &&
1123 env1.enclClass.sym.type.isParameterized() &&
1124 sym.type.getEnclosingType().isParameterized())
1125 return new StaticError(sym);
1126 else if (sym.exists()) return sym;
1127 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1129 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1130 if ((encl.sym.flags() & STATIC) != 0)
1131 staticOnly = true;
1132 }
1134 if (env.tree.getTag() != JCTree.IMPORT) {
1135 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1136 if (sym.exists()) return sym;
1137 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1139 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1140 if (sym.exists()) return sym;
1141 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1143 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1144 if (sym.exists()) return sym;
1145 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1146 }
1148 return bestSoFar;
1149 }
1151 /** Find an unqualified identifier which matches a specified kind set.
1152 * @param env The current environment.
1153 * @param name The indentifier's name.
1154 * @param kind Indicates the possible symbol kinds
1155 * (a subset of VAL, TYP, PCK).
1156 */
1157 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1158 Symbol bestSoFar = typeNotFound;
1159 Symbol sym;
1161 if ((kind & VAR) != 0) {
1162 sym = findVar(env, name);
1163 if (sym.exists()) return sym;
1164 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1165 }
1167 if ((kind & TYP) != 0) {
1168 sym = findType(env, name);
1169 if (sym.exists()) return sym;
1170 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1171 }
1173 if ((kind & PCK) != 0) return reader.enterPackage(name);
1174 else return bestSoFar;
1175 }
1177 /** Find an identifier in a package which matches a specified kind set.
1178 * @param env The current environment.
1179 * @param name The identifier's name.
1180 * @param kind Indicates the possible symbol kinds
1181 * (a nonempty subset of TYP, PCK).
1182 */
1183 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1184 Name name, int kind) {
1185 Name fullname = TypeSymbol.formFullName(name, pck);
1186 Symbol bestSoFar = typeNotFound;
1187 PackageSymbol pack = null;
1188 if ((kind & PCK) != 0) {
1189 pack = reader.enterPackage(fullname);
1190 if (pack.exists()) return pack;
1191 }
1192 if ((kind & TYP) != 0) {
1193 Symbol sym = loadClass(env, fullname);
1194 if (sym.exists()) {
1195 // don't allow programs to use flatnames
1196 if (name == sym.name) return sym;
1197 }
1198 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1199 }
1200 return (pack != null) ? pack : bestSoFar;
1201 }
1203 /** Find an identifier among the members of a given type `site'.
1204 * @param env The current environment.
1205 * @param site The type containing the symbol to be found.
1206 * @param name The identifier's name.
1207 * @param kind Indicates the possible symbol kinds
1208 * (a subset of VAL, TYP).
1209 */
1210 Symbol findIdentInType(Env<AttrContext> env, Type site,
1211 Name name, int kind) {
1212 Symbol bestSoFar = typeNotFound;
1213 Symbol sym;
1214 if ((kind & VAR) != 0) {
1215 sym = findField(env, site, name, site.tsym);
1216 if (sym.exists()) return sym;
1217 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1218 }
1220 if ((kind & TYP) != 0) {
1221 sym = findMemberType(env, site, name, site.tsym);
1222 if (sym.exists()) return sym;
1223 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1224 }
1225 return bestSoFar;
1226 }
1228 /* ***************************************************************************
1229 * Access checking
1230 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1231 * an error message in the process
1232 ****************************************************************************/
1234 /** If `sym' is a bad symbol: report error and return errSymbol
1235 * else pass through unchanged,
1236 * additional arguments duplicate what has been used in trying to find the
1237 * symbol (--> flyweight pattern). This improves performance since we
1238 * expect misses to happen frequently.
1239 *
1240 * @param sym The symbol that was found, or a ResolveError.
1241 * @param pos The position to use for error reporting.
1242 * @param site The original type from where the selection took place.
1243 * @param name The symbol's name.
1244 * @param argtypes The invocation's value arguments,
1245 * if we looked for a method.
1246 * @param typeargtypes The invocation's type arguments,
1247 * if we looked for a method.
1248 */
1249 Symbol access(Symbol sym,
1250 DiagnosticPosition pos,
1251 Type site,
1252 Name name,
1253 boolean qualified,
1254 List<Type> argtypes,
1255 List<Type> typeargtypes) {
1256 if (sym.kind >= AMBIGUOUS) {
1257 ResolveError errSym = (ResolveError)sym;
1258 if (!site.isErroneous() &&
1259 !Type.isErroneous(argtypes) &&
1260 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
1261 logResolveError(errSym, pos, site, name, argtypes, typeargtypes);
1262 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1263 }
1264 return sym;
1265 }
1267 /** Same as above, but without type arguments and arguments.
1268 */
1269 Symbol access(Symbol sym,
1270 DiagnosticPosition pos,
1271 Type site,
1272 Name name,
1273 boolean qualified) {
1274 if (sym.kind >= AMBIGUOUS)
1275 return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
1276 else
1277 return sym;
1278 }
1280 /** Check that sym is not an abstract method.
1281 */
1282 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1283 if ((sym.flags() & ABSTRACT) != 0)
1284 log.error(pos, "abstract.cant.be.accessed.directly",
1285 kindName(sym), sym, sym.location());
1286 }
1288 /* ***************************************************************************
1289 * Debugging
1290 ****************************************************************************/
1292 /** print all scopes starting with scope s and proceeding outwards.
1293 * used for debugging.
1294 */
1295 public void printscopes(Scope s) {
1296 while (s != null) {
1297 if (s.owner != null)
1298 System.err.print(s.owner + ": ");
1299 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1300 if ((e.sym.flags() & ABSTRACT) != 0)
1301 System.err.print("abstract ");
1302 System.err.print(e.sym + " ");
1303 }
1304 System.err.println();
1305 s = s.next;
1306 }
1307 }
1309 void printscopes(Env<AttrContext> env) {
1310 while (env.outer != null) {
1311 System.err.println("------------------------------");
1312 printscopes(env.info.scope);
1313 env = env.outer;
1314 }
1315 }
1317 public void printscopes(Type t) {
1318 while (t.tag == CLASS) {
1319 printscopes(t.tsym.members());
1320 t = types.supertype(t);
1321 }
1322 }
1324 /* ***************************************************************************
1325 * Name resolution
1326 * Naming conventions are as for symbol lookup
1327 * Unlike the find... methods these methods will report access errors
1328 ****************************************************************************/
1330 /** Resolve an unqualified (non-method) identifier.
1331 * @param pos The position to use for error reporting.
1332 * @param env The environment current at the identifier use.
1333 * @param name The identifier's name.
1334 * @param kind The set of admissible symbol kinds for the identifier.
1335 */
1336 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1337 Name name, int kind) {
1338 return access(
1339 findIdent(env, name, kind),
1340 pos, env.enclClass.sym.type, name, false);
1341 }
1343 /** Resolve an unqualified method identifier.
1344 * @param pos The position to use for error reporting.
1345 * @param env The environment current at the method invocation.
1346 * @param name The identifier's name.
1347 * @param argtypes The types of the invocation's value arguments.
1348 * @param typeargtypes The types of the invocation's type arguments.
1349 */
1350 Symbol resolveMethod(DiagnosticPosition pos,
1351 Env<AttrContext> env,
1352 Name name,
1353 List<Type> argtypes,
1354 List<Type> typeargtypes) {
1355 Symbol sym = startResolution();
1356 List<MethodResolutionPhase> steps = methodResolutionSteps;
1357 while (steps.nonEmpty() &&
1358 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1359 sym.kind >= ERRONEOUS) {
1360 currentStep = steps.head;
1361 sym = findFun(env, name, argtypes, typeargtypes,
1362 steps.head.isBoxingRequired,
1363 env.info.varArgs = steps.head.isVarargsRequired);
1364 methodResolutionCache.put(steps.head, sym);
1365 steps = steps.tail;
1366 }
1367 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1368 MethodResolutionPhase errPhase =
1369 firstErroneousResolutionPhase();
1370 sym = access(methodResolutionCache.get(errPhase),
1371 pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1372 env.info.varArgs = errPhase.isVarargsRequired;
1373 }
1374 return sym;
1375 }
1377 private Symbol startResolution() {
1378 wrongMethod.clear();
1379 wrongMethods.clear();
1380 return methodNotFound;
1381 }
1383 /** Resolve a qualified method identifier
1384 * @param pos The position to use for error reporting.
1385 * @param env The environment current at the method invocation.
1386 * @param site The type of the qualifying expression, in which
1387 * identifier is searched.
1388 * @param name The identifier's name.
1389 * @param argtypes The types of the invocation's value arguments.
1390 * @param typeargtypes The types of the invocation's type arguments.
1391 */
1392 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1393 Type site, Name name, List<Type> argtypes,
1394 List<Type> typeargtypes) {
1395 Symbol sym = startResolution();
1396 List<MethodResolutionPhase> steps = methodResolutionSteps;
1397 while (steps.nonEmpty() &&
1398 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1399 sym.kind >= ERRONEOUS) {
1400 currentStep = steps.head;
1401 sym = findMethod(env, site, name, argtypes, typeargtypes,
1402 steps.head.isBoxingRequired(),
1403 env.info.varArgs = steps.head.isVarargsRequired(), false);
1404 methodResolutionCache.put(steps.head, sym);
1405 steps = steps.tail;
1406 }
1407 if (sym.kind >= AMBIGUOUS) {
1408 if (site.tsym.isPolymorphicSignatureGeneric() ||
1409 isTransitionalDynamicCallSite(site, sym)) {
1410 //polymorphic receiver - synthesize new method symbol
1411 env.info.varArgs = false;
1412 sym = findPolymorphicSignatureInstance(env,
1413 site, name, null, argtypes, typeargtypes);
1414 }
1415 else {
1416 //if nothing is found return the 'first' error
1417 MethodResolutionPhase errPhase =
1418 firstErroneousResolutionPhase();
1419 sym = access(methodResolutionCache.get(errPhase),
1420 pos, site, name, true, argtypes, typeargtypes);
1421 env.info.varArgs = errPhase.isVarargsRequired;
1422 }
1423 } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
1424 //non-instantiated polymorphic signature - synthesize new method symbol
1425 env.info.varArgs = false;
1426 sym = findPolymorphicSignatureInstance(env,
1427 site, name, (MethodSymbol)sym, argtypes, typeargtypes);
1428 }
1429 return sym;
1430 }
1432 /** Find or create an implicit method of exactly the given type (after erasure).
1433 * Searches in a side table, not the main scope of the site.
1434 * This emulates the lookup process required by JSR 292 in JVM.
1435 * @param env Attribution environment
1436 * @param site The original type from where the selection takes place.
1437 * @param name The method's name.
1438 * @param spMethod A template for the implicit method, or null.
1439 * @param argtypes The required argument types.
1440 * @param typeargtypes The required type arguments.
1441 */
1442 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
1443 Name name,
1444 MethodSymbol spMethod, // sig. poly. method or null if none
1445 List<Type> argtypes,
1446 List<Type> typeargtypes) {
1447 if (typeargtypes.nonEmpty() && (site.tsym.isPolymorphicSignatureGeneric() ||
1448 (spMethod != null && spMethod.isPolymorphicSignatureGeneric()))) {
1449 log.warning(env.tree.pos(), "type.parameter.on.polymorphic.signature");
1450 }
1452 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
1453 site, name, spMethod, argtypes, typeargtypes);
1454 long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
1455 (spMethod != null ?
1456 spMethod.flags() & Flags.AccessFlags :
1457 Flags.PUBLIC | Flags.STATIC);
1458 Symbol m = null;
1459 for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
1460 e.scope != null;
1461 e = e.next()) {
1462 Symbol sym = e.sym;
1463 if (types.isSameType(mtype, sym.type) &&
1464 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
1465 types.isSameType(sym.owner.type, site)) {
1466 m = sym;
1467 break;
1468 }
1469 }
1470 if (m == null) {
1471 // create the desired method
1472 m = new MethodSymbol(flags, name, mtype, site.tsym);
1473 polymorphicSignatureScope.enter(m);
1474 }
1475 return m;
1476 }
1478 /** Resolve a qualified method identifier, throw a fatal error if not
1479 * found.
1480 * @param pos The position to use for error reporting.
1481 * @param env The environment current at the method invocation.
1482 * @param site The type of the qualifying expression, in which
1483 * identifier is searched.
1484 * @param name The identifier's name.
1485 * @param argtypes The types of the invocation's value arguments.
1486 * @param typeargtypes The types of the invocation's type arguments.
1487 */
1488 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
1489 Type site, Name name,
1490 List<Type> argtypes,
1491 List<Type> typeargtypes) {
1492 Symbol sym = resolveQualifiedMethod(
1493 pos, env, site, name, argtypes, typeargtypes);
1494 if (sym.kind == MTH) return (MethodSymbol)sym;
1495 else throw new FatalError(
1496 diags.fragment("fatal.err.cant.locate.meth",
1497 name));
1498 }
1500 /** Resolve constructor.
1501 * @param pos The position to use for error reporting.
1502 * @param env The environment current at the constructor invocation.
1503 * @param site The type of class for which a constructor is searched.
1504 * @param argtypes The types of the constructor invocation's value
1505 * arguments.
1506 * @param typeargtypes The types of the constructor invocation's type
1507 * arguments.
1508 */
1509 Symbol resolveConstructor(DiagnosticPosition pos,
1510 Env<AttrContext> env,
1511 Type site,
1512 List<Type> argtypes,
1513 List<Type> typeargtypes) {
1514 Symbol sym = startResolution();
1515 List<MethodResolutionPhase> steps = methodResolutionSteps;
1516 while (steps.nonEmpty() &&
1517 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1518 sym.kind >= ERRONEOUS) {
1519 currentStep = steps.head;
1520 sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
1521 steps.head.isBoxingRequired(),
1522 env.info.varArgs = steps.head.isVarargsRequired());
1523 methodResolutionCache.put(steps.head, sym);
1524 steps = steps.tail;
1525 }
1526 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1527 MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
1528 sym = access(methodResolutionCache.get(errPhase),
1529 pos, site, names.init, true, argtypes, typeargtypes);
1530 env.info.varArgs = errPhase.isVarargsRequired();
1531 }
1532 return sym;
1533 }
1535 /** Resolve constructor using diamond inference.
1536 * @param pos The position to use for error reporting.
1537 * @param env The environment current at the constructor invocation.
1538 * @param site The type of class for which a constructor is searched.
1539 * The scope of this class has been touched in attribution.
1540 * @param argtypes The types of the constructor invocation's value
1541 * arguments.
1542 * @param typeargtypes The types of the constructor invocation's type
1543 * arguments.
1544 */
1545 Symbol resolveDiamond(DiagnosticPosition pos,
1546 Env<AttrContext> env,
1547 Type site,
1548 List<Type> argtypes,
1549 List<Type> typeargtypes) {
1550 Symbol sym = startResolution();
1551 List<MethodResolutionPhase> steps = methodResolutionSteps;
1552 while (steps.nonEmpty() &&
1553 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1554 sym.kind >= ERRONEOUS) {
1555 currentStep = steps.head;
1556 sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
1557 steps.head.isBoxingRequired(),
1558 env.info.varArgs = steps.head.isVarargsRequired());
1559 methodResolutionCache.put(steps.head, sym);
1560 steps = steps.tail;
1561 }
1562 if (sym.kind >= AMBIGUOUS) {
1563 final JCDiagnostic details = sym.kind == WRONG_MTH ?
1564 ((InapplicableSymbolError)sym).explanation :
1565 null;
1566 Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
1567 @Override
1568 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
1569 String key = details == null ?
1570 "cant.apply.diamond" :
1571 "cant.apply.diamond.1";
1572 return diags.create(dkind, log.currentSource(), pos, key, diags.fragment("diamond", site.tsym), details);
1573 }
1574 };
1575 MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
1576 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
1577 env.info.varArgs = errPhase.isVarargsRequired();
1578 }
1579 return sym;
1580 }
1582 /** Resolve constructor.
1583 * @param pos The position to use for error reporting.
1584 * @param env The environment current at the constructor invocation.
1585 * @param site The type of class for which a constructor is searched.
1586 * @param argtypes The types of the constructor invocation's value
1587 * arguments.
1588 * @param typeargtypes The types of the constructor invocation's type
1589 * arguments.
1590 * @param allowBoxing Allow boxing and varargs conversions.
1591 * @param useVarargs Box trailing arguments into an array for varargs.
1592 */
1593 Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1594 Type site, List<Type> argtypes,
1595 List<Type> typeargtypes,
1596 boolean allowBoxing,
1597 boolean useVarargs) {
1598 Symbol sym = findMethod(env, site,
1599 names.init, argtypes,
1600 typeargtypes, allowBoxing,
1601 useVarargs, false);
1602 if ((sym.flags() & DEPRECATED) != 0 &&
1603 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
1604 env.info.scope.owner.outermostClass() != sym.outermostClass())
1605 chk.warnDeprecated(pos, sym);
1606 return sym;
1607 }
1609 /** Resolve a constructor, throw a fatal error if not found.
1610 * @param pos The position to use for error reporting.
1611 * @param env The environment current at the method invocation.
1612 * @param site The type to be constructed.
1613 * @param argtypes The types of the invocation's value arguments.
1614 * @param typeargtypes The types of the invocation's type arguments.
1615 */
1616 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1617 Type site,
1618 List<Type> argtypes,
1619 List<Type> typeargtypes) {
1620 Symbol sym = resolveConstructor(
1621 pos, env, site, argtypes, typeargtypes);
1622 if (sym.kind == MTH) return (MethodSymbol)sym;
1623 else throw new FatalError(
1624 diags.fragment("fatal.err.cant.locate.ctor", site));
1625 }
1627 /** Resolve operator.
1628 * @param pos The position to use for error reporting.
1629 * @param optag The tag of the operation tree.
1630 * @param env The environment current at the operation.
1631 * @param argtypes The types of the operands.
1632 */
1633 Symbol resolveOperator(DiagnosticPosition pos, int optag,
1634 Env<AttrContext> env, List<Type> argtypes) {
1635 Name name = treeinfo.operatorName(optag);
1636 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
1637 null, false, false, true);
1638 if (boxingEnabled && sym.kind >= WRONG_MTHS)
1639 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1640 null, true, false, true);
1641 return access(sym, pos, env.enclClass.sym.type, name,
1642 false, argtypes, null);
1643 }
1645 /** Resolve operator.
1646 * @param pos The position to use for error reporting.
1647 * @param optag The tag of the operation tree.
1648 * @param env The environment current at the operation.
1649 * @param arg The type of the operand.
1650 */
1651 Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
1652 return resolveOperator(pos, optag, env, List.of(arg));
1653 }
1655 /** Resolve binary operator.
1656 * @param pos The position to use for error reporting.
1657 * @param optag The tag of the operation tree.
1658 * @param env The environment current at the operation.
1659 * @param left The types of the left operand.
1660 * @param right The types of the right operand.
1661 */
1662 Symbol resolveBinaryOperator(DiagnosticPosition pos,
1663 int optag,
1664 Env<AttrContext> env,
1665 Type left,
1666 Type right) {
1667 return resolveOperator(pos, optag, env, List.of(left, right));
1668 }
1670 /**
1671 * Resolve `c.name' where name == this or name == super.
1672 * @param pos The position to use for error reporting.
1673 * @param env The environment current at the expression.
1674 * @param c The qualifier.
1675 * @param name The identifier's name.
1676 */
1677 Symbol resolveSelf(DiagnosticPosition pos,
1678 Env<AttrContext> env,
1679 TypeSymbol c,
1680 Name name) {
1681 Env<AttrContext> env1 = env;
1682 boolean staticOnly = false;
1683 while (env1.outer != null) {
1684 if (isStatic(env1)) staticOnly = true;
1685 if (env1.enclClass.sym == c) {
1686 Symbol sym = env1.info.scope.lookup(name).sym;
1687 if (sym != null) {
1688 if (staticOnly) sym = new StaticError(sym);
1689 return access(sym, pos, env.enclClass.sym.type,
1690 name, true);
1691 }
1692 }
1693 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1694 env1 = env1.outer;
1695 }
1696 log.error(pos, "not.encl.class", c);
1697 return syms.errSymbol;
1698 }
1700 /**
1701 * Resolve `c.this' for an enclosing class c that contains the
1702 * named member.
1703 * @param pos The position to use for error reporting.
1704 * @param env The environment current at the expression.
1705 * @param member The member that must be contained in the result.
1706 */
1707 Symbol resolveSelfContaining(DiagnosticPosition pos,
1708 Env<AttrContext> env,
1709 Symbol member) {
1710 Name name = names._this;
1711 Env<AttrContext> env1 = env;
1712 boolean staticOnly = false;
1713 while (env1.outer != null) {
1714 if (isStatic(env1)) staticOnly = true;
1715 if (env1.enclClass.sym.isSubClass(member.owner, types) &&
1716 isAccessible(env, env1.enclClass.sym.type, member)) {
1717 Symbol sym = env1.info.scope.lookup(name).sym;
1718 if (sym != null) {
1719 if (staticOnly) sym = new StaticError(sym);
1720 return access(sym, pos, env.enclClass.sym.type,
1721 name, true);
1722 }
1723 }
1724 if ((env1.enclClass.sym.flags() & STATIC) != 0)
1725 staticOnly = true;
1726 env1 = env1.outer;
1727 }
1728 log.error(pos, "encl.class.required", member);
1729 return syms.errSymbol;
1730 }
1732 /**
1733 * Resolve an appropriate implicit this instance for t's container.
1734 * JLS2 8.8.5.1 and 15.9.2
1735 */
1736 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
1737 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
1738 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
1739 : resolveSelfContaining(pos, env, t.tsym)).type;
1740 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
1741 log.error(pos, "cant.ref.before.ctor.called", "this");
1742 return thisType;
1743 }
1745 /* ***************************************************************************
1746 * ResolveError classes, indicating error situations when accessing symbols
1747 ****************************************************************************/
1749 public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
1750 AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
1751 logResolveError(error, tree.pos(), type.getEnclosingType(), null, null, null);
1752 }
1753 //where
1754 private void logResolveError(ResolveError error,
1755 DiagnosticPosition pos,
1756 Type site,
1757 Name name,
1758 List<Type> argtypes,
1759 List<Type> typeargtypes) {
1760 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
1761 pos, site, name, argtypes, typeargtypes);
1762 if (d != null) {
1763 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
1764 log.report(d);
1765 }
1766 }
1768 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
1770 public Object methodArguments(List<Type> argtypes) {
1771 return argtypes.isEmpty() ? noArgs : argtypes;
1772 }
1774 /**
1775 * Root class for resolution errors. Subclass of ResolveError
1776 * represent a different kinds of resolution error - as such they must
1777 * specify how they map into concrete compiler diagnostics.
1778 */
1779 private abstract class ResolveError extends Symbol {
1781 /** The name of the kind of error, for debugging only. */
1782 final String debugName;
1784 ResolveError(int kind, String debugName) {
1785 super(kind, 0, null, null, null);
1786 this.debugName = debugName;
1787 }
1789 @Override
1790 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1791 throw new AssertionError();
1792 }
1794 @Override
1795 public String toString() {
1796 return debugName;
1797 }
1799 @Override
1800 public boolean exists() {
1801 return false;
1802 }
1804 /**
1805 * Create an external representation for this erroneous symbol to be
1806 * used during attribution - by default this returns the symbol of a
1807 * brand new error type which stores the original type found
1808 * during resolution.
1809 *
1810 * @param name the name used during resolution
1811 * @param location the location from which the symbol is accessed
1812 */
1813 protected Symbol access(Name name, TypeSymbol location) {
1814 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
1815 }
1817 /**
1818 * Create a diagnostic representing this resolution error.
1819 *
1820 * @param dkind The kind of the diagnostic to be created (e.g error).
1821 * @param pos The position to be used for error reporting.
1822 * @param site The original type from where the selection took place.
1823 * @param name The name of the symbol to be resolved.
1824 * @param argtypes The invocation's value arguments,
1825 * if we looked for a method.
1826 * @param typeargtypes The invocation's type arguments,
1827 * if we looked for a method.
1828 */
1829 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1830 DiagnosticPosition pos,
1831 Type site,
1832 Name name,
1833 List<Type> argtypes,
1834 List<Type> typeargtypes);
1836 /**
1837 * A name designates an operator if it consists
1838 * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
1839 */
1840 boolean isOperator(Name name) {
1841 int i = 0;
1842 while (i < name.getByteLength() &&
1843 "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
1844 return i > 0 && i == name.getByteLength();
1845 }
1846 }
1848 /**
1849 * This class is the root class of all resolution errors caused by
1850 * an invalid symbol being found during resolution.
1851 */
1852 abstract class InvalidSymbolError extends ResolveError {
1854 /** The invalid symbol found during resolution */
1855 Symbol sym;
1857 InvalidSymbolError(int kind, Symbol sym, String debugName) {
1858 super(kind, debugName);
1859 this.sym = sym;
1860 }
1862 @Override
1863 public boolean exists() {
1864 return true;
1865 }
1867 @Override
1868 public String toString() {
1869 return super.toString() + " wrongSym=" + sym;
1870 }
1872 @Override
1873 public Symbol access(Name name, TypeSymbol location) {
1874 if (sym.kind >= AMBIGUOUS)
1875 return ((ResolveError)sym).access(name, location);
1876 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
1877 return types.createErrorType(name, location, sym.type).tsym;
1878 else
1879 return sym;
1880 }
1881 }
1883 /**
1884 * InvalidSymbolError error class indicating that a symbol matching a
1885 * given name does not exists in a given site.
1886 */
1887 class SymbolNotFoundError extends ResolveError {
1889 SymbolNotFoundError(int kind) {
1890 super(kind, "symbol not found error");
1891 }
1893 @Override
1894 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1895 DiagnosticPosition pos,
1896 Type site,
1897 Name name,
1898 List<Type> argtypes,
1899 List<Type> typeargtypes) {
1900 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
1901 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
1902 if (name == names.error)
1903 return null;
1905 if (isOperator(name)) {
1906 return diags.create(dkind, log.currentSource(), pos,
1907 "operator.cant.be.applied", name, argtypes);
1908 }
1909 boolean hasLocation = false;
1910 if (!site.tsym.name.isEmpty()) {
1911 if (site.tsym.kind == PCK && !site.tsym.exists()) {
1912 return diags.create(dkind, log.currentSource(), pos,
1913 "doesnt.exist", site.tsym);
1914 }
1915 hasLocation = true;
1916 }
1917 boolean isConstructor = kind == ABSENT_MTH &&
1918 name == names.table.names.init;
1919 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
1920 Name idname = isConstructor ? site.tsym.name : name;
1921 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
1922 if (hasLocation) {
1923 return diags.create(dkind, log.currentSource(), pos,
1924 errKey, kindname, idname, //symbol kindname, name
1925 typeargtypes, argtypes, //type parameters and arguments (if any)
1926 typeKindName(site), site); //location kindname, type
1927 }
1928 else {
1929 return diags.create(dkind, log.currentSource(), pos,
1930 errKey, kindname, idname, //symbol kindname, name
1931 typeargtypes, argtypes); //type parameters and arguments (if any)
1932 }
1933 }
1934 //where
1935 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
1936 String key = "cant.resolve";
1937 String suffix = hasLocation ? ".location" : "";
1938 switch (kindname) {
1939 case METHOD:
1940 case CONSTRUCTOR: {
1941 suffix += ".args";
1942 suffix += hasTypeArgs ? ".params" : "";
1943 }
1944 }
1945 return key + suffix;
1946 }
1947 }
1949 /**
1950 * InvalidSymbolError error class indicating that a given symbol
1951 * (either a method, a constructor or an operand) is not applicable
1952 * given an actual arguments/type argument list.
1953 */
1954 class InapplicableSymbolError extends InvalidSymbolError {
1956 /** An auxiliary explanation set in case of instantiation errors. */
1957 JCDiagnostic explanation;
1959 InapplicableSymbolError(Symbol sym) {
1960 super(WRONG_MTH, sym, "inapplicable symbol error");
1961 }
1963 /** Update sym and explanation and return this.
1964 */
1965 InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
1966 this.sym = sym;
1967 if (this.sym == sym && explanation != null)
1968 this.explanation = explanation; //update the details
1969 return this;
1970 }
1972 /** Update sym and return this.
1973 */
1974 InapplicableSymbolError setWrongSym(Symbol sym) {
1975 this.sym = sym;
1976 return this;
1977 }
1979 @Override
1980 public String toString() {
1981 return super.toString() + " explanation=" + explanation;
1982 }
1984 @Override
1985 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1986 DiagnosticPosition pos,
1987 Type site,
1988 Name name,
1989 List<Type> argtypes,
1990 List<Type> typeargtypes) {
1991 if (name == names.error)
1992 return null;
1994 if (isOperator(name)) {
1995 return diags.create(dkind, log.currentSource(),
1996 pos, "operator.cant.be.applied", name, argtypes);
1997 }
1998 else {
1999 Symbol ws = sym.asMemberOf(site, types);
2000 return diags.create(dkind, log.currentSource(), pos,
2001 "cant.apply.symbol" + (explanation != null ? ".1" : ""),
2002 kindName(ws),
2003 ws.name == names.init ? ws.owner.name : ws.name,
2004 methodArguments(ws.type.getParameterTypes()),
2005 methodArguments(argtypes),
2006 kindName(ws.owner),
2007 ws.owner.type,
2008 explanation);
2009 }
2010 }
2012 void clear() {
2013 explanation = null;
2014 }
2016 @Override
2017 public Symbol access(Name name, TypeSymbol location) {
2018 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2019 }
2020 }
2022 /**
2023 * ResolveError error class indicating that a set of symbols
2024 * (either methods, constructors or operands) is not applicable
2025 * given an actual arguments/type argument list.
2026 */
2027 class InapplicableSymbolsError extends ResolveError {
2029 private List<Candidate> candidates = List.nil();
2031 InapplicableSymbolsError(Symbol sym) {
2032 super(WRONG_MTHS, "inapplicable symbols");
2033 }
2035 @Override
2036 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2037 DiagnosticPosition pos,
2038 Type site,
2039 Name name,
2040 List<Type> argtypes,
2041 List<Type> typeargtypes) {
2042 if (candidates.nonEmpty()) {
2043 JCDiagnostic err = diags.create(dkind,
2044 log.currentSource(),
2045 pos,
2046 "cant.apply.symbols",
2047 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2048 getName(),
2049 argtypes);
2050 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2051 } else {
2052 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2053 site, name, argtypes, typeargtypes);
2054 }
2055 }
2057 //where
2058 List<JCDiagnostic> candidateDetails(Type site) {
2059 List<JCDiagnostic> details = List.nil();
2060 for (Candidate c : candidates)
2061 details = details.prepend(c.getDiagnostic(site));
2062 return details.reverse();
2063 }
2065 Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
2066 Candidate c = new Candidate(currentStep, sym, details);
2067 if (c.isValid() && !candidates.contains(c))
2068 candidates = candidates.append(c);
2069 return this;
2070 }
2072 void clear() {
2073 candidates = List.nil();
2074 }
2076 private Name getName() {
2077 Symbol sym = candidates.head.sym;
2078 return sym.name == names.init ?
2079 sym.owner.name :
2080 sym.name;
2081 }
2083 private class Candidate {
2085 final MethodResolutionPhase step;
2086 final Symbol sym;
2087 final JCDiagnostic details;
2089 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
2090 this.step = step;
2091 this.sym = sym;
2092 this.details = details;
2093 }
2095 JCDiagnostic getDiagnostic(Type site) {
2096 return diags.fragment("inapplicable.method",
2097 Kinds.kindName(sym),
2098 sym.location(site, types),
2099 sym.asMemberOf(site, types),
2100 details);
2101 }
2103 @Override
2104 public boolean equals(Object o) {
2105 if (o instanceof Candidate) {
2106 Symbol s1 = this.sym;
2107 Symbol s2 = ((Candidate)o).sym;
2108 if ((s1 != s2 &&
2109 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2110 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2111 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2112 return true;
2113 }
2114 return false;
2115 }
2117 boolean isValid() {
2118 return (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
2119 (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
2120 }
2121 }
2122 }
2124 /**
2125 * An InvalidSymbolError error class indicating that a symbol is not
2126 * accessible from a given site
2127 */
2128 class AccessError extends InvalidSymbolError {
2130 private Env<AttrContext> env;
2131 private Type site;
2133 AccessError(Symbol sym) {
2134 this(null, null, sym);
2135 }
2137 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2138 super(HIDDEN, sym, "access error");
2139 this.env = env;
2140 this.site = site;
2141 if (debugResolve)
2142 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2143 }
2145 @Override
2146 public boolean exists() {
2147 return false;
2148 }
2150 @Override
2151 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2152 DiagnosticPosition pos,
2153 Type site,
2154 Name name,
2155 List<Type> argtypes,
2156 List<Type> typeargtypes) {
2157 if (sym.owner.type.tag == ERROR)
2158 return null;
2160 if (sym.name == names.init && sym.owner != site.tsym) {
2161 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2162 pos, site, name, argtypes, typeargtypes);
2163 }
2164 else if ((sym.flags() & PUBLIC) != 0
2165 || (env != null && this.site != null
2166 && !isAccessible(env, this.site))) {
2167 return diags.create(dkind, log.currentSource(),
2168 pos, "not.def.access.class.intf.cant.access",
2169 sym, sym.location());
2170 }
2171 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2172 return diags.create(dkind, log.currentSource(),
2173 pos, "report.access", sym,
2174 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2175 sym.location());
2176 }
2177 else {
2178 return diags.create(dkind, log.currentSource(),
2179 pos, "not.def.public.cant.access", sym, sym.location());
2180 }
2181 }
2182 }
2184 /**
2185 * InvalidSymbolError error class indicating that an instance member
2186 * has erroneously been accessed from a static context.
2187 */
2188 class StaticError extends InvalidSymbolError {
2190 StaticError(Symbol sym) {
2191 super(STATICERR, sym, "static error");
2192 }
2194 @Override
2195 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2196 DiagnosticPosition pos,
2197 Type site,
2198 Name name,
2199 List<Type> argtypes,
2200 List<Type> typeargtypes) {
2201 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2202 ? types.erasure(sym.type).tsym
2203 : sym);
2204 return diags.create(dkind, log.currentSource(), pos,
2205 "non-static.cant.be.ref", kindName(sym), errSym);
2206 }
2207 }
2209 /**
2210 * InvalidSymbolError error class indicating that a pair of symbols
2211 * (either methods, constructors or operands) are ambiguous
2212 * given an actual arguments/type argument list.
2213 */
2214 class AmbiguityError extends InvalidSymbolError {
2216 /** The other maximally specific symbol */
2217 Symbol sym2;
2219 AmbiguityError(Symbol sym1, Symbol sym2) {
2220 super(AMBIGUOUS, sym1, "ambiguity error");
2221 this.sym2 = sym2;
2222 }
2224 @Override
2225 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2226 DiagnosticPosition pos,
2227 Type site,
2228 Name name,
2229 List<Type> argtypes,
2230 List<Type> typeargtypes) {
2231 AmbiguityError pair = this;
2232 while (true) {
2233 if (pair.sym.kind == AMBIGUOUS)
2234 pair = (AmbiguityError)pair.sym;
2235 else if (pair.sym2.kind == AMBIGUOUS)
2236 pair = (AmbiguityError)pair.sym2;
2237 else break;
2238 }
2239 Name sname = pair.sym.name;
2240 if (sname == names.init) sname = pair.sym.owner.name;
2241 return diags.create(dkind, log.currentSource(),
2242 pos, "ref.ambiguous", sname,
2243 kindName(pair.sym),
2244 pair.sym,
2245 pair.sym.location(site, types),
2246 kindName(pair.sym2),
2247 pair.sym2,
2248 pair.sym2.location(site, types));
2249 }
2250 }
2252 enum MethodResolutionPhase {
2253 BASIC(false, false),
2254 BOX(true, false),
2255 VARARITY(true, true);
2257 boolean isBoxingRequired;
2258 boolean isVarargsRequired;
2260 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2261 this.isBoxingRequired = isBoxingRequired;
2262 this.isVarargsRequired = isVarargsRequired;
2263 }
2265 public boolean isBoxingRequired() {
2266 return isBoxingRequired;
2267 }
2269 public boolean isVarargsRequired() {
2270 return isVarargsRequired;
2271 }
2273 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2274 return (varargsEnabled || !isVarargsRequired) &&
2275 (boxingEnabled || !isBoxingRequired);
2276 }
2277 }
2279 private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
2280 new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
2282 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2284 private MethodResolutionPhase currentStep = null;
2286 private MethodResolutionPhase firstErroneousResolutionPhase() {
2287 MethodResolutionPhase bestSoFar = BASIC;
2288 Symbol sym = methodNotFound;
2289 List<MethodResolutionPhase> steps = methodResolutionSteps;
2290 while (steps.nonEmpty() &&
2291 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2292 sym.kind >= WRONG_MTHS) {
2293 sym = methodResolutionCache.get(steps.head);
2294 bestSoFar = steps.head;
2295 steps = steps.tail;
2296 }
2297 return bestSoFar;
2298 }
2299 }