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