Fri, 28 Jan 2011 12:03:49 +0000
6313164: javac generates code that fails byte code verification for the varargs feature
Summary: method applicability check should fail if formal varargs element type is not accessible
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 MethodSymbol result = new MethodSymbol(
780 mostSpecific.flags(),
781 mostSpecific.name,
782 null,
783 mostSpecific.owner) {
784 @Override
785 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
786 if (origin == site.tsym)
787 return this;
788 else
789 return super.implementation(origin, types, checkResult);
790 }
791 };
792 result.type = (Type)mostSpecific.type.clone();
793 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
794 mt2.getThrownTypes()));
795 return result;
796 }
797 if (m1SignatureMoreSpecific) return m1;
798 if (m2SignatureMoreSpecific) return m2;
799 return ambiguityError(m1, m2);
800 case AMBIGUOUS:
801 AmbiguityError e = (AmbiguityError)m2;
802 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
803 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
804 if (err1 == err2) return err1;
805 if (err1 == e.sym && err2 == e.sym2) return m2;
806 if (err1 instanceof AmbiguityError &&
807 err2 instanceof AmbiguityError &&
808 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
809 return ambiguityError(m1, m2);
810 else
811 return ambiguityError(err1, err2);
812 default:
813 throw new AssertionError();
814 }
815 }
816 //where
817 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
818 noteWarner.clear();
819 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
820 return (instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
821 allowBoxing, false, noteWarner) != null ||
822 useVarargs && instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
823 allowBoxing, true, noteWarner) != null) &&
824 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
825 }
826 //where
827 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
828 List<Type> fromArgs = from.type.getParameterTypes();
829 List<Type> toArgs = to.type.getParameterTypes();
830 if (useVarargs &&
831 (from.flags() & VARARGS) != 0 &&
832 (to.flags() & VARARGS) != 0) {
833 Type varargsTypeFrom = fromArgs.last();
834 Type varargsTypeTo = toArgs.last();
835 ListBuffer<Type> args = ListBuffer.lb();
836 if (toArgs.length() < fromArgs.length()) {
837 //if we are checking a varargs method 'from' against another varargs
838 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
839 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
840 //until 'to' signature has the same arity as 'from')
841 while (fromArgs.head != varargsTypeFrom) {
842 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
843 fromArgs = fromArgs.tail;
844 toArgs = toArgs.head == varargsTypeTo ?
845 toArgs :
846 toArgs.tail;
847 }
848 } else {
849 //formal argument list is same as original list where last
850 //argument (array type) is removed
851 args.appendList(toArgs.reverse().tail.reverse());
852 }
853 //append varargs element type as last synthetic formal
854 args.append(types.elemtype(varargsTypeTo));
855 MethodSymbol msym = new MethodSymbol(to.flags_field,
856 to.name,
857 (Type)to.type.clone(), //see: 6990136
858 to.owner);
859 MethodType mtype = msym.type.asMethodType();
860 mtype.argtypes = args.toList();
861 return msym;
862 } else {
863 return to;
864 }
865 }
866 //where
867 Symbol ambiguityError(Symbol m1, Symbol m2) {
868 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
869 return (m1.flags() & CLASH) == 0 ? m1 : m2;
870 } else {
871 return new AmbiguityError(m1, m2);
872 }
873 }
875 /** Find best qualified method matching given name, type and value
876 * arguments.
877 * @param env The current environment.
878 * @param site The original type from where the selection
879 * takes place.
880 * @param name The method's name.
881 * @param argtypes The method's value arguments.
882 * @param typeargtypes The method's type arguments
883 * @param allowBoxing Allow boxing conversions of arguments.
884 * @param useVarargs Box trailing arguments into an array for varargs.
885 */
886 Symbol findMethod(Env<AttrContext> env,
887 Type site,
888 Name name,
889 List<Type> argtypes,
890 List<Type> typeargtypes,
891 boolean allowBoxing,
892 boolean useVarargs,
893 boolean operator) {
894 Symbol bestSoFar = methodNotFound;
895 return findMethod(env,
896 site,
897 name,
898 argtypes,
899 typeargtypes,
900 site.tsym.type,
901 true,
902 bestSoFar,
903 allowBoxing,
904 useVarargs,
905 operator);
906 }
907 // where
908 private Symbol findMethod(Env<AttrContext> env,
909 Type site,
910 Name name,
911 List<Type> argtypes,
912 List<Type> typeargtypes,
913 Type intype,
914 boolean abstractok,
915 Symbol bestSoFar,
916 boolean allowBoxing,
917 boolean useVarargs,
918 boolean operator) {
919 for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
920 while (ct.tag == TYPEVAR)
921 ct = ct.getUpperBound();
922 ClassSymbol c = (ClassSymbol)ct.tsym;
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);
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 if ((sym.flags() & DEPRECATED) != 0 &&
1642 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
1643 env.info.scope.owner.outermostClass() != sym.outermostClass())
1644 chk.warnDeprecated(pos, sym);
1645 return sym;
1646 }
1648 /** Resolve a constructor, throw a fatal error if not found.
1649 * @param pos The position to use for error reporting.
1650 * @param env The environment current at the method invocation.
1651 * @param site The type to be constructed.
1652 * @param argtypes The types of the invocation's value arguments.
1653 * @param typeargtypes The types of the invocation's type arguments.
1654 */
1655 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1656 Type site,
1657 List<Type> argtypes,
1658 List<Type> typeargtypes) {
1659 Symbol sym = resolveConstructor(
1660 pos, env, site, argtypes, typeargtypes);
1661 if (sym.kind == MTH) return (MethodSymbol)sym;
1662 else throw new FatalError(
1663 diags.fragment("fatal.err.cant.locate.ctor", site));
1664 }
1666 /** Resolve operator.
1667 * @param pos The position to use for error reporting.
1668 * @param optag The tag of the operation tree.
1669 * @param env The environment current at the operation.
1670 * @param argtypes The types of the operands.
1671 */
1672 Symbol resolveOperator(DiagnosticPosition pos, int optag,
1673 Env<AttrContext> env, List<Type> argtypes) {
1674 Name name = treeinfo.operatorName(optag);
1675 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
1676 null, false, false, true);
1677 if (boxingEnabled && sym.kind >= WRONG_MTHS)
1678 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1679 null, true, false, true);
1680 return access(sym, pos, env.enclClass.sym.type, name,
1681 false, argtypes, null);
1682 }
1684 /** Resolve operator.
1685 * @param pos The position to use for error reporting.
1686 * @param optag The tag of the operation tree.
1687 * @param env The environment current at the operation.
1688 * @param arg The type of the operand.
1689 */
1690 Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
1691 return resolveOperator(pos, optag, env, List.of(arg));
1692 }
1694 /** Resolve binary operator.
1695 * @param pos The position to use for error reporting.
1696 * @param optag The tag of the operation tree.
1697 * @param env The environment current at the operation.
1698 * @param left The types of the left operand.
1699 * @param right The types of the right operand.
1700 */
1701 Symbol resolveBinaryOperator(DiagnosticPosition pos,
1702 int optag,
1703 Env<AttrContext> env,
1704 Type left,
1705 Type right) {
1706 return resolveOperator(pos, optag, env, List.of(left, right));
1707 }
1709 /**
1710 * Resolve `c.name' where name == this or name == super.
1711 * @param pos The position to use for error reporting.
1712 * @param env The environment current at the expression.
1713 * @param c The qualifier.
1714 * @param name The identifier's name.
1715 */
1716 Symbol resolveSelf(DiagnosticPosition pos,
1717 Env<AttrContext> env,
1718 TypeSymbol c,
1719 Name name) {
1720 Env<AttrContext> env1 = env;
1721 boolean staticOnly = false;
1722 while (env1.outer != null) {
1723 if (isStatic(env1)) staticOnly = true;
1724 if (env1.enclClass.sym == c) {
1725 Symbol sym = env1.info.scope.lookup(name).sym;
1726 if (sym != null) {
1727 if (staticOnly) sym = new StaticError(sym);
1728 return access(sym, pos, env.enclClass.sym.type,
1729 name, true);
1730 }
1731 }
1732 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1733 env1 = env1.outer;
1734 }
1735 log.error(pos, "not.encl.class", c);
1736 return syms.errSymbol;
1737 }
1739 /**
1740 * Resolve `c.this' for an enclosing class c that contains the
1741 * named member.
1742 * @param pos The position to use for error reporting.
1743 * @param env The environment current at the expression.
1744 * @param member The member that must be contained in the result.
1745 */
1746 Symbol resolveSelfContaining(DiagnosticPosition pos,
1747 Env<AttrContext> env,
1748 Symbol member) {
1749 Name name = names._this;
1750 Env<AttrContext> env1 = env;
1751 boolean staticOnly = false;
1752 while (env1.outer != null) {
1753 if (isStatic(env1)) staticOnly = true;
1754 if (env1.enclClass.sym.isSubClass(member.owner, types) &&
1755 isAccessible(env, env1.enclClass.sym.type, member)) {
1756 Symbol sym = env1.info.scope.lookup(name).sym;
1757 if (sym != null) {
1758 if (staticOnly) sym = new StaticError(sym);
1759 return access(sym, pos, env.enclClass.sym.type,
1760 name, true);
1761 }
1762 }
1763 if ((env1.enclClass.sym.flags() & STATIC) != 0)
1764 staticOnly = true;
1765 env1 = env1.outer;
1766 }
1767 log.error(pos, "encl.class.required", member);
1768 return syms.errSymbol;
1769 }
1771 /**
1772 * Resolve an appropriate implicit this instance for t's container.
1773 * JLS2 8.8.5.1 and 15.9.2
1774 */
1775 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
1776 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
1777 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
1778 : resolveSelfContaining(pos, env, t.tsym)).type;
1779 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
1780 log.error(pos, "cant.ref.before.ctor.called", "this");
1781 return thisType;
1782 }
1784 /* ***************************************************************************
1785 * ResolveError classes, indicating error situations when accessing symbols
1786 ****************************************************************************/
1788 public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
1789 AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
1790 logResolveError(error, tree.pos(), type.getEnclosingType().tsym, type.getEnclosingType(), null, null, null);
1791 }
1792 //where
1793 private void logResolveError(ResolveError error,
1794 DiagnosticPosition pos,
1795 Symbol location,
1796 Type site,
1797 Name name,
1798 List<Type> argtypes,
1799 List<Type> typeargtypes) {
1800 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
1801 pos, location, site, name, argtypes, typeargtypes);
1802 if (d != null) {
1803 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
1804 log.report(d);
1805 }
1806 }
1808 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
1810 public Object methodArguments(List<Type> argtypes) {
1811 return argtypes.isEmpty() ? noArgs : argtypes;
1812 }
1814 /**
1815 * Root class for resolution errors. Subclass of ResolveError
1816 * represent a different kinds of resolution error - as such they must
1817 * specify how they map into concrete compiler diagnostics.
1818 */
1819 private abstract class ResolveError extends Symbol {
1821 /** The name of the kind of error, for debugging only. */
1822 final String debugName;
1824 ResolveError(int kind, String debugName) {
1825 super(kind, 0, null, null, null);
1826 this.debugName = debugName;
1827 }
1829 @Override
1830 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1831 throw new AssertionError();
1832 }
1834 @Override
1835 public String toString() {
1836 return debugName;
1837 }
1839 @Override
1840 public boolean exists() {
1841 return false;
1842 }
1844 /**
1845 * Create an external representation for this erroneous symbol to be
1846 * used during attribution - by default this returns the symbol of a
1847 * brand new error type which stores the original type found
1848 * during resolution.
1849 *
1850 * @param name the name used during resolution
1851 * @param location the location from which the symbol is accessed
1852 */
1853 protected Symbol access(Name name, TypeSymbol location) {
1854 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
1855 }
1857 /**
1858 * Create a diagnostic representing this resolution error.
1859 *
1860 * @param dkind The kind of the diagnostic to be created (e.g error).
1861 * @param pos The position to be used for error reporting.
1862 * @param site The original type from where the selection took place.
1863 * @param name The name of the symbol to be resolved.
1864 * @param argtypes The invocation's value arguments,
1865 * if we looked for a method.
1866 * @param typeargtypes The invocation's type arguments,
1867 * if we looked for a method.
1868 */
1869 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1870 DiagnosticPosition pos,
1871 Symbol location,
1872 Type site,
1873 Name name,
1874 List<Type> argtypes,
1875 List<Type> typeargtypes);
1877 /**
1878 * A name designates an operator if it consists
1879 * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
1880 */
1881 boolean isOperator(Name name) {
1882 int i = 0;
1883 while (i < name.getByteLength() &&
1884 "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
1885 return i > 0 && i == name.getByteLength();
1886 }
1887 }
1889 /**
1890 * This class is the root class of all resolution errors caused by
1891 * an invalid symbol being found during resolution.
1892 */
1893 abstract class InvalidSymbolError extends ResolveError {
1895 /** The invalid symbol found during resolution */
1896 Symbol sym;
1898 InvalidSymbolError(int kind, Symbol sym, String debugName) {
1899 super(kind, debugName);
1900 this.sym = sym;
1901 }
1903 @Override
1904 public boolean exists() {
1905 return true;
1906 }
1908 @Override
1909 public String toString() {
1910 return super.toString() + " wrongSym=" + sym;
1911 }
1913 @Override
1914 public Symbol access(Name name, TypeSymbol location) {
1915 if (sym.kind >= AMBIGUOUS)
1916 return ((ResolveError)sym).access(name, location);
1917 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
1918 return types.createErrorType(name, location, sym.type).tsym;
1919 else
1920 return sym;
1921 }
1922 }
1924 /**
1925 * InvalidSymbolError error class indicating that a symbol matching a
1926 * given name does not exists in a given site.
1927 */
1928 class SymbolNotFoundError extends ResolveError {
1930 SymbolNotFoundError(int kind) {
1931 super(kind, "symbol not found error");
1932 }
1934 @Override
1935 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
1936 DiagnosticPosition pos,
1937 Symbol location,
1938 Type site,
1939 Name name,
1940 List<Type> argtypes,
1941 List<Type> typeargtypes) {
1942 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
1943 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
1944 if (name == names.error)
1945 return null;
1947 if (isOperator(name)) {
1948 boolean isUnaryOp = argtypes.size() == 1;
1949 String key = argtypes.size() == 1 ?
1950 "operator.cant.be.applied" :
1951 "operator.cant.be.applied.1";
1952 Type first = argtypes.head;
1953 Type second = !isUnaryOp ? argtypes.tail.head : null;
1954 return diags.create(dkind, log.currentSource(), pos,
1955 key, name, first, second);
1956 }
1957 boolean hasLocation = false;
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)); //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) {
1997 boolean isVar = location.kind == VAR;
1998 String key = isVar ?
1999 "location.1" :
2000 "location";
2001 return diags.fragment(key,
2002 kindName(location),
2003 location,
2004 isVar ? location.type : null);
2005 }
2006 }
2008 /**
2009 * InvalidSymbolError error class indicating that a given symbol
2010 * (either a method, a constructor or an operand) is not applicable
2011 * given an actual arguments/type argument list.
2012 */
2013 class InapplicableSymbolError extends InvalidSymbolError {
2015 /** An auxiliary explanation set in case of instantiation errors. */
2016 JCDiagnostic explanation;
2018 InapplicableSymbolError(Symbol sym) {
2019 super(WRONG_MTH, sym, "inapplicable symbol error");
2020 }
2022 /** Update sym and explanation and return this.
2023 */
2024 InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
2025 this.sym = sym;
2026 if (this.sym == sym && explanation != null)
2027 this.explanation = explanation; //update the details
2028 return this;
2029 }
2031 /** Update sym and return this.
2032 */
2033 InapplicableSymbolError setWrongSym(Symbol sym) {
2034 this.sym = sym;
2035 return this;
2036 }
2038 @Override
2039 public String toString() {
2040 return super.toString() + " explanation=" + explanation;
2041 }
2043 @Override
2044 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2045 DiagnosticPosition pos,
2046 Symbol location,
2047 Type site,
2048 Name name,
2049 List<Type> argtypes,
2050 List<Type> typeargtypes) {
2051 if (name == names.error)
2052 return null;
2054 if (isOperator(name)) {
2055 return diags.create(dkind, log.currentSource(),
2056 pos, "operator.cant.be.applied", name, argtypes);
2057 }
2058 else {
2059 Symbol ws = sym.asMemberOf(site, types);
2060 return diags.create(dkind, log.currentSource(), pos,
2061 "cant.apply.symbol" + (explanation != null ? ".1" : ""),
2062 kindName(ws),
2063 ws.name == names.init ? ws.owner.name : ws.name,
2064 methodArguments(ws.type.getParameterTypes()),
2065 methodArguments(argtypes),
2066 kindName(ws.owner),
2067 ws.owner.type,
2068 explanation);
2069 }
2070 }
2072 void clear() {
2073 explanation = null;
2074 }
2076 @Override
2077 public Symbol access(Name name, TypeSymbol location) {
2078 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2079 }
2080 }
2082 /**
2083 * ResolveError error class indicating that a set of symbols
2084 * (either methods, constructors or operands) is not applicable
2085 * given an actual arguments/type argument list.
2086 */
2087 class InapplicableSymbolsError extends ResolveError {
2089 private List<Candidate> candidates = List.nil();
2091 InapplicableSymbolsError(Symbol sym) {
2092 super(WRONG_MTHS, "inapplicable symbols");
2093 }
2095 @Override
2096 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2097 DiagnosticPosition pos,
2098 Symbol location,
2099 Type site,
2100 Name name,
2101 List<Type> argtypes,
2102 List<Type> typeargtypes) {
2103 if (candidates.nonEmpty()) {
2104 JCDiagnostic err = diags.create(dkind,
2105 log.currentSource(),
2106 pos,
2107 "cant.apply.symbols",
2108 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2109 getName(),
2110 argtypes);
2111 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2112 } else {
2113 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2114 location, site, name, argtypes, typeargtypes);
2115 }
2116 }
2118 //where
2119 List<JCDiagnostic> candidateDetails(Type site) {
2120 List<JCDiagnostic> details = List.nil();
2121 for (Candidate c : candidates)
2122 details = details.prepend(c.getDiagnostic(site));
2123 return details.reverse();
2124 }
2126 Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
2127 Candidate c = new Candidate(currentStep, sym, details);
2128 if (c.isValid() && !candidates.contains(c))
2129 candidates = candidates.append(c);
2130 return this;
2131 }
2133 void clear() {
2134 candidates = List.nil();
2135 }
2137 private Name getName() {
2138 Symbol sym = candidates.head.sym;
2139 return sym.name == names.init ?
2140 sym.owner.name :
2141 sym.name;
2142 }
2144 private class Candidate {
2146 final MethodResolutionPhase step;
2147 final Symbol sym;
2148 final JCDiagnostic details;
2150 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
2151 this.step = step;
2152 this.sym = sym;
2153 this.details = details;
2154 }
2156 JCDiagnostic getDiagnostic(Type site) {
2157 return diags.fragment("inapplicable.method",
2158 Kinds.kindName(sym),
2159 sym.location(site, types),
2160 sym.asMemberOf(site, types),
2161 details);
2162 }
2164 @Override
2165 public boolean equals(Object o) {
2166 if (o instanceof Candidate) {
2167 Symbol s1 = this.sym;
2168 Symbol s2 = ((Candidate)o).sym;
2169 if ((s1 != s2 &&
2170 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2171 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2172 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2173 return true;
2174 }
2175 return false;
2176 }
2178 boolean isValid() {
2179 return (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
2180 (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
2181 }
2182 }
2183 }
2185 /**
2186 * An InvalidSymbolError error class indicating that a symbol is not
2187 * accessible from a given site
2188 */
2189 class AccessError extends InvalidSymbolError {
2191 private Env<AttrContext> env;
2192 private Type site;
2194 AccessError(Symbol sym) {
2195 this(null, null, sym);
2196 }
2198 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2199 super(HIDDEN, sym, "access error");
2200 this.env = env;
2201 this.site = site;
2202 if (debugResolve)
2203 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2204 }
2206 @Override
2207 public boolean exists() {
2208 return false;
2209 }
2211 @Override
2212 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2213 DiagnosticPosition pos,
2214 Symbol location,
2215 Type site,
2216 Name name,
2217 List<Type> argtypes,
2218 List<Type> typeargtypes) {
2219 if (sym.owner.type.tag == ERROR)
2220 return null;
2222 if (sym.name == names.init && sym.owner != site.tsym) {
2223 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2224 pos, location, site, name, argtypes, typeargtypes);
2225 }
2226 else if ((sym.flags() & PUBLIC) != 0
2227 || (env != null && this.site != null
2228 && !isAccessible(env, this.site))) {
2229 return diags.create(dkind, log.currentSource(),
2230 pos, "not.def.access.class.intf.cant.access",
2231 sym, sym.location());
2232 }
2233 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2234 return diags.create(dkind, log.currentSource(),
2235 pos, "report.access", sym,
2236 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2237 sym.location());
2238 }
2239 else {
2240 return diags.create(dkind, log.currentSource(),
2241 pos, "not.def.public.cant.access", sym, sym.location());
2242 }
2243 }
2244 }
2246 /**
2247 * InvalidSymbolError error class indicating that an instance member
2248 * has erroneously been accessed from a static context.
2249 */
2250 class StaticError extends InvalidSymbolError {
2252 StaticError(Symbol sym) {
2253 super(STATICERR, sym, "static error");
2254 }
2256 @Override
2257 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2258 DiagnosticPosition pos,
2259 Symbol location,
2260 Type site,
2261 Name name,
2262 List<Type> argtypes,
2263 List<Type> typeargtypes) {
2264 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2265 ? types.erasure(sym.type).tsym
2266 : sym);
2267 return diags.create(dkind, log.currentSource(), pos,
2268 "non-static.cant.be.ref", kindName(sym), errSym);
2269 }
2270 }
2272 /**
2273 * InvalidSymbolError error class indicating that a pair of symbols
2274 * (either methods, constructors or operands) are ambiguous
2275 * given an actual arguments/type argument list.
2276 */
2277 class AmbiguityError extends InvalidSymbolError {
2279 /** The other maximally specific symbol */
2280 Symbol sym2;
2282 AmbiguityError(Symbol sym1, Symbol sym2) {
2283 super(AMBIGUOUS, sym1, "ambiguity error");
2284 this.sym2 = sym2;
2285 }
2287 @Override
2288 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2289 DiagnosticPosition pos,
2290 Symbol location,
2291 Type site,
2292 Name name,
2293 List<Type> argtypes,
2294 List<Type> typeargtypes) {
2295 AmbiguityError pair = this;
2296 while (true) {
2297 if (pair.sym.kind == AMBIGUOUS)
2298 pair = (AmbiguityError)pair.sym;
2299 else if (pair.sym2.kind == AMBIGUOUS)
2300 pair = (AmbiguityError)pair.sym2;
2301 else break;
2302 }
2303 Name sname = pair.sym.name;
2304 if (sname == names.init) sname = pair.sym.owner.name;
2305 return diags.create(dkind, log.currentSource(),
2306 pos, "ref.ambiguous", sname,
2307 kindName(pair.sym),
2308 pair.sym,
2309 pair.sym.location(site, types),
2310 kindName(pair.sym2),
2311 pair.sym2,
2312 pair.sym2.location(site, types));
2313 }
2314 }
2316 enum MethodResolutionPhase {
2317 BASIC(false, false),
2318 BOX(true, false),
2319 VARARITY(true, true);
2321 boolean isBoxingRequired;
2322 boolean isVarargsRequired;
2324 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2325 this.isBoxingRequired = isBoxingRequired;
2326 this.isVarargsRequired = isVarargsRequired;
2327 }
2329 public boolean isBoxingRequired() {
2330 return isBoxingRequired;
2331 }
2333 public boolean isVarargsRequired() {
2334 return isVarargsRequired;
2335 }
2337 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2338 return (varargsEnabled || !isVarargsRequired) &&
2339 (boxingEnabled || !isBoxingRequired);
2340 }
2341 }
2343 private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
2344 new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
2346 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2348 private MethodResolutionPhase currentStep = null;
2350 private MethodResolutionPhase firstErroneousResolutionPhase() {
2351 MethodResolutionPhase bestSoFar = BASIC;
2352 Symbol sym = methodNotFound;
2353 List<MethodResolutionPhase> steps = methodResolutionSteps;
2354 while (steps.nonEmpty() &&
2355 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2356 sym.kind >= WRONG_MTHS) {
2357 sym = methodResolutionCache.get(steps.head);
2358 bestSoFar = steps.head;
2359 steps = steps.tail;
2360 }
2361 return bestSoFar;
2362 }
2363 }