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