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