Thu, 04 Oct 2012 13:04:53 +0100
7177387: Add target-typing support in method context
Summary: Add support for deferred types and speculative attribution
Reviewed-by: jjg, dlsmith
1 /*
2 * Copyright (c) 1999, 2012, 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.api.Formattable.LocalizedString;
29 import com.sun.tools.javac.code.*;
30 import com.sun.tools.javac.code.Symbol.*;
31 import com.sun.tools.javac.code.Type.*;
32 import com.sun.tools.javac.comp.Attr.ResultInfo;
33 import com.sun.tools.javac.comp.Check.CheckContext;
34 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
35 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
36 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
37 import com.sun.tools.javac.comp.Infer.InferenceContext;
38 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
40 import com.sun.tools.javac.jvm.*;
41 import com.sun.tools.javac.tree.*;
42 import com.sun.tools.javac.tree.JCTree.*;
43 import com.sun.tools.javac.util.*;
44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.EnumMap;
51 import java.util.EnumSet;
52 import java.util.Iterator;
53 import java.util.Map;
55 import javax.lang.model.element.ElementVisitor;
57 import static com.sun.tools.javac.code.Flags.*;
58 import static com.sun.tools.javac.code.Flags.BLOCK;
59 import static com.sun.tools.javac.code.Kinds.*;
60 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
61 import static com.sun.tools.javac.code.TypeTags.*;
62 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
63 import static com.sun.tools.javac.tree.JCTree.Tag.*;
65 /** Helper class for name resolution, used mostly by the attribution phase.
66 *
67 * <p><b>This is NOT part of any supported API.
68 * If you write code that depends on this, you do so at your own risk.
69 * This code and its internal interfaces are subject to change or
70 * deletion without notice.</b>
71 */
72 public class Resolve {
73 protected static final Context.Key<Resolve> resolveKey =
74 new Context.Key<Resolve>();
76 Names names;
77 Log log;
78 Symtab syms;
79 Attr attr;
80 DeferredAttr deferredAttr;
81 Check chk;
82 Infer infer;
83 ClassReader reader;
84 TreeInfo treeinfo;
85 Types types;
86 JCDiagnostic.Factory diags;
87 public final boolean boxingEnabled; // = source.allowBoxing();
88 public final boolean varargsEnabled; // = source.allowVarargs();
89 public final boolean allowMethodHandles;
90 private final boolean debugResolve;
91 final EnumSet<VerboseResolutionMode> verboseResolutionMode;
93 Scope polymorphicSignatureScope;
95 protected Resolve(Context context) {
96 context.put(resolveKey, this);
97 syms = Symtab.instance(context);
99 varNotFound = new
100 SymbolNotFoundError(ABSENT_VAR);
101 wrongMethod = new
102 InapplicableSymbolError();
103 wrongMethods = new
104 InapplicableSymbolsError();
105 methodNotFound = new
106 SymbolNotFoundError(ABSENT_MTH);
107 typeNotFound = new
108 SymbolNotFoundError(ABSENT_TYP);
110 names = Names.instance(context);
111 log = Log.instance(context);
112 attr = Attr.instance(context);
113 deferredAttr = DeferredAttr.instance(context);
114 chk = Check.instance(context);
115 infer = Infer.instance(context);
116 reader = ClassReader.instance(context);
117 treeinfo = TreeInfo.instance(context);
118 types = Types.instance(context);
119 diags = JCDiagnostic.Factory.instance(context);
120 Source source = Source.instance(context);
121 boxingEnabled = source.allowBoxing();
122 varargsEnabled = source.allowVarargs();
123 Options options = Options.instance(context);
124 debugResolve = options.isSet("debugresolve");
125 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
126 Target target = Target.instance(context);
127 allowMethodHandles = target.hasMethodHandles();
128 polymorphicSignatureScope = new Scope(syms.noSymbol);
130 inapplicableMethodException = new InapplicableMethodException(diags);
131 }
133 /** error symbols, which are returned when resolution fails
134 */
135 private final SymbolNotFoundError varNotFound;
136 private final InapplicableSymbolError wrongMethod;
137 private final InapplicableSymbolsError wrongMethods;
138 private final SymbolNotFoundError methodNotFound;
139 private final SymbolNotFoundError typeNotFound;
141 public static Resolve instance(Context context) {
142 Resolve instance = context.get(resolveKey);
143 if (instance == null)
144 instance = new Resolve(context);
145 return instance;
146 }
148 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
149 enum VerboseResolutionMode {
150 SUCCESS("success"),
151 FAILURE("failure"),
152 APPLICABLE("applicable"),
153 INAPPLICABLE("inapplicable"),
154 DEFERRED_INST("deferred-inference"),
155 PREDEF("predef"),
156 OBJECT_INIT("object-init"),
157 INTERNAL("internal");
159 String opt;
161 private VerboseResolutionMode(String opt) {
162 this.opt = opt;
163 }
165 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
166 String s = opts.get("verboseResolution");
167 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
168 if (s == null) return res;
169 if (s.contains("all")) {
170 res = EnumSet.allOf(VerboseResolutionMode.class);
171 }
172 Collection<String> args = Arrays.asList(s.split(","));
173 for (VerboseResolutionMode mode : values()) {
174 if (args.contains(mode.opt)) {
175 res.add(mode);
176 } else if (args.contains("-" + mode.opt)) {
177 res.remove(mode);
178 }
179 }
180 return res;
181 }
182 }
184 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
185 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
186 boolean success = bestSoFar.kind < ERRONEOUS;
188 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
189 return;
190 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
191 return;
192 }
194 if (bestSoFar.name == names.init &&
195 bestSoFar.owner == syms.objectType.tsym &&
196 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
197 return; //skip diags for Object constructor resolution
198 } else if (site == syms.predefClass.type &&
199 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
200 return; //skip spurious diags for predef symbols (i.e. operators)
201 } else if (currentResolutionContext.internalResolution &&
202 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
203 return;
204 }
206 int pos = 0;
207 int mostSpecificPos = -1;
208 ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
209 for (Candidate c : currentResolutionContext.candidates) {
210 if (currentResolutionContext.step != c.step ||
211 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
212 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
213 continue;
214 } else {
215 subDiags.append(c.isApplicable() ?
216 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
217 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
218 if (c.sym == bestSoFar)
219 mostSpecificPos = pos;
220 pos++;
221 }
222 }
223 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
224 List<Type> argtypes2 = Type.map(argtypes,
225 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
226 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
227 site.tsym, mostSpecificPos, currentResolutionContext.step,
228 methodArguments(argtypes2),
229 methodArguments(typeargtypes));
230 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
231 log.report(d);
232 }
234 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
235 JCDiagnostic subDiag = null;
236 if (sym.type.tag == FORALL) {
237 subDiag = diags.fragment("partial.inst.sig", inst);
238 }
240 String key = subDiag == null ?
241 "applicable.method.found" :
242 "applicable.method.found.1";
244 return diags.fragment(key, pos, sym, subDiag);
245 }
247 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
248 return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
249 }
250 // </editor-fold>
252 /* ************************************************************************
253 * Identifier resolution
254 *************************************************************************/
256 /** An environment is "static" if its static level is greater than
257 * the one of its outer environment
258 */
259 protected static boolean isStatic(Env<AttrContext> env) {
260 return env.info.staticLevel > env.outer.info.staticLevel;
261 }
263 /** An environment is an "initializer" if it is a constructor or
264 * an instance initializer.
265 */
266 static boolean isInitializer(Env<AttrContext> env) {
267 Symbol owner = env.info.scope.owner;
268 return owner.isConstructor() ||
269 owner.owner.kind == TYP &&
270 (owner.kind == VAR ||
271 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
272 (owner.flags() & STATIC) == 0;
273 }
275 /** Is class accessible in given evironment?
276 * @param env The current environment.
277 * @param c The class whose accessibility is checked.
278 */
279 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
280 return isAccessible(env, c, false);
281 }
283 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
284 boolean isAccessible = false;
285 switch ((short)(c.flags() & AccessFlags)) {
286 case PRIVATE:
287 isAccessible =
288 env.enclClass.sym.outermostClass() ==
289 c.owner.outermostClass();
290 break;
291 case 0:
292 isAccessible =
293 env.toplevel.packge == c.owner // fast special case
294 ||
295 env.toplevel.packge == c.packge()
296 ||
297 // Hack: this case is added since synthesized default constructors
298 // of anonymous classes should be allowed to access
299 // classes which would be inaccessible otherwise.
300 env.enclMethod != null &&
301 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
302 break;
303 default: // error recovery
304 case PUBLIC:
305 isAccessible = true;
306 break;
307 case PROTECTED:
308 isAccessible =
309 env.toplevel.packge == c.owner // fast special case
310 ||
311 env.toplevel.packge == c.packge()
312 ||
313 isInnerSubClass(env.enclClass.sym, c.owner);
314 break;
315 }
316 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
317 isAccessible :
318 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
319 }
320 //where
321 /** Is given class a subclass of given base class, or an inner class
322 * of a subclass?
323 * Return null if no such class exists.
324 * @param c The class which is the subclass or is contained in it.
325 * @param base The base class
326 */
327 private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
328 while (c != null && !c.isSubClass(base, types)) {
329 c = c.owner.enclClass();
330 }
331 return c != null;
332 }
334 boolean isAccessible(Env<AttrContext> env, Type t) {
335 return isAccessible(env, t, false);
336 }
338 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
339 return (t.tag == ARRAY)
340 ? isAccessible(env, types.elemtype(t))
341 : isAccessible(env, t.tsym, checkInner);
342 }
344 /** Is symbol accessible as a member of given type in given evironment?
345 * @param env The current environment.
346 * @param site The type of which the tested symbol is regarded
347 * as a member.
348 * @param sym The symbol.
349 */
350 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
351 return isAccessible(env, site, sym, false);
352 }
353 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
354 if (sym.name == names.init && sym.owner != site.tsym) return false;
355 switch ((short)(sym.flags() & AccessFlags)) {
356 case PRIVATE:
357 return
358 (env.enclClass.sym == sym.owner // fast special case
359 ||
360 env.enclClass.sym.outermostClass() ==
361 sym.owner.outermostClass())
362 &&
363 sym.isInheritedIn(site.tsym, types);
364 case 0:
365 return
366 (env.toplevel.packge == sym.owner.owner // fast special case
367 ||
368 env.toplevel.packge == sym.packge())
369 &&
370 isAccessible(env, site, checkInner)
371 &&
372 sym.isInheritedIn(site.tsym, types)
373 &&
374 notOverriddenIn(site, sym);
375 case PROTECTED:
376 return
377 (env.toplevel.packge == sym.owner.owner // fast special case
378 ||
379 env.toplevel.packge == sym.packge()
380 ||
381 isProtectedAccessible(sym, env.enclClass.sym, site)
382 ||
383 // OK to select instance method or field from 'super' or type name
384 // (but type names should be disallowed elsewhere!)
385 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
386 &&
387 isAccessible(env, site, checkInner)
388 &&
389 notOverriddenIn(site, sym);
390 default: // this case includes erroneous combinations as well
391 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
392 }
393 }
394 //where
395 /* `sym' is accessible only if not overridden by
396 * another symbol which is a member of `site'
397 * (because, if it is overridden, `sym' is not strictly
398 * speaking a member of `site'). A polymorphic signature method
399 * cannot be overridden (e.g. MH.invokeExact(Object[])).
400 */
401 private boolean notOverriddenIn(Type site, Symbol sym) {
402 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
403 return true;
404 else {
405 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
406 return (s2 == null || s2 == sym || sym.owner == s2.owner ||
407 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
408 }
409 }
410 //where
411 /** Is given protected symbol accessible if it is selected from given site
412 * and the selection takes place in given class?
413 * @param sym The symbol with protected access
414 * @param c The class where the access takes place
415 * @site The type of the qualifier
416 */
417 private
418 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
419 while (c != null &&
420 !(c.isSubClass(sym.owner, types) &&
421 (c.flags() & INTERFACE) == 0 &&
422 // In JLS 2e 6.6.2.1, the subclass restriction applies
423 // only to instance fields and methods -- types are excluded
424 // regardless of whether they are declared 'static' or not.
425 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
426 c = c.owner.enclClass();
427 return c != null;
428 }
430 /** Try to instantiate the type of a method so that it fits
431 * given type arguments and argument types. If succesful, return
432 * the method's instantiated type, else return null.
433 * The instantiation will take into account an additional leading
434 * formal parameter if the method is an instance method seen as a member
435 * of un underdetermined site In this case, we treat site as an additional
436 * parameter and the parameters of the class containing the method as
437 * additional type variables that get instantiated.
438 *
439 * @param env The current environment
440 * @param site The type of which the method is a member.
441 * @param m The method symbol.
442 * @param argtypes The invocation's given value arguments.
443 * @param typeargtypes The invocation's given type arguments.
444 * @param allowBoxing Allow boxing conversions of arguments.
445 * @param useVarargs Box trailing arguments into an array for varargs.
446 */
447 Type rawInstantiate(Env<AttrContext> env,
448 Type site,
449 Symbol m,
450 ResultInfo resultInfo,
451 List<Type> argtypes,
452 List<Type> typeargtypes,
453 boolean allowBoxing,
454 boolean useVarargs,
455 Warner warn)
456 throws Infer.InferenceException {
457 if (useVarargs && (m.flags() & VARARGS) == 0)
458 throw inapplicableMethodException.setMessage();
459 Type mt = types.memberType(site, m);
461 // tvars is the list of formal type variables for which type arguments
462 // need to inferred.
463 List<Type> tvars = List.nil();
464 if (typeargtypes == null) typeargtypes = List.nil();
465 if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
466 // This is not a polymorphic method, but typeargs are supplied
467 // which is fine, see JLS 15.12.2.1
468 } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
469 ForAll pmt = (ForAll) mt;
470 if (typeargtypes.length() != pmt.tvars.length())
471 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
472 // Check type arguments are within bounds
473 List<Type> formals = pmt.tvars;
474 List<Type> actuals = typeargtypes;
475 while (formals.nonEmpty() && actuals.nonEmpty()) {
476 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
477 pmt.tvars, typeargtypes);
478 for (; bounds.nonEmpty(); bounds = bounds.tail)
479 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
480 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
481 formals = formals.tail;
482 actuals = actuals.tail;
483 }
484 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
485 } else if (mt.tag == FORALL) {
486 ForAll pmt = (ForAll) mt;
487 List<Type> tvars1 = types.newInstances(pmt.tvars);
488 tvars = tvars.appendList(tvars1);
489 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
490 }
492 // find out whether we need to go the slow route via infer
493 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
494 for (List<Type> l = argtypes;
495 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
496 l = l.tail) {
497 if (l.head.tag == FORALL) instNeeded = true;
498 }
500 if (instNeeded)
501 return infer.instantiateMethod(env,
502 tvars,
503 (MethodType)mt,
504 resultInfo,
505 m,
506 argtypes,
507 allowBoxing,
508 useVarargs,
509 currentResolutionContext,
510 warn);
512 checkRawArgumentsAcceptable(env, m, argtypes, mt.getParameterTypes(),
513 allowBoxing, useVarargs, warn);
514 return mt;
515 }
517 Type checkMethod(Env<AttrContext> env,
518 Type site,
519 Symbol m,
520 ResultInfo resultInfo,
521 List<Type> argtypes,
522 List<Type> typeargtypes,
523 Warner warn) {
524 MethodResolutionContext prevContext = currentResolutionContext;
525 try {
526 currentResolutionContext = new MethodResolutionContext();
527 currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
528 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
529 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
530 step.isBoxingRequired(), step.isVarargsRequired(), warn);
531 }
532 finally {
533 currentResolutionContext = prevContext;
534 }
535 }
537 /** Same but returns null instead throwing a NoInstanceException
538 */
539 Type instantiate(Env<AttrContext> env,
540 Type site,
541 Symbol m,
542 ResultInfo resultInfo,
543 List<Type> argtypes,
544 List<Type> typeargtypes,
545 boolean allowBoxing,
546 boolean useVarargs,
547 Warner warn) {
548 try {
549 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
550 allowBoxing, useVarargs, warn);
551 } catch (InapplicableMethodException ex) {
552 return null;
553 }
554 }
556 /** Check if a parameter list accepts a list of args.
557 */
558 boolean argumentsAcceptable(Env<AttrContext> env,
559 Symbol msym,
560 List<Type> argtypes,
561 List<Type> formals,
562 boolean allowBoxing,
563 boolean useVarargs,
564 Warner warn) {
565 try {
566 checkRawArgumentsAcceptable(env, msym, argtypes, formals, allowBoxing, useVarargs, warn);
567 return true;
568 } catch (InapplicableMethodException ex) {
569 return false;
570 }
571 }
572 /**
573 * A check handler is used by the main method applicability routine in order
574 * to handle specific method applicability failures. It is assumed that a class
575 * implementing this interface should throw exceptions that are a subtype of
576 * InapplicableMethodException (see below). Such exception will terminate the
577 * method applicability check and propagate important info outwards (for the
578 * purpose of generating better diagnostics).
579 */
580 interface MethodCheckHandler {
581 /* The number of actuals and formals differ */
582 InapplicableMethodException arityMismatch();
583 /* An actual argument type does not conform to the corresponding formal type */
584 InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
585 /* The element type of a varargs is not accessible in the current context */
586 InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
587 }
589 /**
590 * Basic method check handler used within Resolve - all methods end up
591 * throwing InapplicableMethodException; a diagnostic fragment that describes
592 * the cause as to why the method is not applicable is set on the exception
593 * before it is thrown.
594 */
595 MethodCheckHandler resolveHandler = new MethodCheckHandler() {
596 public InapplicableMethodException arityMismatch() {
597 return inapplicableMethodException.setMessage("arg.length.mismatch");
598 }
599 public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
600 String key = varargs ?
601 "varargs.argument.mismatch" :
602 "no.conforming.assignment.exists";
603 return inapplicableMethodException.setMessage(key,
604 details);
605 }
606 public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
607 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
608 expected, Kinds.kindName(location), location);
609 }
610 };
612 void checkRawArgumentsAcceptable(Env<AttrContext> env,
613 Symbol msym,
614 List<Type> argtypes,
615 List<Type> formals,
616 boolean allowBoxing,
617 boolean useVarargs,
618 Warner warn) {
619 checkRawArgumentsAcceptable(env, msym, currentResolutionContext.attrMode(), infer.emptyContext, argtypes, formals,
620 allowBoxing, useVarargs, warn, resolveHandler);
621 }
623 /**
624 * Main method applicability routine. Given a list of actual types A,
625 * a list of formal types F, determines whether the types in A are
626 * compatible (by method invocation conversion) with the types in F.
627 *
628 * Since this routine is shared between overload resolution and method
629 * type-inference, a (possibly empty) inference context is used to convert
630 * formal types to the corresponding 'undet' form ahead of a compatibility
631 * check so that constraints can be propagated and collected.
632 *
633 * Moreover, if one or more types in A is a deferred type, this routine uses
634 * DeferredAttr in order to perform deferred attribution. If one or more actual
635 * deferred types are stuck, they are placed in a queue and revisited later
636 * after the remainder of the arguments have been seen. If this is not sufficient
637 * to 'unstuck' the argument, a cyclic inference error is called out.
638 *
639 * A method check handler (see above) is used in order to report errors.
640 */
641 void checkRawArgumentsAcceptable(final Env<AttrContext> env,
642 Symbol msym,
643 DeferredAttr.AttrMode mode,
644 final Infer.InferenceContext inferenceContext,
645 List<Type> argtypes,
646 List<Type> formals,
647 boolean allowBoxing,
648 boolean useVarargs,
649 Warner warn,
650 final MethodCheckHandler handler) {
651 Type varargsFormal = useVarargs ? formals.last() : null;
653 if (varargsFormal == null &&
654 argtypes.size() != formals.size()) {
655 throw handler.arityMismatch(); // not enough args
656 }
658 DeferredAttr.DeferredAttrContext deferredAttrContext =
659 deferredAttr.new DeferredAttrContext(mode, msym, currentResolutionContext.step, inferenceContext);
661 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
662 ResultInfo mresult = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, deferredAttrContext, handler, warn);
663 mresult.check(null, argtypes.head);
664 argtypes = argtypes.tail;
665 formals = formals.tail;
666 }
668 if (formals.head != varargsFormal) {
669 throw handler.arityMismatch(); // not enough args
670 }
672 if (useVarargs) {
673 //note: if applicability check is triggered by most specific test,
674 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
675 final Type elt = types.elemtype(varargsFormal);
676 ResultInfo mresult = methodCheckResult(elt, allowBoxing, true, inferenceContext, deferredAttrContext, handler, warn);
677 while (argtypes.nonEmpty()) {
678 mresult.check(null, argtypes.head);
679 argtypes = argtypes.tail;
680 }
681 //check varargs element type accessibility
682 varargsAccessible(env, elt, handler, inferenceContext);
683 }
685 deferredAttrContext.complete();
686 }
688 void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
689 if (inferenceContext.free(t)) {
690 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
691 @Override
692 public void typesInferred(InferenceContext inferenceContext) {
693 varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
694 }
695 });
696 } else {
697 if (!isAccessible(env, t)) {
698 Symbol location = env.enclClass.sym;
699 throw handler.inaccessibleVarargs(location, t);
700 }
701 }
702 }
704 /**
705 * Check context to be used during method applicability checks. A method check
706 * context might contain inference variables.
707 */
708 abstract class MethodCheckContext implements CheckContext {
710 MethodCheckHandler handler;
711 boolean useVarargs;
712 Infer.InferenceContext inferenceContext;
713 DeferredAttrContext deferredAttrContext;
714 Warner rsWarner;
716 public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs,
717 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
718 this.handler = handler;
719 this.useVarargs = useVarargs;
720 this.inferenceContext = inferenceContext;
721 this.deferredAttrContext = deferredAttrContext;
722 this.rsWarner = rsWarner;
723 }
725 public void report(DiagnosticPosition pos, JCDiagnostic details) {
726 throw handler.argumentMismatch(useVarargs, details);
727 }
729 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
730 return rsWarner;
731 }
733 public InferenceContext inferenceContext() {
734 return inferenceContext;
735 }
737 public DeferredAttrContext deferredAttrContext() {
738 return deferredAttrContext;
739 }
740 }
742 /**
743 * Subclass of method check context class that implements strict method conversion.
744 * Strict method conversion checks compatibility between types using subtyping tests.
745 */
746 class StrictMethodContext extends MethodCheckContext {
748 public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs,
749 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
750 super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
751 }
753 public boolean compatible(Type found, Type req, Warner warn) {
754 return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
755 }
756 }
758 /**
759 * Subclass of method check context class that implements loose method conversion.
760 * Loose method conversion checks compatibility between types using method conversion tests.
761 */
762 class LooseMethodContext extends MethodCheckContext {
764 public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs,
765 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
766 super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
767 }
769 public boolean compatible(Type found, Type req, Warner warn) {
770 return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
771 }
772 }
774 /**
775 * Create a method check context to be used during method applicability check
776 */
777 ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
778 Infer.InferenceContext inferenceContext, DeferredAttr.DeferredAttrContext deferredAttrContext,
779 MethodCheckHandler methodHandler, Warner rsWarner) {
780 MethodCheckContext checkContext = allowBoxing ?
781 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner) :
782 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
783 return new MethodResultInfo(to, checkContext, deferredAttrContext);
784 }
786 class MethodResultInfo extends ResultInfo {
788 DeferredAttr.DeferredAttrContext deferredAttrContext;
790 public MethodResultInfo(Type pt, MethodCheckContext checkContext, DeferredAttr.DeferredAttrContext deferredAttrContext) {
791 attr.super(VAL, pt, checkContext);
792 this.deferredAttrContext = deferredAttrContext;
793 }
795 @Override
796 protected Type check(DiagnosticPosition pos, Type found) {
797 if (found.tag == DEFERRED) {
798 DeferredType dt = (DeferredType)found;
799 return dt.check(this);
800 } else {
801 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
802 }
803 }
805 @Override
806 protected MethodResultInfo dup(Type newPt) {
807 return new MethodResultInfo(newPt, (MethodCheckContext)checkContext, deferredAttrContext);
808 }
809 }
811 public static class InapplicableMethodException extends RuntimeException {
812 private static final long serialVersionUID = 0;
814 JCDiagnostic diagnostic;
815 JCDiagnostic.Factory diags;
817 InapplicableMethodException(JCDiagnostic.Factory diags) {
818 this.diagnostic = null;
819 this.diags = diags;
820 }
821 InapplicableMethodException setMessage() {
822 return setMessage((JCDiagnostic)null);
823 }
824 InapplicableMethodException setMessage(String key) {
825 return setMessage(key != null ? diags.fragment(key) : null);
826 }
827 InapplicableMethodException setMessage(String key, Object... args) {
828 return setMessage(key != null ? diags.fragment(key, args) : null);
829 }
830 InapplicableMethodException setMessage(JCDiagnostic diag) {
831 this.diagnostic = diag;
832 return this;
833 }
835 public JCDiagnostic getDiagnostic() {
836 return diagnostic;
837 }
838 }
839 private final InapplicableMethodException inapplicableMethodException;
841 /* ***************************************************************************
842 * Symbol lookup
843 * the following naming conventions for arguments are used
844 *
845 * env is the environment where the symbol was mentioned
846 * site is the type of which the symbol is a member
847 * name is the symbol's name
848 * if no arguments are given
849 * argtypes are the value arguments, if we search for a method
850 *
851 * If no symbol was found, a ResolveError detailing the problem is returned.
852 ****************************************************************************/
854 /** Find field. Synthetic fields are always skipped.
855 * @param env The current environment.
856 * @param site The original type from where the selection takes place.
857 * @param name The name of the field.
858 * @param c The class to search for the field. This is always
859 * a superclass or implemented interface of site's class.
860 */
861 Symbol findField(Env<AttrContext> env,
862 Type site,
863 Name name,
864 TypeSymbol c) {
865 while (c.type.tag == TYPEVAR)
866 c = c.type.getUpperBound().tsym;
867 Symbol bestSoFar = varNotFound;
868 Symbol sym;
869 Scope.Entry e = c.members().lookup(name);
870 while (e.scope != null) {
871 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
872 return isAccessible(env, site, e.sym)
873 ? e.sym : new AccessError(env, site, e.sym);
874 }
875 e = e.next();
876 }
877 Type st = types.supertype(c.type);
878 if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
879 sym = findField(env, site, name, st.tsym);
880 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
881 }
882 for (List<Type> l = types.interfaces(c.type);
883 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
884 l = l.tail) {
885 sym = findField(env, site, name, l.head.tsym);
886 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
887 sym.owner != bestSoFar.owner)
888 bestSoFar = new AmbiguityError(bestSoFar, sym);
889 else if (sym.kind < bestSoFar.kind)
890 bestSoFar = sym;
891 }
892 return bestSoFar;
893 }
895 /** Resolve a field identifier, throw a fatal error if not found.
896 * @param pos The position to use for error reporting.
897 * @param env The environment current at the method invocation.
898 * @param site The type of the qualifying expression, in which
899 * identifier is searched.
900 * @param name The identifier's name.
901 */
902 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
903 Type site, Name name) {
904 Symbol sym = findField(env, site, name, site.tsym);
905 if (sym.kind == VAR) return (VarSymbol)sym;
906 else throw new FatalError(
907 diags.fragment("fatal.err.cant.locate.field",
908 name));
909 }
911 /** Find unqualified variable or field with given name.
912 * Synthetic fields always skipped.
913 * @param env The current environment.
914 * @param name The name of the variable or field.
915 */
916 Symbol findVar(Env<AttrContext> env, Name name) {
917 Symbol bestSoFar = varNotFound;
918 Symbol sym;
919 Env<AttrContext> env1 = env;
920 boolean staticOnly = false;
921 while (env1.outer != null) {
922 if (isStatic(env1)) staticOnly = true;
923 Scope.Entry e = env1.info.scope.lookup(name);
924 while (e.scope != null &&
925 (e.sym.kind != VAR ||
926 (e.sym.flags_field & SYNTHETIC) != 0))
927 e = e.next();
928 sym = (e.scope != null)
929 ? e.sym
930 : findField(
931 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
932 if (sym.exists()) {
933 if (staticOnly &&
934 sym.kind == VAR &&
935 sym.owner.kind == TYP &&
936 (sym.flags() & STATIC) == 0)
937 return new StaticError(sym);
938 else
939 return sym;
940 } else if (sym.kind < bestSoFar.kind) {
941 bestSoFar = sym;
942 }
944 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
945 env1 = env1.outer;
946 }
948 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
949 if (sym.exists())
950 return sym;
951 if (bestSoFar.exists())
952 return bestSoFar;
954 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
955 for (; e.scope != null; e = e.next()) {
956 sym = e.sym;
957 Type origin = e.getOrigin().owner.type;
958 if (sym.kind == VAR) {
959 if (e.sym.owner.type != origin)
960 sym = sym.clone(e.getOrigin().owner);
961 return isAccessible(env, origin, sym)
962 ? sym : new AccessError(env, origin, sym);
963 }
964 }
966 Symbol origin = null;
967 e = env.toplevel.starImportScope.lookup(name);
968 for (; e.scope != null; e = e.next()) {
969 sym = e.sym;
970 if (sym.kind != VAR)
971 continue;
972 // invariant: sym.kind == VAR
973 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
974 return new AmbiguityError(bestSoFar, sym);
975 else if (bestSoFar.kind >= VAR) {
976 origin = e.getOrigin().owner;
977 bestSoFar = isAccessible(env, origin.type, sym)
978 ? sym : new AccessError(env, origin.type, sym);
979 }
980 }
981 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
982 return bestSoFar.clone(origin);
983 else
984 return bestSoFar;
985 }
987 Warner noteWarner = new Warner();
989 /** Select the best method for a call site among two choices.
990 * @param env The current environment.
991 * @param site The original type from where the
992 * selection takes place.
993 * @param argtypes The invocation's value arguments,
994 * @param typeargtypes The invocation's type arguments,
995 * @param sym Proposed new best match.
996 * @param bestSoFar Previously found best match.
997 * @param allowBoxing Allow boxing conversions of arguments.
998 * @param useVarargs Box trailing arguments into an array for varargs.
999 */
1000 @SuppressWarnings("fallthrough")
1001 Symbol selectBest(Env<AttrContext> env,
1002 Type site,
1003 List<Type> argtypes,
1004 List<Type> typeargtypes,
1005 Symbol sym,
1006 Symbol bestSoFar,
1007 boolean allowBoxing,
1008 boolean useVarargs,
1009 boolean operator) {
1010 if (sym.kind == ERR) return bestSoFar;
1011 if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
1012 Assert.check(sym.kind < AMBIGUOUS);
1013 try {
1014 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1015 allowBoxing, useVarargs, Warner.noWarnings);
1016 if (!operator)
1017 currentResolutionContext.addApplicableCandidate(sym, mt);
1018 } catch (InapplicableMethodException ex) {
1019 if (!operator)
1020 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1021 switch (bestSoFar.kind) {
1022 case ABSENT_MTH:
1023 return wrongMethod;
1024 case WRONG_MTH:
1025 if (operator) return bestSoFar;
1026 case WRONG_MTHS:
1027 return wrongMethods;
1028 default:
1029 return bestSoFar;
1030 }
1031 }
1032 if (!isAccessible(env, site, sym)) {
1033 return (bestSoFar.kind == ABSENT_MTH)
1034 ? new AccessError(env, site, sym)
1035 : bestSoFar;
1036 }
1037 return (bestSoFar.kind > AMBIGUOUS)
1038 ? sym
1039 : mostSpecific(sym, bestSoFar, env, site,
1040 allowBoxing && operator, useVarargs);
1041 }
1043 /* Return the most specific of the two methods for a call,
1044 * given that both are accessible and applicable.
1045 * @param m1 A new candidate for most specific.
1046 * @param m2 The previous most specific candidate.
1047 * @param env The current environment.
1048 * @param site The original type from where the selection
1049 * takes place.
1050 * @param allowBoxing Allow boxing conversions of arguments.
1051 * @param useVarargs Box trailing arguments into an array for varargs.
1052 */
1053 Symbol mostSpecific(Symbol m1,
1054 Symbol m2,
1055 Env<AttrContext> env,
1056 final Type site,
1057 boolean allowBoxing,
1058 boolean useVarargs) {
1059 switch (m2.kind) {
1060 case MTH:
1061 if (m1 == m2) return m1;
1062 boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
1063 boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
1064 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1065 Type mt1 = types.memberType(site, m1);
1066 Type mt2 = types.memberType(site, m2);
1067 if (!types.overrideEquivalent(mt1, mt2))
1068 return ambiguityError(m1, m2);
1070 // same signature; select (a) the non-bridge method, or
1071 // (b) the one that overrides the other, or (c) the concrete
1072 // one, or (d) merge both abstract signatures
1073 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1074 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1076 // if one overrides or hides the other, use it
1077 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1078 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1079 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1080 ((m1.owner.flags_field & INTERFACE) == 0 ||
1081 (m2.owner.flags_field & INTERFACE) != 0) &&
1082 m1.overrides(m2, m1Owner, types, false))
1083 return m1;
1084 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1085 ((m2.owner.flags_field & INTERFACE) == 0 ||
1086 (m1.owner.flags_field & INTERFACE) != 0) &&
1087 m2.overrides(m1, m2Owner, types, false))
1088 return m2;
1089 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1090 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1091 if (m1Abstract && !m2Abstract) return m2;
1092 if (m2Abstract && !m1Abstract) return m1;
1093 // both abstract or both concrete
1094 if (!m1Abstract && !m2Abstract)
1095 return ambiguityError(m1, m2);
1096 // check that both signatures have the same erasure
1097 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
1098 m2.erasure(types).getParameterTypes()))
1099 return ambiguityError(m1, m2);
1100 // both abstract, neither overridden; merge throws clause and result type
1101 Type mst = mostSpecificReturnType(mt1, mt2);
1102 if (mst == null) {
1103 // Theoretically, this can't happen, but it is possible
1104 // due to error recovery or mixing incompatible class files
1105 return ambiguityError(m1, m2);
1106 }
1107 Symbol mostSpecific = mst == mt1 ? m1 : m2;
1108 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
1109 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
1110 MethodSymbol result = new MethodSymbol(
1111 mostSpecific.flags(),
1112 mostSpecific.name,
1113 newSig,
1114 mostSpecific.owner) {
1115 @Override
1116 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1117 if (origin == site.tsym)
1118 return this;
1119 else
1120 return super.implementation(origin, types, checkResult);
1121 }
1122 };
1123 return result;
1124 }
1125 if (m1SignatureMoreSpecific) return m1;
1126 if (m2SignatureMoreSpecific) return m2;
1127 return ambiguityError(m1, m2);
1128 case AMBIGUOUS:
1129 AmbiguityError e = (AmbiguityError)m2;
1130 Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
1131 Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
1132 if (err1 == err2) return err1;
1133 if (err1 == e.sym && err2 == e.sym2) return m2;
1134 if (err1 instanceof AmbiguityError &&
1135 err2 instanceof AmbiguityError &&
1136 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
1137 return ambiguityError(m1, m2);
1138 else
1139 return ambiguityError(err1, err2);
1140 default:
1141 throw new AssertionError();
1142 }
1143 }
1144 //where
1145 private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1146 noteWarner.clear();
1147 Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
1148 Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs), null,
1149 types.lowerBoundArgtypes(mtype1), null,
1150 allowBoxing, false, noteWarner);
1151 return mtype2 != null &&
1152 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1153 }
1154 //where
1155 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
1156 List<Type> fromArgs = from.type.getParameterTypes();
1157 List<Type> toArgs = to.type.getParameterTypes();
1158 if (useVarargs &&
1159 (from.flags() & VARARGS) != 0 &&
1160 (to.flags() & VARARGS) != 0) {
1161 Type varargsTypeFrom = fromArgs.last();
1162 Type varargsTypeTo = toArgs.last();
1163 ListBuffer<Type> args = ListBuffer.lb();
1164 if (toArgs.length() < fromArgs.length()) {
1165 //if we are checking a varargs method 'from' against another varargs
1166 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
1167 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
1168 //until 'to' signature has the same arity as 'from')
1169 while (fromArgs.head != varargsTypeFrom) {
1170 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
1171 fromArgs = fromArgs.tail;
1172 toArgs = toArgs.head == varargsTypeTo ?
1173 toArgs :
1174 toArgs.tail;
1175 }
1176 } else {
1177 //formal argument list is same as original list where last
1178 //argument (array type) is removed
1179 args.appendList(toArgs.reverse().tail.reverse());
1180 }
1181 //append varargs element type as last synthetic formal
1182 args.append(types.elemtype(varargsTypeTo));
1183 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
1184 return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
1185 } else {
1186 return to;
1187 }
1188 }
1189 //where
1190 Type mostSpecificReturnType(Type mt1, Type mt2) {
1191 Type rt1 = mt1.getReturnType();
1192 Type rt2 = mt2.getReturnType();
1194 if (mt1.tag == FORALL && mt2.tag == FORALL) {
1195 //if both are generic methods, adjust return type ahead of subtyping check
1196 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1197 }
1198 //first use subtyping, then return type substitutability
1199 if (types.isSubtype(rt1, rt2)) {
1200 return mt1;
1201 } else if (types.isSubtype(rt2, rt1)) {
1202 return mt2;
1203 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1204 return mt1;
1205 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1206 return mt2;
1207 } else {
1208 return null;
1209 }
1210 }
1211 //where
1212 Symbol ambiguityError(Symbol m1, Symbol m2) {
1213 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1214 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1215 } else {
1216 return new AmbiguityError(m1, m2);
1217 }
1218 }
1220 /** Find best qualified method matching given name, type and value
1221 * arguments.
1222 * @param env The current environment.
1223 * @param site The original type from where the selection
1224 * takes place.
1225 * @param name The method's name.
1226 * @param argtypes The method's value arguments.
1227 * @param typeargtypes The method's type arguments
1228 * @param allowBoxing Allow boxing conversions of arguments.
1229 * @param useVarargs Box trailing arguments into an array for varargs.
1230 */
1231 Symbol findMethod(Env<AttrContext> env,
1232 Type site,
1233 Name name,
1234 List<Type> argtypes,
1235 List<Type> typeargtypes,
1236 boolean allowBoxing,
1237 boolean useVarargs,
1238 boolean operator) {
1239 Symbol bestSoFar = methodNotFound;
1240 bestSoFar = findMethod(env,
1241 site,
1242 name,
1243 argtypes,
1244 typeargtypes,
1245 site.tsym.type,
1246 bestSoFar,
1247 allowBoxing,
1248 useVarargs,
1249 operator);
1250 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1251 return bestSoFar;
1252 }
1253 // where
1254 private Symbol findMethod(Env<AttrContext> env,
1255 Type site,
1256 Name name,
1257 List<Type> argtypes,
1258 List<Type> typeargtypes,
1259 Type intype,
1260 Symbol bestSoFar,
1261 boolean allowBoxing,
1262 boolean useVarargs,
1263 boolean operator) {
1264 boolean abstractOk = true;
1265 List<Type> itypes = List.nil();
1266 for (TypeSymbol s : superclasses(intype)) {
1267 bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
1268 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1269 //We should not look for abstract methods if receiver is a concrete class
1270 //(as concrete classes are expected to implement all abstracts coming
1271 //from superinterfaces)
1272 abstractOk &= (s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0;
1273 if (abstractOk) {
1274 for (Type itype : types.interfaces(s.type)) {
1275 itypes = types.union(types.closure(itype), itypes);
1276 }
1277 }
1278 if (name == names.init) break;
1279 }
1281 Symbol concrete = bestSoFar.kind < ERR &&
1282 (bestSoFar.flags() & ABSTRACT) == 0 ?
1283 bestSoFar : methodNotFound;
1285 if (name != names.init) {
1286 //keep searching for abstract methods
1287 for (Type itype : itypes) {
1288 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1289 bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
1290 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1291 if (concrete != bestSoFar &&
1292 concrete.kind < ERR && bestSoFar.kind < ERR &&
1293 types.isSubSignature(concrete.type, bestSoFar.type)) {
1294 //this is an hack - as javac does not do full membership checks
1295 //most specific ends up comparing abstract methods that might have
1296 //been implemented by some concrete method in a subclass and,
1297 //because of raw override, it is possible for an abstract method
1298 //to be more specific than the concrete method - so we need
1299 //to explicitly call that out (see CR 6178365)
1300 bestSoFar = concrete;
1301 }
1302 }
1303 }
1304 return bestSoFar;
1305 }
1307 /**
1308 * Return an Iterable object to scan the superclasses of a given type.
1309 * It's crucial that the scan is done lazily, as we don't want to accidentally
1310 * access more supertypes than strictly needed (as this could trigger completion
1311 * errors if some of the not-needed supertypes are missing/ill-formed).
1312 */
1313 Iterable<TypeSymbol> superclasses(final Type intype) {
1314 return new Iterable<TypeSymbol>() {
1315 public Iterator<TypeSymbol> iterator() {
1316 return new Iterator<TypeSymbol>() {
1318 List<TypeSymbol> seen = List.nil();
1319 TypeSymbol currentSym = symbolFor(intype);
1320 TypeSymbol prevSym = null;
1322 public boolean hasNext() {
1323 if (currentSym == syms.noSymbol) {
1324 currentSym = symbolFor(types.supertype(prevSym.type));
1325 }
1326 return currentSym != null;
1327 }
1329 public TypeSymbol next() {
1330 prevSym = currentSym;
1331 currentSym = syms.noSymbol;
1332 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1333 return prevSym;
1334 }
1336 public void remove() {
1337 throw new UnsupportedOperationException();
1338 }
1340 TypeSymbol symbolFor(Type t) {
1341 if (t.tag != CLASS &&
1342 t.tag != TYPEVAR) {
1343 return null;
1344 }
1345 while (t.tag == TYPEVAR)
1346 t = t.getUpperBound();
1347 if (seen.contains(t.tsym)) {
1348 //degenerate case in which we have a circular
1349 //class hierarchy - because of ill-formed classfiles
1350 return null;
1351 }
1352 seen = seen.prepend(t.tsym);
1353 return t.tsym;
1354 }
1355 };
1356 }
1357 };
1358 }
1360 /**
1361 * Lookup a method with given name and argument types in a given scope
1362 */
1363 Symbol lookupMethod(Env<AttrContext> env,
1364 Type site,
1365 Name name,
1366 List<Type> argtypes,
1367 List<Type> typeargtypes,
1368 Scope sc,
1369 Symbol bestSoFar,
1370 boolean allowBoxing,
1371 boolean useVarargs,
1372 boolean operator,
1373 boolean abstractok) {
1374 for (Symbol s : sc.getElementsByName(name, lookupFilter)) {
1375 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1376 bestSoFar, allowBoxing, useVarargs, operator);
1377 }
1378 return bestSoFar;
1379 }
1380 //where
1381 Filter<Symbol> lookupFilter = new Filter<Symbol>() {
1382 public boolean accepts(Symbol s) {
1383 return s.kind == MTH &&
1384 (s.flags() & SYNTHETIC) == 0;
1385 }
1386 };
1388 /** Find unqualified method matching given name, type and value arguments.
1389 * @param env The current environment.
1390 * @param name The method's name.
1391 * @param argtypes The method's value arguments.
1392 * @param typeargtypes The method's type arguments.
1393 * @param allowBoxing Allow boxing conversions of arguments.
1394 * @param useVarargs Box trailing arguments into an array for varargs.
1395 */
1396 Symbol findFun(Env<AttrContext> env, Name name,
1397 List<Type> argtypes, List<Type> typeargtypes,
1398 boolean allowBoxing, boolean useVarargs) {
1399 Symbol bestSoFar = methodNotFound;
1400 Symbol sym;
1401 Env<AttrContext> env1 = env;
1402 boolean staticOnly = false;
1403 while (env1.outer != null) {
1404 if (isStatic(env1)) staticOnly = true;
1405 sym = findMethod(
1406 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1407 allowBoxing, useVarargs, false);
1408 if (sym.exists()) {
1409 if (staticOnly &&
1410 sym.kind == MTH &&
1411 sym.owner.kind == TYP &&
1412 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1413 else return sym;
1414 } else if (sym.kind < bestSoFar.kind) {
1415 bestSoFar = sym;
1416 }
1417 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1418 env1 = env1.outer;
1419 }
1421 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1422 typeargtypes, allowBoxing, useVarargs, false);
1423 if (sym.exists())
1424 return sym;
1426 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1427 for (; e.scope != null; e = e.next()) {
1428 sym = e.sym;
1429 Type origin = e.getOrigin().owner.type;
1430 if (sym.kind == MTH) {
1431 if (e.sym.owner.type != origin)
1432 sym = sym.clone(e.getOrigin().owner);
1433 if (!isAccessible(env, origin, sym))
1434 sym = new AccessError(env, origin, sym);
1435 bestSoFar = selectBest(env, origin,
1436 argtypes, typeargtypes,
1437 sym, bestSoFar,
1438 allowBoxing, useVarargs, false);
1439 }
1440 }
1441 if (bestSoFar.exists())
1442 return bestSoFar;
1444 e = env.toplevel.starImportScope.lookup(name);
1445 for (; e.scope != null; e = e.next()) {
1446 sym = e.sym;
1447 Type origin = e.getOrigin().owner.type;
1448 if (sym.kind == MTH) {
1449 if (e.sym.owner.type != origin)
1450 sym = sym.clone(e.getOrigin().owner);
1451 if (!isAccessible(env, origin, sym))
1452 sym = new AccessError(env, origin, sym);
1453 bestSoFar = selectBest(env, origin,
1454 argtypes, typeargtypes,
1455 sym, bestSoFar,
1456 allowBoxing, useVarargs, false);
1457 }
1458 }
1459 return bestSoFar;
1460 }
1462 /** Load toplevel or member class with given fully qualified name and
1463 * verify that it is accessible.
1464 * @param env The current environment.
1465 * @param name The fully qualified name of the class to be loaded.
1466 */
1467 Symbol loadClass(Env<AttrContext> env, Name name) {
1468 try {
1469 ClassSymbol c = reader.loadClass(name);
1470 return isAccessible(env, c) ? c : new AccessError(c);
1471 } catch (ClassReader.BadClassFile err) {
1472 throw err;
1473 } catch (CompletionFailure ex) {
1474 return typeNotFound;
1475 }
1476 }
1478 /** Find qualified member type.
1479 * @param env The current environment.
1480 * @param site The original type from where the selection takes
1481 * place.
1482 * @param name The type's name.
1483 * @param c The class to search for the member type. This is
1484 * always a superclass or implemented interface of
1485 * site's class.
1486 */
1487 Symbol findMemberType(Env<AttrContext> env,
1488 Type site,
1489 Name name,
1490 TypeSymbol c) {
1491 Symbol bestSoFar = typeNotFound;
1492 Symbol sym;
1493 Scope.Entry e = c.members().lookup(name);
1494 while (e.scope != null) {
1495 if (e.sym.kind == TYP) {
1496 return isAccessible(env, site, e.sym)
1497 ? e.sym
1498 : new AccessError(env, site, e.sym);
1499 }
1500 e = e.next();
1501 }
1502 Type st = types.supertype(c.type);
1503 if (st != null && st.tag == CLASS) {
1504 sym = findMemberType(env, site, name, st.tsym);
1505 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1506 }
1507 for (List<Type> l = types.interfaces(c.type);
1508 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1509 l = l.tail) {
1510 sym = findMemberType(env, site, name, l.head.tsym);
1511 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1512 sym.owner != bestSoFar.owner)
1513 bestSoFar = new AmbiguityError(bestSoFar, sym);
1514 else if (sym.kind < bestSoFar.kind)
1515 bestSoFar = sym;
1516 }
1517 return bestSoFar;
1518 }
1520 /** Find a global type in given scope and load corresponding class.
1521 * @param env The current environment.
1522 * @param scope The scope in which to look for the type.
1523 * @param name The type's name.
1524 */
1525 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1526 Symbol bestSoFar = typeNotFound;
1527 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1528 Symbol sym = loadClass(env, e.sym.flatName());
1529 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1530 bestSoFar != sym)
1531 return new AmbiguityError(bestSoFar, sym);
1532 else if (sym.kind < bestSoFar.kind)
1533 bestSoFar = sym;
1534 }
1535 return bestSoFar;
1536 }
1538 /** Find an unqualified type symbol.
1539 * @param env The current environment.
1540 * @param name The type's name.
1541 */
1542 Symbol findType(Env<AttrContext> env, Name name) {
1543 Symbol bestSoFar = typeNotFound;
1544 Symbol sym;
1545 boolean staticOnly = false;
1546 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1547 if (isStatic(env1)) staticOnly = true;
1548 for (Scope.Entry e = env1.info.scope.lookup(name);
1549 e.scope != null;
1550 e = e.next()) {
1551 if (e.sym.kind == TYP) {
1552 if (staticOnly &&
1553 e.sym.type.tag == TYPEVAR &&
1554 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1555 return e.sym;
1556 }
1557 }
1559 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1560 env1.enclClass.sym);
1561 if (staticOnly && sym.kind == TYP &&
1562 sym.type.tag == CLASS &&
1563 sym.type.getEnclosingType().tag == CLASS &&
1564 env1.enclClass.sym.type.isParameterized() &&
1565 sym.type.getEnclosingType().isParameterized())
1566 return new StaticError(sym);
1567 else if (sym.exists()) return sym;
1568 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1570 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1571 if ((encl.sym.flags() & STATIC) != 0)
1572 staticOnly = true;
1573 }
1575 if (!env.tree.hasTag(IMPORT)) {
1576 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1577 if (sym.exists()) return sym;
1578 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1580 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1581 if (sym.exists()) return sym;
1582 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1584 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1585 if (sym.exists()) return sym;
1586 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1587 }
1589 return bestSoFar;
1590 }
1592 /** Find an unqualified identifier which matches a specified kind set.
1593 * @param env The current environment.
1594 * @param name The indentifier's name.
1595 * @param kind Indicates the possible symbol kinds
1596 * (a subset of VAL, TYP, PCK).
1597 */
1598 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1599 Symbol bestSoFar = typeNotFound;
1600 Symbol sym;
1602 if ((kind & VAR) != 0) {
1603 sym = findVar(env, name);
1604 if (sym.exists()) return sym;
1605 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1606 }
1608 if ((kind & TYP) != 0) {
1609 sym = findType(env, name);
1610 if (sym.exists()) return sym;
1611 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1612 }
1614 if ((kind & PCK) != 0) return reader.enterPackage(name);
1615 else return bestSoFar;
1616 }
1618 /** Find an identifier in a package which matches a specified kind set.
1619 * @param env The current environment.
1620 * @param name The identifier's name.
1621 * @param kind Indicates the possible symbol kinds
1622 * (a nonempty subset of TYP, PCK).
1623 */
1624 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1625 Name name, int kind) {
1626 Name fullname = TypeSymbol.formFullName(name, pck);
1627 Symbol bestSoFar = typeNotFound;
1628 PackageSymbol pack = null;
1629 if ((kind & PCK) != 0) {
1630 pack = reader.enterPackage(fullname);
1631 if (pack.exists()) return pack;
1632 }
1633 if ((kind & TYP) != 0) {
1634 Symbol sym = loadClass(env, fullname);
1635 if (sym.exists()) {
1636 // don't allow programs to use flatnames
1637 if (name == sym.name) return sym;
1638 }
1639 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1640 }
1641 return (pack != null) ? pack : bestSoFar;
1642 }
1644 /** Find an identifier among the members of a given type `site'.
1645 * @param env The current environment.
1646 * @param site The type containing the symbol to be found.
1647 * @param name The identifier's name.
1648 * @param kind Indicates the possible symbol kinds
1649 * (a subset of VAL, TYP).
1650 */
1651 Symbol findIdentInType(Env<AttrContext> env, Type site,
1652 Name name, int kind) {
1653 Symbol bestSoFar = typeNotFound;
1654 Symbol sym;
1655 if ((kind & VAR) != 0) {
1656 sym = findField(env, site, name, site.tsym);
1657 if (sym.exists()) return sym;
1658 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1659 }
1661 if ((kind & TYP) != 0) {
1662 sym = findMemberType(env, site, name, site.tsym);
1663 if (sym.exists()) return sym;
1664 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1665 }
1666 return bestSoFar;
1667 }
1669 /* ***************************************************************************
1670 * Access checking
1671 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1672 * an error message in the process
1673 ****************************************************************************/
1675 /** If `sym' is a bad symbol: report error and return errSymbol
1676 * else pass through unchanged,
1677 * additional arguments duplicate what has been used in trying to find the
1678 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
1679 * expect misses to happen frequently.
1680 *
1681 * @param sym The symbol that was found, or a ResolveError.
1682 * @param pos The position to use for error reporting.
1683 * @param location The symbol the served as a context for this lookup
1684 * @param site The original type from where the selection took place.
1685 * @param name The symbol's name.
1686 * @param qualified Did we get here through a qualified expression resolution?
1687 * @param argtypes The invocation's value arguments,
1688 * if we looked for a method.
1689 * @param typeargtypes The invocation's type arguments,
1690 * if we looked for a method.
1691 * @param logResolveHelper helper class used to log resolve errors
1692 */
1693 Symbol accessInternal(Symbol sym,
1694 DiagnosticPosition pos,
1695 Symbol location,
1696 Type site,
1697 Name name,
1698 boolean qualified,
1699 List<Type> argtypes,
1700 List<Type> typeargtypes,
1701 LogResolveHelper logResolveHelper) {
1702 if (sym.kind >= AMBIGUOUS) {
1703 ResolveError errSym = (ResolveError)sym;
1704 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1705 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
1706 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
1707 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1708 }
1709 }
1710 return sym;
1711 }
1713 /**
1714 * Variant of the generalized access routine, to be used for generating method
1715 * resolution diagnostics
1716 */
1717 Symbol accessMethod(Symbol sym,
1718 DiagnosticPosition pos,
1719 Symbol location,
1720 Type site,
1721 Name name,
1722 boolean qualified,
1723 List<Type> argtypes,
1724 List<Type> typeargtypes) {
1725 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
1726 }
1728 /** Same as original accessMethod(), but without location.
1729 */
1730 Symbol accessMethod(Symbol sym,
1731 DiagnosticPosition pos,
1732 Type site,
1733 Name name,
1734 boolean qualified,
1735 List<Type> argtypes,
1736 List<Type> typeargtypes) {
1737 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1738 }
1740 /**
1741 * Variant of the generalized access routine, to be used for generating variable,
1742 * type resolution diagnostics
1743 */
1744 Symbol accessBase(Symbol sym,
1745 DiagnosticPosition pos,
1746 Symbol location,
1747 Type site,
1748 Name name,
1749 boolean qualified) {
1750 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
1751 }
1753 /** Same as original accessBase(), but without location.
1754 */
1755 Symbol accessBase(Symbol sym,
1756 DiagnosticPosition pos,
1757 Type site,
1758 Name name,
1759 boolean qualified) {
1760 return accessBase(sym, pos, site.tsym, site, name, qualified);
1761 }
1763 interface LogResolveHelper {
1764 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
1765 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
1766 }
1768 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
1769 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1770 return !site.isErroneous();
1771 }
1772 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1773 return argtypes;
1774 }
1775 };
1777 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
1778 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1779 return !site.isErroneous() &&
1780 !Type.isErroneous(argtypes) &&
1781 (typeargtypes == null || !Type.isErroneous(typeargtypes));
1782 }
1783 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1784 if (syms.operatorNames.contains(name)) {
1785 return argtypes;
1786 } else {
1787 Symbol msym = errSym.kind == WRONG_MTH ?
1788 ((InapplicableSymbolError)errSym).errCandidate().sym : accessedSym;
1790 List<Type> argtypes2 = Type.map(argtypes,
1791 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, msym, currentResolutionContext.firstErroneousResolutionPhase()));
1793 if (msym != accessedSym) {
1794 //fixup deferred type caches - this 'hack' is required because the symbol
1795 //returned by InapplicableSymbolError.access() will hide the candidate
1796 //method symbol that can be used for lookups in the speculative cache,
1797 //causing problems in Attr.checkId()
1798 for (Type t : argtypes) {
1799 if (t.tag == DEFERRED) {
1800 DeferredType dt = (DeferredType)t;
1801 dt.speculativeCache.dupAllTo(msym, accessedSym);
1802 }
1803 }
1804 }
1805 return argtypes2;
1806 }
1807 }
1808 };
1810 /** Check that sym is not an abstract method.
1811 */
1812 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1813 if ((sym.flags() & ABSTRACT) != 0)
1814 log.error(pos, "abstract.cant.be.accessed.directly",
1815 kindName(sym), sym, sym.location());
1816 }
1818 /* ***************************************************************************
1819 * Debugging
1820 ****************************************************************************/
1822 /** print all scopes starting with scope s and proceeding outwards.
1823 * used for debugging.
1824 */
1825 public void printscopes(Scope s) {
1826 while (s != null) {
1827 if (s.owner != null)
1828 System.err.print(s.owner + ": ");
1829 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1830 if ((e.sym.flags() & ABSTRACT) != 0)
1831 System.err.print("abstract ");
1832 System.err.print(e.sym + " ");
1833 }
1834 System.err.println();
1835 s = s.next;
1836 }
1837 }
1839 void printscopes(Env<AttrContext> env) {
1840 while (env.outer != null) {
1841 System.err.println("------------------------------");
1842 printscopes(env.info.scope);
1843 env = env.outer;
1844 }
1845 }
1847 public void printscopes(Type t) {
1848 while (t.tag == CLASS) {
1849 printscopes(t.tsym.members());
1850 t = types.supertype(t);
1851 }
1852 }
1854 /* ***************************************************************************
1855 * Name resolution
1856 * Naming conventions are as for symbol lookup
1857 * Unlike the find... methods these methods will report access errors
1858 ****************************************************************************/
1860 /** Resolve an unqualified (non-method) identifier.
1861 * @param pos The position to use for error reporting.
1862 * @param env The environment current at the identifier use.
1863 * @param name The identifier's name.
1864 * @param kind The set of admissible symbol kinds for the identifier.
1865 */
1866 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1867 Name name, int kind) {
1868 return accessBase(
1869 findIdent(env, name, kind),
1870 pos, env.enclClass.sym.type, name, false);
1871 }
1873 /** Resolve an unqualified method identifier.
1874 * @param pos The position to use for error reporting.
1875 * @param env The environment current at the method invocation.
1876 * @param name The identifier's name.
1877 * @param argtypes The types of the invocation's value arguments.
1878 * @param typeargtypes The types of the invocation's type arguments.
1879 */
1880 Symbol resolveMethod(DiagnosticPosition pos,
1881 Env<AttrContext> env,
1882 Name name,
1883 List<Type> argtypes,
1884 List<Type> typeargtypes) {
1885 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1886 try {
1887 currentResolutionContext = new MethodResolutionContext();
1888 Symbol sym = methodNotFound;
1889 List<MethodResolutionPhase> steps = methodResolutionSteps;
1890 while (steps.nonEmpty() &&
1891 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1892 sym.kind >= ERRONEOUS) {
1893 currentResolutionContext.step = env.info.pendingResolutionPhase = steps.head;
1894 sym = findFun(env, name, argtypes, typeargtypes,
1895 steps.head.isBoxingRequired,
1896 steps.head.isVarargsRequired);
1897 currentResolutionContext.resolutionCache.put(steps.head, sym);
1898 steps = steps.tail;
1899 }
1900 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1901 MethodResolutionPhase errPhase =
1902 currentResolutionContext.firstErroneousResolutionPhase();
1903 sym = accessMethod(currentResolutionContext.resolutionCache.get(errPhase),
1904 pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1905 env.info.pendingResolutionPhase = errPhase;
1906 }
1907 return sym;
1908 }
1909 finally {
1910 currentResolutionContext = prevResolutionContext;
1911 }
1912 }
1914 /** Resolve a qualified method identifier
1915 * @param pos The position to use for error reporting.
1916 * @param env The environment current at the method invocation.
1917 * @param site The type of the qualifying expression, in which
1918 * identifier is searched.
1919 * @param name The identifier's name.
1920 * @param argtypes The types of the invocation's value arguments.
1921 * @param typeargtypes The types of the invocation's type arguments.
1922 */
1923 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1924 Type site, Name name, List<Type> argtypes,
1925 List<Type> typeargtypes) {
1926 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
1927 }
1928 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1929 Symbol location, Type site, Name name, List<Type> argtypes,
1930 List<Type> typeargtypes) {
1931 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
1932 }
1933 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
1934 DiagnosticPosition pos, Env<AttrContext> env,
1935 Symbol location, Type site, Name name, List<Type> argtypes,
1936 List<Type> typeargtypes) {
1937 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1938 try {
1939 currentResolutionContext = resolveContext;
1940 Symbol sym = methodNotFound;
1941 List<MethodResolutionPhase> steps = methodResolutionSteps;
1942 while (steps.nonEmpty() &&
1943 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1944 sym.kind >= ERRONEOUS) {
1945 currentResolutionContext.step = env.info.pendingResolutionPhase = steps.head;
1946 sym = findMethod(env, site, name, argtypes, typeargtypes,
1947 steps.head.isBoxingRequired(),
1948 steps.head.isVarargsRequired(), false);
1949 currentResolutionContext.resolutionCache.put(steps.head, sym);
1950 steps = steps.tail;
1951 }
1952 if (sym.kind >= AMBIGUOUS) {
1953 //if nothing is found return the 'first' error
1954 MethodResolutionPhase errPhase =
1955 currentResolutionContext.firstErroneousResolutionPhase();
1956 sym = accessMethod(currentResolutionContext.resolutionCache.get(errPhase),
1957 pos, location, site, name, true, argtypes, typeargtypes);
1958 env.info.pendingResolutionPhase = errPhase;
1959 } else if (allowMethodHandles) {
1960 MethodSymbol msym = (MethodSymbol)sym;
1961 if (msym.isSignaturePolymorphic(types)) {
1962 env.info.pendingResolutionPhase = BASIC;
1963 return findPolymorphicSignatureInstance(env, sym, argtypes);
1964 }
1965 }
1966 return sym;
1967 }
1968 finally {
1969 currentResolutionContext = prevResolutionContext;
1970 }
1971 }
1973 /** Find or create an implicit method of exactly the given type (after erasure).
1974 * Searches in a side table, not the main scope of the site.
1975 * This emulates the lookup process required by JSR 292 in JVM.
1976 * @param env Attribution environment
1977 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
1978 * @param argtypes The required argument types
1979 */
1980 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
1981 Symbol spMethod,
1982 List<Type> argtypes) {
1983 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
1984 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
1985 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
1986 if (types.isSameType(mtype, sym.type)) {
1987 return sym;
1988 }
1989 }
1991 // create the desired method
1992 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
1993 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
1994 polymorphicSignatureScope.enter(msym);
1995 return msym;
1996 }
1998 /** Resolve a qualified method identifier, throw a fatal error if not
1999 * found.
2000 * @param pos The position to use for error reporting.
2001 * @param env The environment current at the method invocation.
2002 * @param site The type of the qualifying expression, in which
2003 * identifier is searched.
2004 * @param name The identifier's name.
2005 * @param argtypes The types of the invocation's value arguments.
2006 * @param typeargtypes The types of the invocation's type arguments.
2007 */
2008 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2009 Type site, Name name,
2010 List<Type> argtypes,
2011 List<Type> typeargtypes) {
2012 MethodResolutionContext resolveContext = new MethodResolutionContext();
2013 resolveContext.internalResolution = true;
2014 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2015 site, name, argtypes, typeargtypes);
2016 if (sym.kind == MTH) return (MethodSymbol)sym;
2017 else throw new FatalError(
2018 diags.fragment("fatal.err.cant.locate.meth",
2019 name));
2020 }
2022 /** Resolve constructor.
2023 * @param pos The position to use for error reporting.
2024 * @param env The environment current at the constructor invocation.
2025 * @param site The type of class for which a constructor is searched.
2026 * @param argtypes The types of the constructor invocation's value
2027 * arguments.
2028 * @param typeargtypes The types of the constructor invocation's type
2029 * arguments.
2030 */
2031 Symbol resolveConstructor(DiagnosticPosition pos,
2032 Env<AttrContext> env,
2033 Type site,
2034 List<Type> argtypes,
2035 List<Type> typeargtypes) {
2036 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2037 }
2038 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2039 DiagnosticPosition pos,
2040 Env<AttrContext> env,
2041 Type site,
2042 List<Type> argtypes,
2043 List<Type> typeargtypes) {
2044 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2045 try {
2046 currentResolutionContext = resolveContext;
2047 Symbol sym = methodNotFound;
2048 List<MethodResolutionPhase> steps = methodResolutionSteps;
2049 while (steps.nonEmpty() &&
2050 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2051 sym.kind >= ERRONEOUS) {
2052 currentResolutionContext.step = env.info.pendingResolutionPhase = steps.head;
2053 sym = findConstructor(pos, env, site, argtypes, typeargtypes,
2054 steps.head.isBoxingRequired(),
2055 steps.head.isVarargsRequired());
2056 currentResolutionContext.resolutionCache.put(steps.head, sym);
2057 steps = steps.tail;
2058 }
2059 if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
2060 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
2061 sym = accessMethod(currentResolutionContext.resolutionCache.get(errPhase),
2062 pos, site, names.init, true, argtypes, typeargtypes);
2063 env.info.pendingResolutionPhase = errPhase;
2064 }
2065 return sym;
2066 }
2067 finally {
2068 currentResolutionContext = prevResolutionContext;
2069 }
2070 }
2072 /** Resolve constructor using diamond inference.
2073 * @param pos The position to use for error reporting.
2074 * @param env The environment current at the constructor invocation.
2075 * @param site The type of class for which a constructor is searched.
2076 * The scope of this class has been touched in attribution.
2077 * @param argtypes The types of the constructor invocation's value
2078 * arguments.
2079 * @param typeargtypes The types of the constructor invocation's type
2080 * arguments.
2081 */
2082 Symbol resolveDiamond(DiagnosticPosition pos,
2083 Env<AttrContext> env,
2084 Type site,
2085 List<Type> argtypes,
2086 List<Type> typeargtypes) {
2087 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2088 try {
2089 currentResolutionContext = new MethodResolutionContext();
2090 Symbol sym = methodNotFound;
2091 List<MethodResolutionPhase> steps = methodResolutionSteps;
2092 while (steps.nonEmpty() &&
2093 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2094 sym.kind >= ERRONEOUS) {
2095 currentResolutionContext.step = env.info.pendingResolutionPhase = steps.head;
2096 sym = findDiamond(env, site, argtypes, typeargtypes,
2097 steps.head.isBoxingRequired(),
2098 steps.head.isVarargsRequired());
2099 currentResolutionContext.resolutionCache.put(steps.head, sym);
2100 steps = steps.tail;
2101 }
2102 if (sym.kind >= AMBIGUOUS) {
2103 Symbol errSym =
2104 currentResolutionContext.resolutionCache.get(currentResolutionContext.firstErroneousResolutionPhase());
2105 final JCDiagnostic details = errSym.kind == WRONG_MTH ?
2106 ((InapplicableSymbolError)errSym).errCandidate().details :
2107 null;
2108 errSym = new InapplicableSymbolError(errSym.kind, "diamondError") {
2109 @Override
2110 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2111 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2112 String key = details == null ?
2113 "cant.apply.diamond" :
2114 "cant.apply.diamond.1";
2115 return diags.create(dkind, log.currentSource(), pos, key,
2116 diags.fragment("diamond", site.tsym), details);
2117 }
2118 };
2119 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
2120 sym = accessMethod(errSym, pos, site, names.init, true, argtypes, typeargtypes);
2121 env.info.pendingResolutionPhase = errPhase;
2122 }
2123 return sym;
2124 }
2125 finally {
2126 currentResolutionContext = prevResolutionContext;
2127 }
2128 }
2130 /** This method scans all the constructor symbol in a given class scope -
2131 * assuming that the original scope contains a constructor of the kind:
2132 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2133 * a method check is executed against the modified constructor type:
2134 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2135 * inference. The inferred return type of the synthetic constructor IS
2136 * the inferred type for the diamond operator.
2137 */
2138 private Symbol findDiamond(Env<AttrContext> env,
2139 Type site,
2140 List<Type> argtypes,
2141 List<Type> typeargtypes,
2142 boolean allowBoxing,
2143 boolean useVarargs) {
2144 Symbol bestSoFar = methodNotFound;
2145 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2146 e.scope != null;
2147 e = e.next()) {
2148 final Symbol sym = e.sym;
2149 //- System.out.println(" e " + e.sym);
2150 if (sym.kind == MTH &&
2151 (sym.flags_field & SYNTHETIC) == 0) {
2152 List<Type> oldParams = e.sym.type.tag == FORALL ?
2153 ((ForAll)sym.type).tvars :
2154 List.<Type>nil();
2155 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2156 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2157 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2158 @Override
2159 public Symbol baseSymbol() {
2160 return sym;
2161 }
2162 };
2163 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2164 newConstr,
2165 bestSoFar,
2166 allowBoxing,
2167 useVarargs,
2168 false);
2169 }
2170 }
2171 return bestSoFar;
2172 }
2174 /** Resolve constructor.
2175 * @param pos The position to use for error reporting.
2176 * @param env The environment current at the constructor invocation.
2177 * @param site The type of class for which a constructor is searched.
2178 * @param argtypes The types of the constructor invocation's value
2179 * arguments.
2180 * @param typeargtypes The types of the constructor invocation's type
2181 * arguments.
2182 * @param allowBoxing Allow boxing and varargs conversions.
2183 * @param useVarargs Box trailing arguments into an array for varargs.
2184 */
2185 Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2186 Type site, List<Type> argtypes,
2187 List<Type> typeargtypes,
2188 boolean allowBoxing,
2189 boolean useVarargs) {
2190 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2191 try {
2192 currentResolutionContext = new MethodResolutionContext();
2193 return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
2194 }
2195 finally {
2196 currentResolutionContext = prevResolutionContext;
2197 }
2198 }
2200 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2201 Type site, List<Type> argtypes,
2202 List<Type> typeargtypes,
2203 boolean allowBoxing,
2204 boolean useVarargs) {
2205 Symbol sym = findMethod(env, site,
2206 names.init, argtypes,
2207 typeargtypes, allowBoxing,
2208 useVarargs, false);
2209 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2210 return sym;
2211 }
2213 /** Resolve a constructor, throw a fatal error if not found.
2214 * @param pos The position to use for error reporting.
2215 * @param env The environment current at the method invocation.
2216 * @param site The type to be constructed.
2217 * @param argtypes The types of the invocation's value arguments.
2218 * @param typeargtypes The types of the invocation's type arguments.
2219 */
2220 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2221 Type site,
2222 List<Type> argtypes,
2223 List<Type> typeargtypes) {
2224 MethodResolutionContext resolveContext = new MethodResolutionContext();
2225 resolveContext.internalResolution = true;
2226 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2227 if (sym.kind == MTH) return (MethodSymbol)sym;
2228 else throw new FatalError(
2229 diags.fragment("fatal.err.cant.locate.ctor", site));
2230 }
2232 /** Resolve operator.
2233 * @param pos The position to use for error reporting.
2234 * @param optag The tag of the operation tree.
2235 * @param env The environment current at the operation.
2236 * @param argtypes The types of the operands.
2237 */
2238 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2239 Env<AttrContext> env, List<Type> argtypes) {
2240 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2241 try {
2242 currentResolutionContext = new MethodResolutionContext();
2243 Name name = treeinfo.operatorName(optag);
2244 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2245 null, false, false, true);
2246 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2247 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2248 null, true, false, true);
2249 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2250 false, argtypes, null);
2251 }
2252 finally {
2253 currentResolutionContext = prevResolutionContext;
2254 }
2255 }
2257 /** Resolve operator.
2258 * @param pos The position to use for error reporting.
2259 * @param optag The tag of the operation tree.
2260 * @param env The environment current at the operation.
2261 * @param arg The type of the operand.
2262 */
2263 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2264 return resolveOperator(pos, optag, env, List.of(arg));
2265 }
2267 /** Resolve binary operator.
2268 * @param pos The position to use for error reporting.
2269 * @param optag The tag of the operation tree.
2270 * @param env The environment current at the operation.
2271 * @param left The types of the left operand.
2272 * @param right The types of the right operand.
2273 */
2274 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2275 JCTree.Tag optag,
2276 Env<AttrContext> env,
2277 Type left,
2278 Type right) {
2279 return resolveOperator(pos, optag, env, List.of(left, right));
2280 }
2282 /**
2283 * Resolve `c.name' where name == this or name == super.
2284 * @param pos The position to use for error reporting.
2285 * @param env The environment current at the expression.
2286 * @param c The qualifier.
2287 * @param name The identifier's name.
2288 */
2289 Symbol resolveSelf(DiagnosticPosition pos,
2290 Env<AttrContext> env,
2291 TypeSymbol c,
2292 Name name) {
2293 Env<AttrContext> env1 = env;
2294 boolean staticOnly = false;
2295 while (env1.outer != null) {
2296 if (isStatic(env1)) staticOnly = true;
2297 if (env1.enclClass.sym == c) {
2298 Symbol sym = env1.info.scope.lookup(name).sym;
2299 if (sym != null) {
2300 if (staticOnly) sym = new StaticError(sym);
2301 return accessBase(sym, pos, env.enclClass.sym.type,
2302 name, true);
2303 }
2304 }
2305 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2306 env1 = env1.outer;
2307 }
2308 log.error(pos, "not.encl.class", c);
2309 return syms.errSymbol;
2310 }
2312 /**
2313 * Resolve `c.this' for an enclosing class c that contains the
2314 * named member.
2315 * @param pos The position to use for error reporting.
2316 * @param env The environment current at the expression.
2317 * @param member The member that must be contained in the result.
2318 */
2319 Symbol resolveSelfContaining(DiagnosticPosition pos,
2320 Env<AttrContext> env,
2321 Symbol member,
2322 boolean isSuperCall) {
2323 Name name = names._this;
2324 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2325 boolean staticOnly = false;
2326 if (env1 != null) {
2327 while (env1 != null && env1.outer != null) {
2328 if (isStatic(env1)) staticOnly = true;
2329 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2330 Symbol sym = env1.info.scope.lookup(name).sym;
2331 if (sym != null) {
2332 if (staticOnly) sym = new StaticError(sym);
2333 return accessBase(sym, pos, env.enclClass.sym.type,
2334 name, true);
2335 }
2336 }
2337 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2338 staticOnly = true;
2339 env1 = env1.outer;
2340 }
2341 }
2342 log.error(pos, "encl.class.required", member);
2343 return syms.errSymbol;
2344 }
2346 /**
2347 * Resolve an appropriate implicit this instance for t's container.
2348 * JLS 8.8.5.1 and 15.9.2
2349 */
2350 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2351 return resolveImplicitThis(pos, env, t, false);
2352 }
2354 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2355 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2356 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2357 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2358 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2359 log.error(pos, "cant.ref.before.ctor.called", "this");
2360 return thisType;
2361 }
2363 /* ***************************************************************************
2364 * ResolveError classes, indicating error situations when accessing symbols
2365 ****************************************************************************/
2367 //used by TransTypes when checking target type of synthetic cast
2368 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2369 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2370 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2371 }
2372 //where
2373 private void logResolveError(ResolveError error,
2374 DiagnosticPosition pos,
2375 Symbol location,
2376 Type site,
2377 Name name,
2378 List<Type> argtypes,
2379 List<Type> typeargtypes) {
2380 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2381 pos, location, site, name, argtypes, typeargtypes);
2382 if (d != null) {
2383 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2384 log.report(d);
2385 }
2386 }
2388 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2390 public Object methodArguments(List<Type> argtypes) {
2391 return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
2392 }
2394 /**
2395 * Root class for resolution errors. Subclass of ResolveError
2396 * represent a different kinds of resolution error - as such they must
2397 * specify how they map into concrete compiler diagnostics.
2398 */
2399 private abstract class ResolveError extends Symbol {
2401 /** The name of the kind of error, for debugging only. */
2402 final String debugName;
2404 ResolveError(int kind, String debugName) {
2405 super(kind, 0, null, null, null);
2406 this.debugName = debugName;
2407 }
2409 @Override
2410 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2411 throw new AssertionError();
2412 }
2414 @Override
2415 public String toString() {
2416 return debugName;
2417 }
2419 @Override
2420 public boolean exists() {
2421 return false;
2422 }
2424 /**
2425 * Create an external representation for this erroneous symbol to be
2426 * used during attribution - by default this returns the symbol of a
2427 * brand new error type which stores the original type found
2428 * during resolution.
2429 *
2430 * @param name the name used during resolution
2431 * @param location the location from which the symbol is accessed
2432 */
2433 protected Symbol access(Name name, TypeSymbol location) {
2434 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2435 }
2437 /**
2438 * Create a diagnostic representing this resolution error.
2439 *
2440 * @param dkind The kind of the diagnostic to be created (e.g error).
2441 * @param pos The position to be used for error reporting.
2442 * @param site The original type from where the selection took place.
2443 * @param name The name of the symbol to be resolved.
2444 * @param argtypes The invocation's value arguments,
2445 * if we looked for a method.
2446 * @param typeargtypes The invocation's type arguments,
2447 * if we looked for a method.
2448 */
2449 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2450 DiagnosticPosition pos,
2451 Symbol location,
2452 Type site,
2453 Name name,
2454 List<Type> argtypes,
2455 List<Type> typeargtypes);
2456 }
2458 /**
2459 * This class is the root class of all resolution errors caused by
2460 * an invalid symbol being found during resolution.
2461 */
2462 abstract class InvalidSymbolError extends ResolveError {
2464 /** The invalid symbol found during resolution */
2465 Symbol sym;
2467 InvalidSymbolError(int kind, Symbol sym, String debugName) {
2468 super(kind, debugName);
2469 this.sym = sym;
2470 }
2472 @Override
2473 public boolean exists() {
2474 return true;
2475 }
2477 @Override
2478 public String toString() {
2479 return super.toString() + " wrongSym=" + sym;
2480 }
2482 @Override
2483 public Symbol access(Name name, TypeSymbol location) {
2484 if (sym.kind >= AMBIGUOUS)
2485 return ((ResolveError)sym).access(name, location);
2486 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
2487 return types.createErrorType(name, location, sym.type).tsym;
2488 else
2489 return sym;
2490 }
2491 }
2493 /**
2494 * InvalidSymbolError error class indicating that a symbol matching a
2495 * given name does not exists in a given site.
2496 */
2497 class SymbolNotFoundError extends ResolveError {
2499 SymbolNotFoundError(int kind) {
2500 super(kind, "symbol not found error");
2501 }
2503 @Override
2504 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2505 DiagnosticPosition pos,
2506 Symbol location,
2507 Type site,
2508 Name name,
2509 List<Type> argtypes,
2510 List<Type> typeargtypes) {
2511 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
2512 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
2513 if (name == names.error)
2514 return null;
2516 if (syms.operatorNames.contains(name)) {
2517 boolean isUnaryOp = argtypes.size() == 1;
2518 String key = argtypes.size() == 1 ?
2519 "operator.cant.be.applied" :
2520 "operator.cant.be.applied.1";
2521 Type first = argtypes.head;
2522 Type second = !isUnaryOp ? argtypes.tail.head : null;
2523 return diags.create(dkind, log.currentSource(), pos,
2524 key, name, first, second);
2525 }
2526 boolean hasLocation = false;
2527 if (location == null) {
2528 location = site.tsym;
2529 }
2530 if (!location.name.isEmpty()) {
2531 if (location.kind == PCK && !site.tsym.exists()) {
2532 return diags.create(dkind, log.currentSource(), pos,
2533 "doesnt.exist", location);
2534 }
2535 hasLocation = !location.name.equals(names._this) &&
2536 !location.name.equals(names._super);
2537 }
2538 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
2539 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
2540 Name idname = isConstructor ? site.tsym.name : name;
2541 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
2542 if (hasLocation) {
2543 return diags.create(dkind, log.currentSource(), pos,
2544 errKey, kindname, idname, //symbol kindname, name
2545 typeargtypes, argtypes, //type parameters and arguments (if any)
2546 getLocationDiag(location, site)); //location kindname, type
2547 }
2548 else {
2549 return diags.create(dkind, log.currentSource(), pos,
2550 errKey, kindname, idname, //symbol kindname, name
2551 typeargtypes, argtypes); //type parameters and arguments (if any)
2552 }
2553 }
2554 //where
2555 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
2556 String key = "cant.resolve";
2557 String suffix = hasLocation ? ".location" : "";
2558 switch (kindname) {
2559 case METHOD:
2560 case CONSTRUCTOR: {
2561 suffix += ".args";
2562 suffix += hasTypeArgs ? ".params" : "";
2563 }
2564 }
2565 return key + suffix;
2566 }
2567 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
2568 if (location.kind == VAR) {
2569 return diags.fragment("location.1",
2570 kindName(location),
2571 location,
2572 location.type);
2573 } else {
2574 return diags.fragment("location",
2575 typeKindName(site),
2576 site,
2577 null);
2578 }
2579 }
2580 }
2582 /**
2583 * InvalidSymbolError error class indicating that a given symbol
2584 * (either a method, a constructor or an operand) is not applicable
2585 * given an actual arguments/type argument list.
2586 */
2587 class InapplicableSymbolError extends ResolveError {
2589 InapplicableSymbolError() {
2590 super(WRONG_MTH, "inapplicable symbol error");
2591 }
2593 protected InapplicableSymbolError(int kind, String debugName) {
2594 super(kind, debugName);
2595 }
2597 @Override
2598 public String toString() {
2599 return super.toString();
2600 }
2602 @Override
2603 public boolean exists() {
2604 return true;
2605 }
2607 @Override
2608 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2609 DiagnosticPosition pos,
2610 Symbol location,
2611 Type site,
2612 Name name,
2613 List<Type> argtypes,
2614 List<Type> typeargtypes) {
2615 if (name == names.error)
2616 return null;
2618 if (syms.operatorNames.contains(name)) {
2619 boolean isUnaryOp = argtypes.size() == 1;
2620 String key = argtypes.size() == 1 ?
2621 "operator.cant.be.applied" :
2622 "operator.cant.be.applied.1";
2623 Type first = argtypes.head;
2624 Type second = !isUnaryOp ? argtypes.tail.head : null;
2625 return diags.create(dkind, log.currentSource(), pos,
2626 key, name, first, second);
2627 }
2628 else {
2629 Candidate c = errCandidate();
2630 Symbol ws = c.sym.asMemberOf(site, types);
2631 return diags.create(dkind, log.currentSource(), pos,
2632 "cant.apply.symbol" + (c.details != null ? ".1" : ""),
2633 kindName(ws),
2634 ws.name == names.init ? ws.owner.name : ws.name,
2635 methodArguments(ws.type.getParameterTypes()),
2636 methodArguments(argtypes),
2637 kindName(ws.owner),
2638 ws.owner.type,
2639 c.details);
2640 }
2641 }
2643 @Override
2644 public Symbol access(Name name, TypeSymbol location) {
2645 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2646 }
2648 protected boolean shouldReport(Candidate c) {
2649 return !c.isApplicable() &&
2650 (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
2651 (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
2652 }
2654 private Candidate errCandidate() {
2655 for (Candidate c : currentResolutionContext.candidates) {
2656 if (shouldReport(c)) {
2657 return c;
2658 }
2659 }
2660 Assert.error();
2661 return null;
2662 }
2663 }
2665 /**
2666 * ResolveError error class indicating that a set of symbols
2667 * (either methods, constructors or operands) is not applicable
2668 * given an actual arguments/type argument list.
2669 */
2670 class InapplicableSymbolsError extends InapplicableSymbolError {
2672 InapplicableSymbolsError() {
2673 super(WRONG_MTHS, "inapplicable symbols");
2674 }
2676 @Override
2677 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2678 DiagnosticPosition pos,
2679 Symbol location,
2680 Type site,
2681 Name name,
2682 List<Type> argtypes,
2683 List<Type> typeargtypes) {
2684 if (currentResolutionContext.candidates.nonEmpty()) {
2685 JCDiagnostic err = diags.create(dkind,
2686 log.currentSource(),
2687 pos,
2688 "cant.apply.symbols",
2689 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
2690 getName(),
2691 argtypes);
2692 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
2693 } else {
2694 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
2695 location, site, name, argtypes, typeargtypes);
2696 }
2697 }
2699 //where
2700 List<JCDiagnostic> candidateDetails(Type site) {
2701 List<JCDiagnostic> details = List.nil();
2702 for (Candidate c : currentResolutionContext.candidates) {
2703 if (!shouldReport(c)) continue;
2704 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
2705 Kinds.kindName(c.sym),
2706 c.sym.location(site, types),
2707 c.sym.asMemberOf(site, types),
2708 c.details);
2709 details = details.prepend(detailDiag);
2710 }
2711 return details.reverse();
2712 }
2714 private Name getName() {
2715 Symbol sym = currentResolutionContext.candidates.head.sym;
2716 return sym.name == names.init ?
2717 sym.owner.name :
2718 sym.name;
2719 }
2720 }
2722 /**
2723 * An InvalidSymbolError error class indicating that a symbol is not
2724 * accessible from a given site
2725 */
2726 class AccessError extends InvalidSymbolError {
2728 private Env<AttrContext> env;
2729 private Type site;
2731 AccessError(Symbol sym) {
2732 this(null, null, sym);
2733 }
2735 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
2736 super(HIDDEN, sym, "access error");
2737 this.env = env;
2738 this.site = site;
2739 if (debugResolve)
2740 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
2741 }
2743 @Override
2744 public boolean exists() {
2745 return false;
2746 }
2748 @Override
2749 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2750 DiagnosticPosition pos,
2751 Symbol location,
2752 Type site,
2753 Name name,
2754 List<Type> argtypes,
2755 List<Type> typeargtypes) {
2756 if (sym.owner.type.tag == ERROR)
2757 return null;
2759 if (sym.name == names.init && sym.owner != site.tsym) {
2760 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
2761 pos, location, site, name, argtypes, typeargtypes);
2762 }
2763 else if ((sym.flags() & PUBLIC) != 0
2764 || (env != null && this.site != null
2765 && !isAccessible(env, this.site))) {
2766 return diags.create(dkind, log.currentSource(),
2767 pos, "not.def.access.class.intf.cant.access",
2768 sym, sym.location());
2769 }
2770 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
2771 return diags.create(dkind, log.currentSource(),
2772 pos, "report.access", sym,
2773 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
2774 sym.location());
2775 }
2776 else {
2777 return diags.create(dkind, log.currentSource(),
2778 pos, "not.def.public.cant.access", sym, sym.location());
2779 }
2780 }
2781 }
2783 /**
2784 * InvalidSymbolError error class indicating that an instance member
2785 * has erroneously been accessed from a static context.
2786 */
2787 class StaticError extends InvalidSymbolError {
2789 StaticError(Symbol sym) {
2790 super(STATICERR, sym, "static error");
2791 }
2793 @Override
2794 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2795 DiagnosticPosition pos,
2796 Symbol location,
2797 Type site,
2798 Name name,
2799 List<Type> argtypes,
2800 List<Type> typeargtypes) {
2801 Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
2802 ? types.erasure(sym.type).tsym
2803 : sym);
2804 return diags.create(dkind, log.currentSource(), pos,
2805 "non-static.cant.be.ref", kindName(sym), errSym);
2806 }
2807 }
2809 /**
2810 * InvalidSymbolError error class indicating that a pair of symbols
2811 * (either methods, constructors or operands) are ambiguous
2812 * given an actual arguments/type argument list.
2813 */
2814 class AmbiguityError extends InvalidSymbolError {
2816 /** The other maximally specific symbol */
2817 Symbol sym2;
2819 AmbiguityError(Symbol sym1, Symbol sym2) {
2820 super(AMBIGUOUS, sym1, "ambiguity error");
2821 this.sym2 = sym2;
2822 }
2824 @Override
2825 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2826 DiagnosticPosition pos,
2827 Symbol location,
2828 Type site,
2829 Name name,
2830 List<Type> argtypes,
2831 List<Type> typeargtypes) {
2832 AmbiguityError pair = this;
2833 while (true) {
2834 if (pair.sym.kind == AMBIGUOUS)
2835 pair = (AmbiguityError)pair.sym;
2836 else if (pair.sym2.kind == AMBIGUOUS)
2837 pair = (AmbiguityError)pair.sym2;
2838 else break;
2839 }
2840 Name sname = pair.sym.name;
2841 if (sname == names.init) sname = pair.sym.owner.name;
2842 return diags.create(dkind, log.currentSource(),
2843 pos, "ref.ambiguous", sname,
2844 kindName(pair.sym),
2845 pair.sym,
2846 pair.sym.location(site, types),
2847 kindName(pair.sym2),
2848 pair.sym2,
2849 pair.sym2.location(site, types));
2850 }
2851 }
2853 enum MethodResolutionPhase {
2854 BASIC(false, false),
2855 BOX(true, false),
2856 VARARITY(true, true);
2858 boolean isBoxingRequired;
2859 boolean isVarargsRequired;
2861 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
2862 this.isBoxingRequired = isBoxingRequired;
2863 this.isVarargsRequired = isVarargsRequired;
2864 }
2866 public boolean isBoxingRequired() {
2867 return isBoxingRequired;
2868 }
2870 public boolean isVarargsRequired() {
2871 return isVarargsRequired;
2872 }
2874 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
2875 return (varargsEnabled || !isVarargsRequired) &&
2876 (boxingEnabled || !isBoxingRequired);
2877 }
2878 }
2880 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
2882 /**
2883 * A resolution context is used to keep track of intermediate results of
2884 * overload resolution, such as list of method that are not applicable
2885 * (used to generate more precise diagnostics) and so on. Resolution contexts
2886 * can be nested - this means that when each overload resolution routine should
2887 * work within the resolution context it created.
2888 */
2889 class MethodResolutionContext {
2891 private List<Candidate> candidates = List.nil();
2893 private Map<MethodResolutionPhase, Symbol> resolutionCache =
2894 new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
2896 MethodResolutionPhase step = null;
2898 private boolean internalResolution = false;
2899 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
2901 private MethodResolutionPhase firstErroneousResolutionPhase() {
2902 MethodResolutionPhase bestSoFar = BASIC;
2903 Symbol sym = methodNotFound;
2904 List<MethodResolutionPhase> steps = methodResolutionSteps;
2905 while (steps.nonEmpty() &&
2906 steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
2907 sym.kind >= WRONG_MTHS) {
2908 sym = resolutionCache.get(steps.head);
2909 bestSoFar = steps.head;
2910 steps = steps.tail;
2911 }
2912 return bestSoFar;
2913 }
2915 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
2916 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
2917 if (!candidates.contains(c))
2918 candidates = candidates.append(c);
2919 }
2921 void addApplicableCandidate(Symbol sym, Type mtype) {
2922 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
2923 candidates = candidates.append(c);
2924 }
2926 /**
2927 * This class represents an overload resolution candidate. There are two
2928 * kinds of candidates: applicable methods and inapplicable methods;
2929 * applicable methods have a pointer to the instantiated method type,
2930 * while inapplicable candidates contain further details about the
2931 * reason why the method has been considered inapplicable.
2932 */
2933 class Candidate {
2935 final MethodResolutionPhase step;
2936 final Symbol sym;
2937 final JCDiagnostic details;
2938 final Type mtype;
2940 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
2941 this.step = step;
2942 this.sym = sym;
2943 this.details = details;
2944 this.mtype = mtype;
2945 }
2947 @Override
2948 public boolean equals(Object o) {
2949 if (o instanceof Candidate) {
2950 Symbol s1 = this.sym;
2951 Symbol s2 = ((Candidate)o).sym;
2952 if ((s1 != s2 &&
2953 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
2954 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
2955 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
2956 return true;
2957 }
2958 return false;
2959 }
2961 boolean isApplicable() {
2962 return mtype != null;
2963 }
2964 }
2966 DeferredAttr.AttrMode attrMode() {
2967 return attrMode;
2968 }
2970 boolean internal() {
2971 return internalResolution;
2972 }
2973 }
2975 MethodResolutionContext currentResolutionContext = null;
2976 }