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