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