Wed, 02 Mar 2011 10:56:39 +0000
6541876: "Enclosing Instance" error new in 1.6
Summary: unqualified 'this' should not be selected in a qualified super() call in a default constructor
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 || sym.owner == s2.owner ||
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();
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(env, 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(Env<AttrContext> env,
415 List<Type> argtypes,
416 List<Type> formals,
417 boolean allowBoxing,
418 boolean useVarargs,
419 Warner warn) {
420 try {
421 checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
422 return true;
423 } catch (InapplicableMethodException ex) {
424 return false;
425 }
426 }
427 void checkRawArgumentsAcceptable(Env<AttrContext> env,
428 List<Type> argtypes,
429 List<Type> formals,
430 boolean allowBoxing,
431 boolean useVarargs,
432 Warner warn) {
433 Type varargsFormal = useVarargs ? formals.last() : null;
434 if (varargsFormal == null &&
435 argtypes.size() != formals.size()) {
436 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
437 }
439 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
440 boolean works = allowBoxing
441 ? types.isConvertible(argtypes.head, formals.head, warn)
442 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
443 if (!works)
444 throw inapplicableMethodException.setMessage("no.conforming.assignment.exists",
445 argtypes.head,
446 formals.head);
447 argtypes = argtypes.tail;
448 formals = formals.tail;
449 }
451 if (formals.head != varargsFormal)
452 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
454 if (useVarargs) {
455 //note: if applicability check is triggered by most specific test,
456 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
457 Type elt = types.elemtypeOrType(varargsFormal);
458 while (argtypes.nonEmpty()) {
459 if (!types.isConvertible(argtypes.head, elt, warn))
460 throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
461 argtypes.head,
462 elt);
463 argtypes = argtypes.tail;
464 }
465 //check varargs element type accessibility
466 if (!isAccessible(env, elt)) {
467 Symbol location = env.enclClass.sym;
468 throw inapplicableMethodException.setMessage("inaccessible.varargs.type",
469 elt,
470 Kinds.kindName(location),
471 location);
472 }
473 }
474 return;
475 }
476 // where
477 public static class InapplicableMethodException extends RuntimeException {
478 private static final long serialVersionUID = 0;
480 JCDiagnostic diagnostic;
481 JCDiagnostic.Factory diags;
483 InapplicableMethodException(JCDiagnostic.Factory diags) {
484 this.diagnostic = null;
485 this.diags = diags;
486 }
487 InapplicableMethodException setMessage() {
488 this.diagnostic = null;
489 return this;
490 }
491 InapplicableMethodException setMessage(String key) {
492 this.diagnostic = key != null ? diags.fragment(key) : null;
493 return this;
494 }
495 InapplicableMethodException setMessage(String key, Object... args) {
496 this.diagnostic = key != null ? diags.fragment(key, args) : null;
497 return this;
498 }
499 InapplicableMethodException setMessage(JCDiagnostic diag) {
500 this.diagnostic = diag;
501 return this;
502 }
504 public JCDiagnostic getDiagnostic() {
505 return diagnostic;
506 }
507 }
508 private final InapplicableMethodException inapplicableMethodException;
510 /* ***************************************************************************
511 * Symbol lookup
512 * the following naming conventions for arguments are used
513 *
514 * env is the environment where the symbol was mentioned
515 * site is the type of which the symbol is a member
516 * name is the symbol's name
517 * if no arguments are given
518 * argtypes are the value arguments, if we search for a method
519 *
520 * If no symbol was found, a ResolveError detailing the problem is returned.
521 ****************************************************************************/
523 /** Find field. Synthetic fields are always skipped.
524 * @param env The current environment.
525 * @param site The original type from where the selection takes place.
526 * @param name The name of the field.
527 * @param c The class to search for the field. This is always
528 * a superclass or implemented interface of site's class.
529 */
530 Symbol findField(Env<AttrContext> env,
531 Type site,
532 Name name,
533 TypeSymbol c) {
534 while (c.type.tag == TYPEVAR)
535 c = c.type.getUpperBound().tsym;
536 Symbol bestSoFar = varNotFound;
537 Symbol sym;
538 Scope.Entry e = c.members().lookup(name);
539 while (e.scope != null) {
540 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
541 return isAccessible(env, site, e.sym)
542 ? e.sym : new AccessError(env, site, e.sym);
543 }
544 e = e.next();
545 }
546 Type st = types.supertype(c.type);
547 if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
548 sym = findField(env, site, name, st.tsym);
549 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
550 }
551 for (List<Type> l = types.interfaces(c.type);
552 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
553 l = l.tail) {
554 sym = findField(env, site, name, l.head.tsym);
555 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
556 sym.owner != bestSoFar.owner)
557 bestSoFar = new AmbiguityError(bestSoFar, sym);
558 else if (sym.kind < bestSoFar.kind)
559 bestSoFar = sym;
560 }
561 return bestSoFar;
562 }
564 /** Resolve a field identifier, throw a fatal error if not found.
565 * @param pos The position to use for error reporting.
566 * @param env The environment current at the method invocation.
567 * @param site The type of the qualifying expression, in which
568 * identifier is searched.
569 * @param name The identifier's name.
570 */
571 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
572 Type site, Name name) {
573 Symbol sym = findField(env, site, name, site.tsym);
574 if (sym.kind == VAR) return (VarSymbol)sym;
575 else throw new FatalError(
576 diags.fragment("fatal.err.cant.locate.field",
577 name));
578 }
580 /** Find unqualified variable or field with given name.
581 * Synthetic fields always skipped.
582 * @param env The current environment.
583 * @param name The name of the variable or field.
584 */
585 Symbol findVar(Env<AttrContext> env, Name name) {
586 Symbol bestSoFar = varNotFound;
587 Symbol sym;
588 Env<AttrContext> env1 = env;
589 boolean staticOnly = false;
590 while (env1.outer != null) {
591 if (isStatic(env1)) staticOnly = true;
592 Scope.Entry e = env1.info.scope.lookup(name);
593 while (e.scope != null &&
594 (e.sym.kind != VAR ||
595 (e.sym.flags_field & SYNTHETIC) != 0))
596 e = e.next();
597 sym = (e.scope != null)
598 ? e.sym
599 : findField(
600 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
601 if (sym.exists()) {
602 if (staticOnly &&
603 sym.kind == VAR &&
604 sym.owner.kind == TYP &&
605 (sym.flags() & STATIC) == 0)
606 return new StaticError(sym);
607 else
608 return sym;
609 } else if (sym.kind < bestSoFar.kind) {
610 bestSoFar = sym;
611 }
613 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
614 env1 = env1.outer;
615 }
617 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
618 if (sym.exists())
619 return sym;
620 if (bestSoFar.exists())
621 return bestSoFar;
623 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
624 for (; e.scope != null; e = e.next()) {
625 sym = e.sym;
626 Type origin = e.getOrigin().owner.type;
627 if (sym.kind == VAR) {
628 if (e.sym.owner.type != origin)
629 sym = sym.clone(e.getOrigin().owner);
630 return isAccessible(env, origin, sym)
631 ? sym : new AccessError(env, origin, sym);
632 }
633 }
635 Symbol origin = null;
636 e = env.toplevel.starImportScope.lookup(name);
637 for (; e.scope != null; e = e.next()) {
638 sym = e.sym;
639 if (sym.kind != VAR)
640 continue;
641 // invariant: sym.kind == VAR
642 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
643 return new AmbiguityError(bestSoFar, sym);
644 else if (bestSoFar.kind >= VAR) {
645 origin = e.getOrigin().owner;
646 bestSoFar = isAccessible(env, origin.type, sym)
647 ? sym : new AccessError(env, origin.type, sym);
648 }
649 }
650 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
651 return bestSoFar.clone(origin);
652 else
653 return bestSoFar;
654 }
656 Warner noteWarner = new Warner();
658 /** Select the best method for a call site among two choices.
659 * @param env The current environment.
660 * @param site The original type from where the
661 * selection takes place.
662 * @param argtypes The invocation's value arguments,
663 * @param typeargtypes The invocation's type arguments,
664 * @param sym Proposed new best match.
665 * @param bestSoFar Previously found best match.
666 * @param allowBoxing Allow boxing conversions of arguments.
667 * @param useVarargs Box trailing arguments into an array for varargs.
668 */
669 @SuppressWarnings("fallthrough")
670 Symbol selectBest(Env<AttrContext> env,
671 Type site,
672 List<Type> argtypes,
673 List<Type> typeargtypes,
674 Symbol sym,
675 Symbol bestSoFar,
676 boolean allowBoxing,
677 boolean useVarargs,
678 boolean operator) {
679 if (sym.kind == ERR) return bestSoFar;
680 if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
681 Assert.check(sym.kind < AMBIGUOUS);
682 try {
683 rawInstantiate(env, site, sym, argtypes, typeargtypes,
684 allowBoxing, useVarargs, Warner.noWarnings);
685 } catch (InapplicableMethodException ex) {
686 switch (bestSoFar.kind) {
687 case ABSENT_MTH:
688 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
689 case WRONG_MTH:
690 wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
691 case WRONG_MTHS:
692 return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
693 default:
694 return bestSoFar;
695 }
696 }
697 if (!isAccessible(env, site, sym)) {
698 return (bestSoFar.kind == ABSENT_MTH)
699 ? new AccessError(env, site, sym)
700 : bestSoFar;
701 }
702 return (bestSoFar.kind > AMBIGUOUS)
703 ? sym
704 : mostSpecific(sym, bestSoFar, env, site,
705 allowBoxing && operator, useVarargs);
706 }
708 /* Return the most specific of the two methods for a call,
709 * given that both are accessible and applicable.
710 * @param m1 A new candidate for most specific.
711 * @param m2 The previous most specific candidate.
712 * @param env The current environment.
713 * @param site The original type from where the selection
714 * takes place.
715 * @param allowBoxing Allow boxing conversions of arguments.
716 * @param useVarargs Box trailing arguments into an array for varargs.
717 */
718 Symbol mostSpecific(Symbol m1,
719 Symbol m2,
720 Env<AttrContext> env,
721 final Type site,
722 boolean allowBoxing,
723 boolean useVarargs) {
724 switch (m2.kind) {
725 case MTH:
726 if (m1 == m2) return m1;
727 boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
728 boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
729 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
730 Type mt1 = types.memberType(site, m1);
731 Type mt2 = types.memberType(site, m2);
732 if (!types.overrideEquivalent(mt1, mt2))
733 return ambiguityError(m1, m2);
735 // same signature; select (a) the non-bridge method, or
736 // (b) the one that overrides the other, or (c) the concrete
737 // one, or (d) merge both abstract signatures
738 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
739 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
741 // if one overrides or hides the other, use it
742 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
743 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
744 if (types.asSuper(m1Owner.type, m2Owner) != null &&
745 ((m1.owner.flags_field & INTERFACE) == 0 ||
746 (m2.owner.flags_field & INTERFACE) != 0) &&
747 m1.overrides(m2, m1Owner, types, false))
748 return m1;
749 if (types.asSuper(m2Owner.type, m1Owner) != null &&
750 ((m2.owner.flags_field & INTERFACE) == 0 ||
751 (m1.owner.flags_field & INTERFACE) != 0) &&
752 m2.overrides(m1, m2Owner, types, false))
753 return m2;
754 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
755 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
756 if (m1Abstract && !m2Abstract) return m2;
757 if (m2Abstract && !m1Abstract) return m1;
758 // both abstract or both concrete
759 if (!m1Abstract && !m2Abstract)
760 return ambiguityError(m1, m2);
761 // check that both signatures have the same erasure
762 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
763 m2.erasure(types).getParameterTypes()))
764 return ambiguityError(m1, m2);
765 // both abstract, neither overridden; merge throws clause and result type
766 Symbol mostSpecific;
767 Type result2 = mt2.getReturnType();
768 if (mt2.tag == FORALL)
769 result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
770 if (types.isSubtype(mt1.getReturnType(), result2))
771 mostSpecific = m1;
772 else if (types.isSubtype(result2, mt1.getReturnType()))
773 mostSpecific = m2;
774 else {
775 // Theoretically, this can't happen, but it is possible
776 // due to error recovery or mixing incompatible class files
777 return ambiguityError(m1, m2);
778 }
779 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
780 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
781 MethodSymbol result = new MethodSymbol(
782 mostSpecific.flags(),
783 mostSpecific.name,
784 newSig,
785 mostSpecific.owner) {
786 @Override
787 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
788 if (origin == site.tsym)
789 return this;
790 else
791 return super.implementation(origin, types, checkResult);
792 }
793 };
794 return result;
795 }
796 if (m1SignatureMoreSpecific) return m1;
797 if (m2SignatureMoreSpecific) return m2;
798 return ambiguityError(m1, m2);
799 case AMBIGUOUS:
800 AmbiguityError e = (AmbiguityError)m2;
801 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
802 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
803 if (err1 == err2) return err1;
804 if (err1 == e.sym && err2 == e.sym2) return m2;
805 if (err1 instanceof AmbiguityError &&
806 err2 instanceof AmbiguityError &&
807 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
808 return ambiguityError(m1, m2);
809 else
810 return ambiguityError(err1, err2);
811 default:
812 throw new AssertionError();
813 }
814 }
815 //where
816 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
817 noteWarner.clear();
818 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
819 return (instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
820 allowBoxing, false, noteWarner) != null ||
821 useVarargs && instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
822 allowBoxing, true, noteWarner) != null) &&
823 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
824 }
825 //where
826 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
827 List<Type> fromArgs = from.type.getParameterTypes();
828 List<Type> toArgs = to.type.getParameterTypes();
829 if (useVarargs &&
830 (from.flags() & VARARGS) != 0 &&
831 (to.flags() & VARARGS) != 0) {
832 Type varargsTypeFrom = fromArgs.last();
833 Type varargsTypeTo = toArgs.last();
834 ListBuffer<Type> args = ListBuffer.lb();
835 if (toArgs.length() < fromArgs.length()) {
836 //if we are checking a varargs method 'from' against another varargs
837 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
838 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
839 //until 'to' signature has the same arity as 'from')
840 while (fromArgs.head != varargsTypeFrom) {
841 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
842 fromArgs = fromArgs.tail;
843 toArgs = toArgs.head == varargsTypeTo ?
844 toArgs :
845 toArgs.tail;
846 }
847 } else {
848 //formal argument list is same as original list where last
849 //argument (array type) is removed
850 args.appendList(toArgs.reverse().tail.reverse());
851 }
852 //append varargs element type as last synthetic formal
853 args.append(types.elemtype(varargsTypeTo));
854 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
855 return new MethodSymbol(to.flags_field, to.name, mtype, to.owner);
856 } else {
857 return to;
858 }
859 }
860 //where
861 Symbol ambiguityError(Symbol m1, Symbol m2) {
862 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
863 return (m1.flags() & CLASH) == 0 ? m1 : m2;
864 } else {
865 return new AmbiguityError(m1, m2);
866 }
867 }
869 /** Find best qualified method matching given name, type and value
870 * arguments.
871 * @param env The current environment.
872 * @param site The original type from where the selection
873 * takes place.
874 * @param name The method's name.
875 * @param argtypes The method's value arguments.
876 * @param typeargtypes The method's type arguments
877 * @param allowBoxing Allow boxing conversions of arguments.
878 * @param useVarargs Box trailing arguments into an array for varargs.
879 */
880 Symbol findMethod(Env<AttrContext> env,
881 Type site,
882 Name name,
883 List<Type> argtypes,
884 List<Type> typeargtypes,
885 boolean allowBoxing,
886 boolean useVarargs,
887 boolean operator) {
888 Symbol bestSoFar = methodNotFound;
889 return findMethod(env,
890 site,
891 name,
892 argtypes,
893 typeargtypes,
894 site.tsym.type,
895 true,
896 bestSoFar,
897 allowBoxing,
898 useVarargs,
899 operator);
900 }
901 // where
902 private Symbol findMethod(Env<AttrContext> env,
903 Type site,
904 Name name,
905 List<Type> argtypes,
906 List<Type> typeargtypes,
907 Type intype,
908 boolean abstractok,
909 Symbol bestSoFar,
910 boolean allowBoxing,
911 boolean useVarargs,
912 boolean operator) {
913 for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
914 while (ct.tag == TYPEVAR)
915 ct = ct.getUpperBound();
916 ClassSymbol c = (ClassSymbol)ct.tsym;
917 if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
918 abstractok = false;
919 for (Scope.Entry e = c.members().lookup(name);
920 e.scope != null;
921 e = e.next()) {
922 //- System.out.println(" e " + e.sym);
923 if (e.sym.kind == MTH &&
924 (e.sym.flags_field & SYNTHETIC) == 0) {
925 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
926 e.sym, bestSoFar,
927 allowBoxing,
928 useVarargs,
929 operator);
930 }
931 }
932 if (name == names.init)
933 break;
934 //- System.out.println(" - " + bestSoFar);
935 if (abstractok) {
936 Symbol concrete = methodNotFound;
937 if ((bestSoFar.flags() & ABSTRACT) == 0)
938 concrete = bestSoFar;
939 for (List<Type> l = types.interfaces(c.type);
940 l.nonEmpty();
941 l = l.tail) {
942 bestSoFar = findMethod(env, site, name, argtypes,
943 typeargtypes,
944 l.head, abstractok, bestSoFar,
945 allowBoxing, useVarargs, operator);
946 }
947 if (concrete != bestSoFar &&
948 concrete.kind < ERR && bestSoFar.kind < ERR &&
949 types.isSubSignature(concrete.type, bestSoFar.type))
950 bestSoFar = concrete;
951 }
952 }
953 return bestSoFar;
954 }
956 /** Find unqualified method matching given name, type and value arguments.
957 * @param env The current environment.
958 * @param name The method's name.
959 * @param argtypes The method's value arguments.
960 * @param typeargtypes The method's type arguments.
961 * @param allowBoxing Allow boxing conversions of arguments.
962 * @param useVarargs Box trailing arguments into an array for varargs.
963 */
964 Symbol findFun(Env<AttrContext> env, Name name,
965 List<Type> argtypes, List<Type> typeargtypes,
966 boolean allowBoxing, boolean useVarargs) {
967 Symbol bestSoFar = methodNotFound;
968 Symbol sym;
969 Env<AttrContext> env1 = env;
970 boolean staticOnly = false;
971 while (env1.outer != null) {
972 if (isStatic(env1)) staticOnly = true;
973 sym = findMethod(
974 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
975 allowBoxing, useVarargs, false);
976 if (sym.exists()) {
977 if (staticOnly &&
978 sym.kind == MTH &&
979 sym.owner.kind == TYP &&
980 (sym.flags() & STATIC) == 0) return new StaticError(sym);
981 else return sym;
982 } else if (sym.kind < bestSoFar.kind) {
983 bestSoFar = sym;
984 }
985 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
986 env1 = env1.outer;
987 }
989 sym = findMethod(env, syms.predefClass.type, name, argtypes,
990 typeargtypes, allowBoxing, useVarargs, false);
991 if (sym.exists())
992 return sym;
994 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
995 for (; e.scope != null; e = e.next()) {
996 sym = e.sym;
997 Type origin = e.getOrigin().owner.type;
998 if (sym.kind == MTH) {
999 if (e.sym.owner.type != origin)
1000 sym = sym.clone(e.getOrigin().owner);
1001 if (!isAccessible(env, origin, sym))
1002 sym = new AccessError(env, origin, sym);
1003 bestSoFar = selectBest(env, origin,
1004 argtypes, typeargtypes,
1005 sym, bestSoFar,
1006 allowBoxing, useVarargs, false);
1007 }
1008 }
1009 if (bestSoFar.exists())
1010 return bestSoFar;
1012 e = env.toplevel.starImportScope.lookup(name);
1013 for (; e.scope != null; e = e.next()) {
1014 sym = e.sym;
1015 Type origin = e.getOrigin().owner.type;
1016 if (sym.kind == MTH) {
1017 if (e.sym.owner.type != origin)
1018 sym = sym.clone(e.getOrigin().owner);
1019 if (!isAccessible(env, origin, sym))
1020 sym = new AccessError(env, origin, sym);
1021 bestSoFar = selectBest(env, origin,
1022 argtypes, typeargtypes,
1023 sym, bestSoFar,
1024 allowBoxing, useVarargs, false);
1025 }
1026 }
1027 return bestSoFar;
1028 }
1030 /** Load toplevel or member class with given fully qualified name and
1031 * verify that it is accessible.
1032 * @param env The current environment.
1033 * @param name The fully qualified name of the class to be loaded.
1034 */
1035 Symbol loadClass(Env<AttrContext> env, Name name) {
1036 try {
1037 ClassSymbol c = reader.loadClass(name);
1038 return isAccessible(env, c) ? c : new AccessError(c);
1039 } catch (ClassReader.BadClassFile err) {
1040 throw err;
1041 } catch (CompletionFailure ex) {
1042 return typeNotFound;
1043 }
1044 }
1046 /** Find qualified member type.
1047 * @param env The current environment.
1048 * @param site The original type from where the selection takes
1049 * place.
1050 * @param name The type's name.
1051 * @param c The class to search for the member type. This is
1052 * always a superclass or implemented interface of
1053 * site's class.
1054 */
1055 Symbol findMemberType(Env<AttrContext> env,
1056 Type site,
1057 Name name,
1058 TypeSymbol c) {
1059 Symbol bestSoFar = typeNotFound;
1060 Symbol sym;
1061 Scope.Entry e = c.members().lookup(name);
1062 while (e.scope != null) {
1063 if (e.sym.kind == TYP) {
1064 return isAccessible(env, site, e.sym)
1065 ? e.sym
1066 : new AccessError(env, site, e.sym);
1067 }
1068 e = e.next();
1069 }
1070 Type st = types.supertype(c.type);
1071 if (st != null && st.tag == CLASS) {
1072 sym = findMemberType(env, site, name, st.tsym);
1073 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1074 }
1075 for (List<Type> l = types.interfaces(c.type);
1076 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1077 l = l.tail) {
1078 sym = findMemberType(env, site, name, l.head.tsym);
1079 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1080 sym.owner != bestSoFar.owner)
1081 bestSoFar = new AmbiguityError(bestSoFar, sym);
1082 else if (sym.kind < bestSoFar.kind)
1083 bestSoFar = sym;
1084 }
1085 return bestSoFar;
1086 }
1088 /** Find a global type in given scope and load corresponding class.
1089 * @param env The current environment.
1090 * @param scope The scope in which to look for the type.
1091 * @param name The type's name.
1092 */
1093 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1094 Symbol bestSoFar = typeNotFound;
1095 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1096 Symbol sym = loadClass(env, e.sym.flatName());
1097 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1098 bestSoFar != sym)
1099 return new AmbiguityError(bestSoFar, sym);
1100 else if (sym.kind < bestSoFar.kind)
1101 bestSoFar = sym;
1102 }
1103 return bestSoFar;
1104 }
1106 /** Find an unqualified type symbol.
1107 * @param env The current environment.
1108 * @param name The type's name.
1109 */
1110 Symbol findType(Env<AttrContext> env, Name name) {
1111 Symbol bestSoFar = typeNotFound;
1112 Symbol sym;
1113 boolean staticOnly = false;
1114 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1115 if (isStatic(env1)) staticOnly = true;
1116 for (Scope.Entry e = env1.info.scope.lookup(name);
1117 e.scope != null;
1118 e = e.next()) {
1119 if (e.sym.kind == TYP) {
1120 if (staticOnly &&
1121 e.sym.type.tag == TYPEVAR &&
1122 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1123 return e.sym;
1124 }
1125 }
1127 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1128 env1.enclClass.sym);
1129 if (staticOnly && sym.kind == TYP &&
1130 sym.type.tag == CLASS &&
1131 sym.type.getEnclosingType().tag == CLASS &&
1132 env1.enclClass.sym.type.isParameterized() &&
1133 sym.type.getEnclosingType().isParameterized())
1134 return new StaticError(sym);
1135 else if (sym.exists()) return sym;
1136 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1138 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1139 if ((encl.sym.flags() & STATIC) != 0)
1140 staticOnly = true;
1141 }
1143 if (env.tree.getTag() != JCTree.IMPORT) {
1144 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1145 if (sym.exists()) return sym;
1146 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1148 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1149 if (sym.exists()) return sym;
1150 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1152 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1153 if (sym.exists()) return sym;
1154 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1155 }
1157 return bestSoFar;
1158 }
1160 /** Find an unqualified identifier which matches a specified kind set.
1161 * @param env The current environment.
1162 * @param name The indentifier's name.
1163 * @param kind Indicates the possible symbol kinds
1164 * (a subset of VAL, TYP, PCK).
1165 */
1166 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1167 Symbol bestSoFar = typeNotFound;
1168 Symbol sym;
1170 if ((kind & VAR) != 0) {
1171 sym = findVar(env, name);
1172 if (sym.exists()) return sym;
1173 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1174 }
1176 if ((kind & TYP) != 0) {
1177 sym = findType(env, name);
1178 if (sym.exists()) return sym;
1179 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1180 }
1182 if ((kind & PCK) != 0) return reader.enterPackage(name);
1183 else return bestSoFar;
1184 }
1186 /** Find an identifier in a package which matches a specified kind set.
1187 * @param env The current environment.
1188 * @param name The identifier's name.
1189 * @param kind Indicates the possible symbol kinds
1190 * (a nonempty subset of TYP, PCK).
1191 */
1192 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1193 Name name, int kind) {
1194 Name fullname = TypeSymbol.formFullName(name, pck);
1195 Symbol bestSoFar = typeNotFound;
1196 PackageSymbol pack = null;
1197 if ((kind & PCK) != 0) {
1198 pack = reader.enterPackage(fullname);
1199 if (pack.exists()) return pack;
1200 }
1201 if ((kind & TYP) != 0) {
1202 Symbol sym = loadClass(env, fullname);
1203 if (sym.exists()) {
1204 // don't allow programs to use flatnames
1205 if (name == sym.name) return sym;
1206 }
1207 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1208 }
1209 return (pack != null) ? pack : bestSoFar;
1210 }
1212 /** Find an identifier among the members of a given type `site'.
1213 * @param env The current environment.
1214 * @param site The type containing the symbol to be found.
1215 * @param name The identifier's name.
1216 * @param kind Indicates the possible symbol kinds
1217 * (a subset of VAL, TYP).
1218 */
1219 Symbol findIdentInType(Env<AttrContext> env, Type site,
1220 Name name, int kind) {
1221 Symbol bestSoFar = typeNotFound;
1222 Symbol sym;
1223 if ((kind & VAR) != 0) {
1224 sym = findField(env, site, name, site.tsym);
1225 if (sym.exists()) return sym;
1226 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1227 }
1229 if ((kind & TYP) != 0) {
1230 sym = findMemberType(env, site, name, site.tsym);
1231 if (sym.exists()) return sym;
1232 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1233 }
1234 return bestSoFar;
1235 }
1237 /* ***************************************************************************
1238 * Access checking
1239 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1240 * an error message in the process
1241 ****************************************************************************/
1243 /** If `sym' is a bad symbol: report error and return errSymbol
1244 * else pass through unchanged,
1245 * additional arguments duplicate what has been used in trying to find the
1246 * symbol (--> flyweight pattern). This improves performance since we
1247 * expect misses to happen frequently.
1248 *
1249 * @param sym The symbol that was found, or a ResolveError.
1250 * @param pos The position to use for error reporting.
1251 * @param site The original type from where the selection took place.
1252 * @param name The symbol's name.
1253 * @param argtypes The invocation's value arguments,
1254 * if we looked for a method.
1255 * @param typeargtypes The invocation's type arguments,
1256 * if we looked for a method.
1257 */
1258 Symbol access(Symbol sym,
1259 DiagnosticPosition pos,
1260 Symbol location,
1261 Type site,
1262 Name name,
1263 boolean qualified,
1264 List<Type> argtypes,
1265 List<Type> typeargtypes) {
1266 if (sym.kind >= AMBIGUOUS) {
1267 ResolveError errSym = (ResolveError)sym;
1268 if (!site.isErroneous() &&
1269 !Type.isErroneous(argtypes) &&
1270 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
1271 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1272 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1273 }
1274 return sym;
1275 }
1277 /** Same as original access(), but without location.
1278 */
1279 Symbol access(Symbol sym,
1280 DiagnosticPosition pos,
1281 Type site,
1282 Name name,
1283 boolean qualified,
1284 List<Type> argtypes,
1285 List<Type> typeargtypes) {
1286 return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1287 }
1289 /** Same as original access(), but without type arguments and arguments.
1290 */
1291 Symbol access(Symbol sym,
1292 DiagnosticPosition pos,
1293 Symbol location,
1294 Type site,
1295 Name name,
1296 boolean qualified) {
1297 if (sym.kind >= AMBIGUOUS)
1298 return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
1299 else
1300 return sym;
1301 }
1303 /** Same as original access(), but without location, type arguments and arguments.
1304 */
1305 Symbol access(Symbol sym,
1306 DiagnosticPosition pos,
1307 Type site,
1308 Name name,
1309 boolean qualified) {
1310 return access(sym, pos, site.tsym, site, name, qualified);
1311 }
1313 /** Check that sym is not an abstract method.
1314 */
1315 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1316 if ((sym.flags() & ABSTRACT) != 0)
1317 log.error(pos, "abstract.cant.be.accessed.directly",
1318 kindName(sym), sym, sym.location());
1319 }
1321 /* ***************************************************************************
1322 * Debugging
1323 ****************************************************************************/
1325 /** print all scopes starting with scope s and proceeding outwards.
1326 * used for debugging.
1327 */
1328 public void printscopes(Scope s) {
1329 while (s != null) {
1330 if (s.owner != null)
1331 System.err.print(s.owner + ": ");
1332 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1333 if ((e.sym.flags() & ABSTRACT) != 0)
1334 System.err.print("abstract ");
1335 System.err.print(e.sym + " ");
1336 }
1337 System.err.println();
1338 s = s.next;
1339 }
1340 }
1342 void printscopes(Env<AttrContext> env) {
1343 while (env.outer != null) {
1344 System.err.println("------------------------------");
1345 printscopes(env.info.scope);
1346 env = env.outer;
1347 }
1348 }
1350 public void printscopes(Type t) {
1351 while (t.tag == CLASS) {
1352 printscopes(t.tsym.members());
1353 t = types.supertype(t);
1354 }
1355 }
1357 /* ***************************************************************************
1358 * Name resolution
1359 * Naming conventions are as for symbol lookup
1360 * Unlike the find... methods these methods will report access errors
1361 ****************************************************************************/
1363 /** Resolve an unqualified (non-method) identifier.
1364 * @param pos The position to use for error reporting.
1365 * @param env The environment current at the identifier use.
1366 * @param name The identifier's name.
1367 * @param kind The set of admissible symbol kinds for the identifier.
1368 */
1369 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1370 Name name, int kind) {
1371 return access(
1372 findIdent(env, name, kind),
1373 pos, env.enclClass.sym.type, name, false);
1374 }
1376 /** Resolve an unqualified method identifier.
1377 * @param pos The position to use for error reporting.
1378 * @param env The environment current at the method invocation.
1379 * @param name The identifier's name.
1380 * @param argtypes The types of the invocation's value arguments.
1381 * @param typeargtypes The types of the invocation's type arguments.
1382 */
1383 Symbol resolveMethod(DiagnosticPosition pos,
1384 Env<AttrContext> env,
1385 Name name,
1386 List<Type> argtypes,
1387 List<Type> typeargtypes) {
1388 Symbol sym = startResolution();
1389 List<MethodResolutionPhase> steps = methodResolutionSteps;
1390 while (steps.nonEmpty() &&
1391 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1392 sym.kind >= ERRONEOUS) {
1393 currentStep = steps.head;
1394 sym = findFun(env, name, argtypes, typeargtypes,
1395 steps.head.isBoxingRequired,
1396 env.info.varArgs = steps.head.isVarargsRequired);
1397 methodResolutionCache.put(steps.head, sym);
1398 steps = steps.tail;
1399 }
1400 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1401 MethodResolutionPhase errPhase =
1402 firstErroneousResolutionPhase();
1403 sym = access(methodResolutionCache.get(errPhase),
1404 pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1405 env.info.varArgs = errPhase.isVarargsRequired;
1406 }
1407 return sym;
1408 }
1410 private Symbol startResolution() {
1411 wrongMethod.clear();
1412 wrongMethods.clear();
1413 return methodNotFound;
1414 }
1416 /** Resolve a qualified method identifier
1417 * @param pos The position to use for error reporting.
1418 * @param env The environment current at the method invocation.
1419 * @param site The type of the qualifying expression, in which
1420 * identifier is searched.
1421 * @param name The identifier's name.
1422 * @param argtypes The types of the invocation's value arguments.
1423 * @param typeargtypes The types of the invocation's type arguments.
1424 */
1425 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1426 Type site, Name name, List<Type> argtypes,
1427 List<Type> typeargtypes) {
1428 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
1429 }
1430 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1431 Symbol location, Type site, Name name, List<Type> argtypes,
1432 List<Type> typeargtypes) {
1433 Symbol sym = startResolution();
1434 List<MethodResolutionPhase> steps = methodResolutionSteps;
1435 while (steps.nonEmpty() &&
1436 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1437 sym.kind >= ERRONEOUS) {
1438 currentStep = steps.head;
1439 sym = findMethod(env, site, name, argtypes, typeargtypes,
1440 steps.head.isBoxingRequired(),
1441 env.info.varArgs = steps.head.isVarargsRequired(), false);
1442 methodResolutionCache.put(steps.head, sym);
1443 steps = steps.tail;
1444 }
1445 if (sym.kind >= AMBIGUOUS) {
1446 if (site.tsym.isPolymorphicSignatureGeneric()) {
1447 //polymorphic receiver - synthesize new method symbol
1448 env.info.varArgs = false;
1449 sym = findPolymorphicSignatureInstance(env,
1450 site, name, null, argtypes);
1451 }
1452 else {
1453 //if nothing is found return the 'first' error
1454 MethodResolutionPhase errPhase =
1455 firstErroneousResolutionPhase();
1456 sym = access(methodResolutionCache.get(errPhase),
1457 pos, location, site, name, true, argtypes, typeargtypes);
1458 env.info.varArgs = errPhase.isVarargsRequired;
1459 }
1460 } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
1461 //non-instantiated polymorphic signature - synthesize new method symbol
1462 env.info.varArgs = false;
1463 sym = findPolymorphicSignatureInstance(env,
1464 site, name, (MethodSymbol)sym, argtypes);
1465 }
1466 return sym;
1467 }
1469 /** Find or create an implicit method of exactly the given type (after erasure).
1470 * Searches in a side table, not the main scope of the site.
1471 * This emulates the lookup process required by JSR 292 in JVM.
1472 * @param env Attribution environment
1473 * @param site The original type from where the selection takes place.
1474 * @param name The method's name.
1475 * @param spMethod A template for the implicit method, or null.
1476 * @param argtypes The required argument types.
1477 * @param typeargtypes The required type arguments.
1478 */
1479 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
1480 Name name,
1481 MethodSymbol spMethod, // sig. poly. method or null if none
1482 List<Type> argtypes) {
1483 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
1484 site, name, spMethod, argtypes);
1485 long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
1486 (spMethod != null ?
1487 spMethod.flags() & Flags.AccessFlags :
1488 Flags.PUBLIC | Flags.STATIC);
1489 Symbol m = null;
1490 for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
1491 e.scope != null;
1492 e = e.next()) {
1493 Symbol sym = e.sym;
1494 if (types.isSameType(mtype, sym.type) &&
1495 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
1496 types.isSameType(sym.owner.type, site)) {
1497 m = sym;
1498 break;
1499 }
1500 }
1501 if (m == null) {
1502 // create the desired method
1503 m = new MethodSymbol(flags, name, mtype, site.tsym);
1504 polymorphicSignatureScope.enter(m);
1505 }
1506 return m;
1507 }
1509 /** Resolve a qualified method identifier, throw a fatal error if not
1510 * found.
1511 * @param pos The position to use for error reporting.
1512 * @param env The environment current at the method invocation.
1513 * @param site The type of the qualifying expression, in which
1514 * identifier is searched.
1515 * @param name The identifier's name.
1516 * @param argtypes The types of the invocation's value arguments.
1517 * @param typeargtypes The types of the invocation's type arguments.
1518 */
1519 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
1520 Type site, Name name,
1521 List<Type> argtypes,
1522 List<Type> typeargtypes) {
1523 Symbol sym = resolveQualifiedMethod(
1524 pos, env, site.tsym, site, name, argtypes, typeargtypes);
1525 if (sym.kind == MTH) return (MethodSymbol)sym;
1526 else throw new FatalError(
1527 diags.fragment("fatal.err.cant.locate.meth",
1528 name));
1529 }
1531 /** Resolve constructor.
1532 * @param pos The position to use for error reporting.
1533 * @param env The environment current at the constructor invocation.
1534 * @param site The type of class for which a constructor is searched.
1535 * @param argtypes The types of the constructor invocation's value
1536 * arguments.
1537 * @param typeargtypes The types of the constructor invocation's type
1538 * arguments.
1539 */
1540 Symbol resolveConstructor(DiagnosticPosition pos,
1541 Env<AttrContext> env,
1542 Type site,
1543 List<Type> argtypes,
1544 List<Type> typeargtypes) {
1545 Symbol sym = startResolution();
1546 List<MethodResolutionPhase> steps = methodResolutionSteps;
1547 while (steps.nonEmpty() &&
1548 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1549 sym.kind >= ERRONEOUS) {
1550 currentStep = steps.head;
1551 sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
1552 steps.head.isBoxingRequired(),
1553 env.info.varArgs = steps.head.isVarargsRequired());
1554 methodResolutionCache.put(steps.head, sym);
1555 steps = steps.tail;
1556 }
1557 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1558 MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
1559 sym = access(methodResolutionCache.get(errPhase),
1560 pos, site, names.init, true, argtypes, typeargtypes);
1561 env.info.varArgs = errPhase.isVarargsRequired();
1562 }
1563 return sym;
1564 }
1566 /** Resolve constructor using diamond inference.
1567 * @param pos The position to use for error reporting.
1568 * @param env The environment current at the constructor invocation.
1569 * @param site The type of class for which a constructor is searched.
1570 * The scope of this class has been touched in attribution.
1571 * @param argtypes The types of the constructor invocation's value
1572 * arguments.
1573 * @param typeargtypes The types of the constructor invocation's type
1574 * arguments.
1575 */
1576 Symbol resolveDiamond(DiagnosticPosition pos,
1577 Env<AttrContext> env,
1578 Type site,
1579 List<Type> argtypes,
1580 List<Type> typeargtypes) {
1581 Symbol sym = startResolution();
1582 List<MethodResolutionPhase> steps = methodResolutionSteps;
1583 while (steps.nonEmpty() &&
1584 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1585 sym.kind >= ERRONEOUS) {
1586 currentStep = steps.head;
1587 sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
1588 steps.head.isBoxingRequired(),
1589 env.info.varArgs = steps.head.isVarargsRequired());
1590 methodResolutionCache.put(steps.head, sym);
1591 steps = steps.tail;
1592 }
1593 if (sym.kind >= AMBIGUOUS) {
1594 final JCDiagnostic details = sym.kind == WRONG_MTH ?
1595 ((InapplicableSymbolError)sym).explanation :
1596 null;
1597 Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
1598 @Override
1599 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
1600 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
1601 String key = details == null ?
1602 "cant.apply.diamond" :
1603 "cant.apply.diamond.1";
1604 return diags.create(dkind, log.currentSource(), pos, key,
1605 diags.fragment("diamond", site.tsym), details);
1606 }
1607 };
1608 MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
1609 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
1610 env.info.varArgs = errPhase.isVarargsRequired();
1611 }
1612 return sym;
1613 }
1615 /** Resolve constructor.
1616 * @param pos The position to use for error reporting.
1617 * @param env The environment current at the constructor invocation.
1618 * @param site The type of class for which a constructor is searched.
1619 * @param argtypes The types of the constructor invocation's value
1620 * arguments.
1621 * @param typeargtypes The types of the constructor invocation's type
1622 * arguments.
1623 * @param allowBoxing Allow boxing and varargs conversions.
1624 * @param useVarargs Box trailing arguments into an array for varargs.
1625 */
1626 Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1627 Type site, List<Type> argtypes,
1628 List<Type> typeargtypes,
1629 boolean allowBoxing,
1630 boolean useVarargs) {
1631 Symbol sym = findMethod(env, site,
1632 names.init, argtypes,
1633 typeargtypes, allowBoxing,
1634 useVarargs, false);
1635 chk.checkDeprecated(pos, env.info.scope.owner, sym);
1636 return sym;
1637 }
1639 /** Resolve a constructor, throw a fatal error if not found.
1640 * @param pos The position to use for error reporting.
1641 * @param env The environment current at the method invocation.
1642 * @param site The type to be constructed.
1643 * @param argtypes The types of the invocation's value arguments.
1644 * @param typeargtypes The types of the invocation's type arguments.
1645 */
1646 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1647 Type site,
1648 List<Type> argtypes,
1649 List<Type> typeargtypes) {
1650 Symbol sym = resolveConstructor(
1651 pos, env, site, argtypes, typeargtypes);
1652 if (sym.kind == MTH) return (MethodSymbol)sym;
1653 else throw new FatalError(
1654 diags.fragment("fatal.err.cant.locate.ctor", site));
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 argtypes The types of the operands.
1662 */
1663 Symbol resolveOperator(DiagnosticPosition pos, int optag,
1664 Env<AttrContext> env, List<Type> argtypes) {
1665 Name name = treeinfo.operatorName(optag);
1666 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
1667 null, false, false, true);
1668 if (boxingEnabled && sym.kind >= WRONG_MTHS)
1669 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1670 null, true, false, true);
1671 return access(sym, pos, env.enclClass.sym.type, name,
1672 false, argtypes, null);
1673 }
1675 /** Resolve operator.
1676 * @param pos The position to use for error reporting.
1677 * @param optag The tag of the operation tree.
1678 * @param env The environment current at the operation.
1679 * @param arg The type of the operand.
1680 */
1681 Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
1682 return resolveOperator(pos, optag, env, List.of(arg));
1683 }
1685 /** Resolve binary operator.
1686 * @param pos The position to use for error reporting.
1687 * @param optag The tag of the operation tree.
1688 * @param env The environment current at the operation.
1689 * @param left The types of the left operand.
1690 * @param right The types of the right operand.
1691 */
1692 Symbol resolveBinaryOperator(DiagnosticPosition pos,
1693 int optag,
1694 Env<AttrContext> env,
1695 Type left,
1696 Type right) {
1697 return resolveOperator(pos, optag, env, List.of(left, right));
1698 }
1700 /**
1701 * Resolve `c.name' where name == this or name == super.
1702 * @param pos The position to use for error reporting.
1703 * @param env The environment current at the expression.
1704 * @param c The qualifier.
1705 * @param name The identifier's name.
1706 */
1707 Symbol resolveSelf(DiagnosticPosition pos,
1708 Env<AttrContext> env,
1709 TypeSymbol c,
1710 Name name) {
1711 Env<AttrContext> env1 = env;
1712 boolean staticOnly = false;
1713 while (env1.outer != null) {
1714 if (isStatic(env1)) staticOnly = true;
1715 if (env1.enclClass.sym == c) {
1716 Symbol sym = env1.info.scope.lookup(name).sym;
1717 if (sym != null) {
1718 if (staticOnly) sym = new StaticError(sym);
1719 return access(sym, pos, env.enclClass.sym.type,
1720 name, true);
1721 }
1722 }
1723 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1724 env1 = env1.outer;
1725 }
1726 log.error(pos, "not.encl.class", c);
1727 return syms.errSymbol;
1728 }
1730 /**
1731 * Resolve `c.this' for an enclosing class c that contains the
1732 * named member.
1733 * @param pos The position to use for error reporting.
1734 * @param env The environment current at the expression.
1735 * @param member The member that must be contained in the result.
1736 */
1737 Symbol resolveSelfContaining(DiagnosticPosition pos,
1738 Env<AttrContext> env,
1739 Symbol member,
1740 boolean isSuperCall) {
1741 Name name = names._this;
1742 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
1743 boolean staticOnly = false;
1744 if (env1 != null) {
1745 while (env1 != null && env1.outer != null) {
1746 if (isStatic(env1)) staticOnly = true;
1747 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
1748 Symbol sym = env1.info.scope.lookup(name).sym;
1749 if (sym != null) {
1750 if (staticOnly) sym = new StaticError(sym);
1751 return access(sym, pos, env.enclClass.sym.type,
1752 name, true);
1753 }
1754 }
1755 if ((env1.enclClass.sym.flags() & STATIC) != 0)
1756 staticOnly = true;
1757 env1 = env1.outer;
1758 }
1759 }
1760 log.error(pos, "encl.class.required", member);
1761 return syms.errSymbol;
1762 }
1764 /**
1765 * Resolve an appropriate implicit this instance for t's container.
1766 * JLS2 8.8.5.1 and 15.9.2
1767 */
1768 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
1769 return resolveImplicitThis(pos, env, t, false);
1770 }
1772 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
1773 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
1774 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
1775 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
1776 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
1777 log.error(pos, "cant.ref.before.ctor.called", "this");
1778 return thisType;
1779 }
1781 /* ***************************************************************************
1782 * ResolveError classes, indicating error situations when accessing symbols
1783 ****************************************************************************/
1785 public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
1786 AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
1787 logResolveError(error, tree.pos(), type.getEnclosingType().tsym, type.getEnclosingType(), null, null, null);
1788 }
1789 //where
1790 private void logResolveError(ResolveError error,
1791 DiagnosticPosition pos,
1792 Symbol location,
1793 Type site,
1794 Name name,
1795 List<Type> argtypes,
1796 List<Type> typeargtypes) {
1797 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
1798 pos, location, site, name, argtypes, typeargtypes);
1799 if (d != null) {
1800 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
1801 log.report(d);
1802 }
1803 }
1805 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
1807 public Object methodArguments(List<Type> argtypes) {
1808 return argtypes.isEmpty() ? noArgs : argtypes;
1809 }
1811 /**
1812 * Root class for resolution errors. Subclass of ResolveError
1813 * represent a different kinds of resolution error - as such they must
1814 * specify how they map into concrete compiler diagnostics.
1815 */
1816 private abstract class ResolveError extends Symbol {
1818 /** The name of the kind of error, for debugging only. */
1819 final String debugName;
1821 ResolveError(int kind, String debugName) {
1822 super(kind, 0, null, null, null);
1823 this.debugName = debugName;
1824 }
1826 @Override
1827 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1828 throw new AssertionError();
1829 }
1831 @Override
1832 public String toString() {
1833 return debugName;
1834 }
1836 @Override
1837 public boolean exists() {
1838 return false;
1839 }
1841 /**
1842 * Create an external representation for this erroneous symbol to be
1843 * used during attribution - by default this returns the symbol of a
1844 * brand new error type which stores the original type found
1845 * during resolution.
1846 *
1847 * @param name the name used during resolution
1848 * @param location the location from which the symbol is accessed
1849 */
1850 protected Symbol access(Name name, TypeSymbol location) {
1851 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
1852 }
1854 /**
1855 * Create a diagnostic representing this resolution error.
1856 *
1857 * @param dkind The kind of the diagnostic to be created (e.g error).
1858 * @param pos The position to be used for error reporting.
1859 * @param site The original type from where the selection took place.
1860 * @param name The name of the symbol to be resolved.
1861 * @param argtypes The invocation's value arguments,
1862 * if we looked for a method.
1863 * @param typeargtypes The invocation's type arguments,
1864 * if we looked for a method.
1865 */
1866 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1867 DiagnosticPosition pos,
1868 Symbol location,
1869 Type site,
1870 Name name,
1871 List<Type> argtypes,
1872 List<Type> typeargtypes);
1874 /**
1875 * A name designates an operator if it consists
1876 * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
1877 */
1878 boolean isOperator(Name name) {
1879 int i = 0;
1880 while (i < name.getByteLength() &&
1881 "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
1882 return i > 0 && i == name.getByteLength();
1883 }
1884 }
1886 /**
1887 * This class is the root class of all resolution errors caused by
1888 * an invalid symbol being found during resolution.
1889 */
1890 abstract class InvalidSymbolError extends ResolveError {
1892 /** The invalid symbol found during resolution */
1893 Symbol sym;
1895 InvalidSymbolError(int kind, Symbol sym, String debugName) {
1896 super(kind, debugName);
1897 this.sym = sym;
1898 }
1900 @Override
1901 public boolean exists() {
1902 return true;
1903 }
1905 @Override
1906 public String toString() {
1907 return super.toString() + " wrongSym=" + sym;
1908 }
1910 @Override
1911 public Symbol access(Name name, TypeSymbol location) {
1912 if (sym.kind >= AMBIGUOUS)
1913 return ((ResolveError)sym).access(name, location);
1914 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
1915 return types.createErrorType(name, location, sym.type).tsym;
1916 else
1917 return sym;
1918 }
1919 }
1921 /**
1922 * InvalidSymbolError error class indicating that a symbol matching a
1923 * given name does not exists in a given site.
1924 */
1925 class SymbolNotFoundError extends ResolveError {
1927 SymbolNotFoundError(int kind) {
1928 super(kind, "symbol not found error");
1929 }
1931 @Override
1932 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1933 DiagnosticPosition pos,
1934 Symbol location,
1935 Type site,
1936 Name name,
1937 List<Type> argtypes,
1938 List<Type> typeargtypes) {
1939 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
1940 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
1941 if (name == names.error)
1942 return null;
1944 if (isOperator(name)) {
1945 boolean isUnaryOp = argtypes.size() == 1;
1946 String key = argtypes.size() == 1 ?
1947 "operator.cant.be.applied" :
1948 "operator.cant.be.applied.1";
1949 Type first = argtypes.head;
1950 Type second = !isUnaryOp ? argtypes.tail.head : null;
1951 return diags.create(dkind, log.currentSource(), pos,
1952 key, name, first, second);
1953 }
1954 boolean hasLocation = false;
1955 if (location == null) {
1956 location = site.tsym;
1957 }
1958 if (!location.name.isEmpty()) {
1959 if (location.kind == PCK && !site.tsym.exists()) {
1960 return diags.create(dkind, log.currentSource(), pos,
1961 "doesnt.exist", location);
1962 }
1963 hasLocation = !location.name.equals(names._this) &&
1964 !location.name.equals(names._super);
1965 }
1966 boolean isConstructor = kind == ABSENT_MTH &&
1967 name == names.table.names.init;
1968 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
1969 Name idname = isConstructor ? site.tsym.name : name;
1970 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
1971 if (hasLocation) {
1972 return diags.create(dkind, log.currentSource(), pos,
1973 errKey, kindname, idname, //symbol kindname, name
1974 typeargtypes, argtypes, //type parameters and arguments (if any)
1975 getLocationDiag(location, site)); //location kindname, type
1976 }
1977 else {
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 }
1982 }
1983 //where
1984 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
1985 String key = "cant.resolve";
1986 String suffix = hasLocation ? ".location" : "";
1987 switch (kindname) {
1988 case METHOD:
1989 case CONSTRUCTOR: {
1990 suffix += ".args";
1991 suffix += hasTypeArgs ? ".params" : "";
1992 }
1993 }
1994 return key + suffix;
1995 }
1996 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
1997 if (location.kind == VAR) {
1998 return diags.fragment("location.1",
1999 kindName(location),
2000 location,
2001 location.type);
2002 } else {
2003 return diags.fragment("location",
2004 typeKindName(site),
2005 site,
2006 null);
2007 }
2008 }
2009 }
2011 /**
2012 * InvalidSymbolError error class indicating that a given symbol
2013 * (either a method, a constructor or an operand) is not applicable
2014 * given an actual arguments/type argument list.
2015 */
2016 class InapplicableSymbolError extends InvalidSymbolError {
2018 /** An auxiliary explanation set in case of instantiation errors. */
2019 JCDiagnostic explanation;
2021 InapplicableSymbolError(Symbol sym) {
2022 super(WRONG_MTH, sym, "inapplicable symbol error");
2023 }
2025 /** Update sym and explanation and return this.
2026 */
2027 InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
2028 this.sym = sym;
2029 if (this.sym == sym && explanation != null)
2030 this.explanation = explanation; //update the details
2031 return this;
2032 }
2034 /** Update sym and return this.
2035 */
2036 InapplicableSymbolError setWrongSym(Symbol sym) {
2037 this.sym = sym;
2038 return this;
2039 }
2041 @Override
2042 public String toString() {
2043 return super.toString() + " explanation=" + explanation;
2044 }
2046 @Override
2047 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2048 DiagnosticPosition pos,
2049 Symbol location,
2050 Type site,
2051 Name name,
2052 List<Type> argtypes,
2053 List<Type> typeargtypes) {
2054 if (name == names.error)
2055 return null;
2057 if (isOperator(name)) {
2058 boolean isUnaryOp = argtypes.size() == 1;
2059 String key = argtypes.size() == 1 ?
2060 "operator.cant.be.applied" :
2061 "operator.cant.be.applied.1";
2062 Type first = argtypes.head;
2063 Type second = !isUnaryOp ? argtypes.tail.head : null;
2064 return diags.create(dkind, log.currentSource(), pos,
2065 key, name, first, second);
2066 }
2067 else {
2068 Symbol ws = sym.asMemberOf(site, types);
2069 return diags.create(dkind, log.currentSource(), pos,
2070 "cant.apply.symbol" + (explanation != null ? ".1" : ""),
2071 kindName(ws),
2072 ws.name == names.init ? ws.owner.name : ws.name,
2073 methodArguments(ws.type.getParameterTypes()),
2074 methodArguments(argtypes),
2075 kindName(ws.owner),
2076 ws.owner.type,
2077 explanation);
2078 }
2079 }
2081 void clear() {
2082 explanation = null;
2083 }
2085 @Override
2086 public Symbol access(Name name, TypeSymbol location) {
2087 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2088 }
2089 }
2091 /**
2092 * ResolveError error class indicating that a set of symbols
2093 * (either methods, constructors or operands) is not applicable
2094 * given an actual arguments/type argument list.
2095 */
2096 class InapplicableSymbolsError extends ResolveError {
2098 private List<Candidate> candidates = List.nil();
2100 InapplicableSymbolsError(Symbol sym) {
2101 super(WRONG_MTHS, "inapplicable symbols");
2102 }
2104 @Override
2105 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2106 DiagnosticPosition pos,
2107 Symbol location,
2108 Type site,
2109 Name name,
2110 List<Type> argtypes,
2111 List<Type> typeargtypes) {
2112 if (candidates.nonEmpty()) {
2113 JCDiagnostic err = diags.create(dkind,
2114 log.currentSource(),
2115 pos,
2116 "cant.apply.symbols",
2117 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2118 getName(),
2119 argtypes);
2120 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2121 } else {
2122 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2123 location, site, name, argtypes, typeargtypes);
2124 }
2125 }
2127 //where
2128 List<JCDiagnostic> candidateDetails(Type site) {
2129 List<JCDiagnostic> details = List.nil();
2130 for (Candidate c : candidates)
2131 details = details.prepend(c.getDiagnostic(site));
2132 return details.reverse();
2133 }
2135 Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
2136 Candidate c = new Candidate(currentStep, sym, details);
2137 if (c.isValid() && !candidates.contains(c))
2138 candidates = candidates.append(c);
2139 return this;
2140 }
2142 void clear() {
2143 candidates = List.nil();
2144 }
2146 private Name getName() {
2147 Symbol sym = candidates.head.sym;
2148 return sym.name == names.init ?
2149 sym.owner.name :
2150 sym.name;
2151 }
2153 private class Candidate {
2155 final MethodResolutionPhase step;
2156 final Symbol sym;
2157 final JCDiagnostic details;
2159 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
2160 this.step = step;
2161 this.sym = sym;
2162 this.details = details;
2163 }
2165 JCDiagnostic getDiagnostic(Type site) {
2166 return diags.fragment("inapplicable.method",
2167 Kinds.kindName(sym),
2168 sym.location(site, types),
2169 sym.asMemberOf(site, types),
2170 details);
2171 }
2173 @Override
2174 public boolean equals(Object o) {
2175 if (o instanceof Candidate) {
2176 Symbol s1 = this.sym;
2177 Symbol s2 = ((Candidate)o).sym;
2178 if ((s1 != s2 &&
2179 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2180 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2181 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2182 return true;
2183 }
2184 return false;
2185 }
2187 boolean isValid() {
2188 return (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
2189 (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
2190 }
2191 }
2192 }
2194 /**
2195 * An InvalidSymbolError error class indicating that a symbol is not
2196 * accessible from a given site
2197 */
2198 class AccessError extends InvalidSymbolError {
2200 private Env<AttrContext> env;
2201 private Type site;
2203 AccessError(Symbol sym) {
2204 this(null, null, sym);
2205 }
2207 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2208 super(HIDDEN, sym, "access error");
2209 this.env = env;
2210 this.site = site;
2211 if (debugResolve)
2212 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2213 }
2215 @Override
2216 public boolean exists() {
2217 return false;
2218 }
2220 @Override
2221 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2222 DiagnosticPosition pos,
2223 Symbol location,
2224 Type site,
2225 Name name,
2226 List<Type> argtypes,
2227 List<Type> typeargtypes) {
2228 if (sym.owner.type.tag == ERROR)
2229 return null;
2231 if (sym.name == names.init && sym.owner != site.tsym) {
2232 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2233 pos, location, site, name, argtypes, typeargtypes);
2234 }
2235 else if ((sym.flags() & PUBLIC) != 0
2236 || (env != null && this.site != null
2237 && !isAccessible(env, this.site))) {
2238 return diags.create(dkind, log.currentSource(),
2239 pos, "not.def.access.class.intf.cant.access",
2240 sym, sym.location());
2241 }
2242 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2243 return diags.create(dkind, log.currentSource(),
2244 pos, "report.access", sym,
2245 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2246 sym.location());
2247 }
2248 else {
2249 return diags.create(dkind, log.currentSource(),
2250 pos, "not.def.public.cant.access", sym, sym.location());
2251 }
2252 }
2253 }
2255 /**
2256 * InvalidSymbolError error class indicating that an instance member
2257 * has erroneously been accessed from a static context.
2258 */
2259 class StaticError extends InvalidSymbolError {
2261 StaticError(Symbol sym) {
2262 super(STATICERR, sym, "static error");
2263 }
2265 @Override
2266 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2267 DiagnosticPosition pos,
2268 Symbol location,
2269 Type site,
2270 Name name,
2271 List<Type> argtypes,
2272 List<Type> typeargtypes) {
2273 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2274 ? types.erasure(sym.type).tsym
2275 : sym);
2276 return diags.create(dkind, log.currentSource(), pos,
2277 "non-static.cant.be.ref", kindName(sym), errSym);
2278 }
2279 }
2281 /**
2282 * InvalidSymbolError error class indicating that a pair of symbols
2283 * (either methods, constructors or operands) are ambiguous
2284 * given an actual arguments/type argument list.
2285 */
2286 class AmbiguityError extends InvalidSymbolError {
2288 /** The other maximally specific symbol */
2289 Symbol sym2;
2291 AmbiguityError(Symbol sym1, Symbol sym2) {
2292 super(AMBIGUOUS, sym1, "ambiguity error");
2293 this.sym2 = sym2;
2294 }
2296 @Override
2297 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2298 DiagnosticPosition pos,
2299 Symbol location,
2300 Type site,
2301 Name name,
2302 List<Type> argtypes,
2303 List<Type> typeargtypes) {
2304 AmbiguityError pair = this;
2305 while (true) {
2306 if (pair.sym.kind == AMBIGUOUS)
2307 pair = (AmbiguityError)pair.sym;
2308 else if (pair.sym2.kind == AMBIGUOUS)
2309 pair = (AmbiguityError)pair.sym2;
2310 else break;
2311 }
2312 Name sname = pair.sym.name;
2313 if (sname == names.init) sname = pair.sym.owner.name;
2314 return diags.create(dkind, log.currentSource(),
2315 pos, "ref.ambiguous", sname,
2316 kindName(pair.sym),
2317 pair.sym,
2318 pair.sym.location(site, types),
2319 kindName(pair.sym2),
2320 pair.sym2,
2321 pair.sym2.location(site, types));
2322 }
2323 }
2325 enum MethodResolutionPhase {
2326 BASIC(false, false),
2327 BOX(true, false),
2328 VARARITY(true, true);
2330 boolean isBoxingRequired;
2331 boolean isVarargsRequired;
2333 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2334 this.isBoxingRequired = isBoxingRequired;
2335 this.isVarargsRequired = isVarargsRequired;
2336 }
2338 public boolean isBoxingRequired() {
2339 return isBoxingRequired;
2340 }
2342 public boolean isVarargsRequired() {
2343 return isVarargsRequired;
2344 }
2346 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2347 return (varargsEnabled || !isVarargsRequired) &&
2348 (boxingEnabled || !isBoxingRequired);
2349 }
2350 }
2352 private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
2353 new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
2355 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2357 private MethodResolutionPhase currentStep = null;
2359 private MethodResolutionPhase firstErroneousResolutionPhase() {
2360 MethodResolutionPhase bestSoFar = BASIC;
2361 Symbol sym = methodNotFound;
2362 List<MethodResolutionPhase> steps = methodResolutionSteps;
2363 while (steps.nonEmpty() &&
2364 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2365 sym.kind >= WRONG_MTHS) {
2366 sym = methodResolutionCache.get(steps.head);
2367 bestSoFar = steps.head;
2368 steps = steps.tail;
2369 }
2370 return bestSoFar;
2371 }
2372 }