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