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