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