Tue, 08 Jan 2013 10:16:26 +0100
8005179: Cleanup Resolve.AmbiguityError
Summary: Linearize nested ambiguity errors
Reviewed-by: jjg
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.tree.JCTree.JCMemberReference.ReferenceKind;
44 import com.sun.tools.javac.util.*;
45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
49 import java.util.Arrays;
50 import java.util.Collection;
51 import java.util.EnumMap;
52 import java.util.EnumSet;
53 import java.util.Iterator;
54 import java.util.LinkedHashMap;
55 import java.util.LinkedHashSet;
56 import java.util.Map;
57 import java.util.Set;
59 import javax.lang.model.element.ElementVisitor;
61 import static com.sun.tools.javac.code.Flags.*;
62 import static com.sun.tools.javac.code.Flags.BLOCK;
63 import static com.sun.tools.javac.code.Kinds.*;
64 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
65 import static com.sun.tools.javac.code.TypeTag.*;
66 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
67 import static com.sun.tools.javac.tree.JCTree.Tag.*;
69 /** Helper class for name resolution, used mostly by the attribution phase.
70 *
71 * <p><b>This is NOT part of any supported API.
72 * If you write code that depends on this, you do so at your own risk.
73 * This code and its internal interfaces are subject to change or
74 * deletion without notice.</b>
75 */
76 public class Resolve {
77 protected static final Context.Key<Resolve> resolveKey =
78 new Context.Key<Resolve>();
80 Names names;
81 Log log;
82 Symtab syms;
83 Attr attr;
84 DeferredAttr deferredAttr;
85 Check chk;
86 Infer infer;
87 ClassReader reader;
88 TreeInfo treeinfo;
89 Types types;
90 JCDiagnostic.Factory diags;
91 public final boolean boxingEnabled; // = source.allowBoxing();
92 public final boolean varargsEnabled; // = source.allowVarargs();
93 public final boolean allowMethodHandles;
94 public final boolean allowDefaultMethods;
95 private final boolean debugResolve;
96 final EnumSet<VerboseResolutionMode> verboseResolutionMode;
98 Scope polymorphicSignatureScope;
100 protected Resolve(Context context) {
101 context.put(resolveKey, this);
102 syms = Symtab.instance(context);
104 varNotFound = new
105 SymbolNotFoundError(ABSENT_VAR);
106 methodNotFound = new
107 SymbolNotFoundError(ABSENT_MTH);
108 typeNotFound = new
109 SymbolNotFoundError(ABSENT_TYP);
111 names = Names.instance(context);
112 log = Log.instance(context);
113 attr = Attr.instance(context);
114 deferredAttr = DeferredAttr.instance(context);
115 chk = Check.instance(context);
116 infer = Infer.instance(context);
117 reader = ClassReader.instance(context);
118 treeinfo = TreeInfo.instance(context);
119 types = Types.instance(context);
120 diags = JCDiagnostic.Factory.instance(context);
121 Source source = Source.instance(context);
122 boxingEnabled = source.allowBoxing();
123 varargsEnabled = source.allowVarargs();
124 Options options = Options.instance(context);
125 debugResolve = options.isSet("debugresolve");
126 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
127 Target target = Target.instance(context);
128 allowMethodHandles = target.hasMethodHandles();
129 allowDefaultMethods = source.allowDefaultMethods();
130 polymorphicSignatureScope = new Scope(syms.noSymbol);
132 inapplicableMethodException = new InapplicableMethodException(diags);
133 }
135 /** error symbols, which are returned when resolution fails
136 */
137 private final SymbolNotFoundError varNotFound;
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 final 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.hasTag(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.hasTag(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 /**
431 * Performs a recursive scan of a type looking for accessibility problems
432 * from current attribution environment
433 */
434 void checkAccessibleType(Env<AttrContext> env, Type t) {
435 accessibilityChecker.visit(t, env);
436 }
438 /**
439 * Accessibility type-visitor
440 */
441 Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
442 new Types.SimpleVisitor<Void, Env<AttrContext>>() {
444 void visit(List<Type> ts, Env<AttrContext> env) {
445 for (Type t : ts) {
446 visit(t, env);
447 }
448 }
450 public Void visitType(Type t, Env<AttrContext> env) {
451 return null;
452 }
454 @Override
455 public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
456 visit(t.elemtype, env);
457 return null;
458 }
460 @Override
461 public Void visitClassType(ClassType t, Env<AttrContext> env) {
462 visit(t.getTypeArguments(), env);
463 if (!isAccessible(env, t, true)) {
464 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
465 }
466 return null;
467 }
469 @Override
470 public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
471 visit(t.type, env);
472 return null;
473 }
475 @Override
476 public Void visitMethodType(MethodType t, Env<AttrContext> env) {
477 visit(t.getParameterTypes(), env);
478 visit(t.getReturnType(), env);
479 visit(t.getThrownTypes(), env);
480 return null;
481 }
482 };
484 /** Try to instantiate the type of a method so that it fits
485 * given type arguments and argument types. If succesful, return
486 * the method's instantiated type, else return null.
487 * The instantiation will take into account an additional leading
488 * formal parameter if the method is an instance method seen as a member
489 * of un underdetermined site In this case, we treat site as an additional
490 * parameter and the parameters of the class containing the method as
491 * additional type variables that get instantiated.
492 *
493 * @param env The current environment
494 * @param site The type of which the method is a member.
495 * @param m The method symbol.
496 * @param argtypes The invocation's given value arguments.
497 * @param typeargtypes The invocation's given type arguments.
498 * @param allowBoxing Allow boxing conversions of arguments.
499 * @param useVarargs Box trailing arguments into an array for varargs.
500 */
501 Type rawInstantiate(Env<AttrContext> env,
502 Type site,
503 Symbol m,
504 ResultInfo resultInfo,
505 List<Type> argtypes,
506 List<Type> typeargtypes,
507 boolean allowBoxing,
508 boolean useVarargs,
509 MethodCheck methodCheck,
510 Warner warn) throws Infer.InferenceException {
512 Type mt = types.memberType(site, m);
513 // tvars is the list of formal type variables for which type arguments
514 // need to inferred.
515 List<Type> tvars = List.nil();
516 if (typeargtypes == null) typeargtypes = List.nil();
517 if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
518 // This is not a polymorphic method, but typeargs are supplied
519 // which is fine, see JLS 15.12.2.1
520 } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
521 ForAll pmt = (ForAll) mt;
522 if (typeargtypes.length() != pmt.tvars.length())
523 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
524 // Check type arguments are within bounds
525 List<Type> formals = pmt.tvars;
526 List<Type> actuals = typeargtypes;
527 while (formals.nonEmpty() && actuals.nonEmpty()) {
528 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
529 pmt.tvars, typeargtypes);
530 for (; bounds.nonEmpty(); bounds = bounds.tail)
531 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
532 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
533 formals = formals.tail;
534 actuals = actuals.tail;
535 }
536 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
537 } else if (mt.hasTag(FORALL)) {
538 ForAll pmt = (ForAll) mt;
539 List<Type> tvars1 = types.newInstances(pmt.tvars);
540 tvars = tvars.appendList(tvars1);
541 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
542 }
544 // find out whether we need to go the slow route via infer
545 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
546 for (List<Type> l = argtypes;
547 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
548 l = l.tail) {
549 if (l.head.hasTag(FORALL)) instNeeded = true;
550 }
552 if (instNeeded)
553 return infer.instantiateMethod(env,
554 tvars,
555 (MethodType)mt,
556 resultInfo,
557 m,
558 argtypes,
559 allowBoxing,
560 useVarargs,
561 currentResolutionContext,
562 methodCheck,
563 warn);
565 methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext),
566 argtypes, mt.getParameterTypes(), warn);
567 return mt;
568 }
570 Type checkMethod(Env<AttrContext> env,
571 Type site,
572 Symbol m,
573 ResultInfo resultInfo,
574 List<Type> argtypes,
575 List<Type> typeargtypes,
576 Warner warn) {
577 MethodResolutionContext prevContext = currentResolutionContext;
578 try {
579 currentResolutionContext = new MethodResolutionContext();
580 currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
581 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
582 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
583 step.isBoxingRequired(), step.isVarargsRequired(), resolveMethodCheck, warn);
584 }
585 finally {
586 currentResolutionContext = prevContext;
587 }
588 }
590 /** Same but returns null instead throwing a NoInstanceException
591 */
592 Type instantiate(Env<AttrContext> env,
593 Type site,
594 Symbol m,
595 ResultInfo resultInfo,
596 List<Type> argtypes,
597 List<Type> typeargtypes,
598 boolean allowBoxing,
599 boolean useVarargs,
600 MethodCheck methodCheck,
601 Warner warn) {
602 try {
603 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
604 allowBoxing, useVarargs, methodCheck, warn);
605 } catch (InapplicableMethodException ex) {
606 return null;
607 }
608 }
610 /**
611 * This interface defines an entry point that should be used to perform a
612 * method check. A method check usually consist in determining as to whether
613 * a set of types (actuals) is compatible with another set of types (formals).
614 * Since the notion of compatibility can vary depending on the circumstances,
615 * this interfaces allows to easily add new pluggable method check routines.
616 */
617 interface MethodCheck {
618 /**
619 * Main method check routine. A method check usually consist in determining
620 * as to whether a set of types (actuals) is compatible with another set of
621 * types (formals). If an incompatibility is found, an unchecked exception
622 * is assumed to be thrown.
623 */
624 void argumentsAcceptable(Env<AttrContext> env,
625 DeferredAttrContext deferredAttrContext,
626 List<Type> argtypes,
627 List<Type> formals,
628 Warner warn);
629 }
631 /**
632 * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
633 */
634 enum MethodCheckDiag {
635 /**
636 * Actuals and formals differs in length.
637 */
638 ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
639 /**
640 * An actual is incompatible with a formal.
641 */
642 ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
643 /**
644 * An actual is incompatible with the varargs element type.
645 */
646 VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
647 /**
648 * The varargs element type is inaccessible.
649 */
650 INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
652 final String basicKey;
653 final String inferKey;
655 MethodCheckDiag(String basicKey, String inferKey) {
656 this.basicKey = basicKey;
657 this.inferKey = inferKey;
658 }
659 }
661 /**
662 * Main method applicability routine. Given a list of actual types A,
663 * a list of formal types F, determines whether the types in A are
664 * compatible (by method invocation conversion) with the types in F.
665 *
666 * Since this routine is shared between overload resolution and method
667 * type-inference, a (possibly empty) inference context is used to convert
668 * formal types to the corresponding 'undet' form ahead of a compatibility
669 * check so that constraints can be propagated and collected.
670 *
671 * Moreover, if one or more types in A is a deferred type, this routine uses
672 * DeferredAttr in order to perform deferred attribution. If one or more actual
673 * deferred types are stuck, they are placed in a queue and revisited later
674 * after the remainder of the arguments have been seen. If this is not sufficient
675 * to 'unstuck' the argument, a cyclic inference error is called out.
676 *
677 * A method check handler (see above) is used in order to report errors.
678 */
679 MethodCheck resolveMethodCheck = new MethodCheck() {
680 @Override
681 public void argumentsAcceptable(final Env<AttrContext> env,
682 DeferredAttrContext deferredAttrContext,
683 List<Type> argtypes,
684 List<Type> formals,
685 Warner warn) {
686 //should we expand formals?
687 boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
689 //inference context used during this method check
690 InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
692 Type varargsFormal = useVarargs ? formals.last() : null;
694 if (varargsFormal == null &&
695 argtypes.size() != formals.size()) {
696 report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
697 }
699 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
700 ResultInfo mresult = methodCheckResult(false, formals.head, deferredAttrContext, warn);
701 mresult.check(null, argtypes.head);
702 argtypes = argtypes.tail;
703 formals = formals.tail;
704 }
706 if (formals.head != varargsFormal) {
707 report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
708 }
710 if (useVarargs) {
711 //note: if applicability check is triggered by most specific test,
712 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
713 final Type elt = types.elemtype(varargsFormal);
714 ResultInfo mresult = methodCheckResult(true, elt, deferredAttrContext, warn);
715 while (argtypes.nonEmpty()) {
716 mresult.check(null, argtypes.head);
717 argtypes = argtypes.tail;
718 }
719 //check varargs element type accessibility
720 varargsAccessible(env, elt, inferenceContext);
721 }
722 }
724 private void report(MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
725 boolean inferDiag = inferenceContext != infer.emptyContext;
726 InapplicableMethodException ex = inferDiag ?
727 infer.inferenceException : inapplicableMethodException;
728 if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
729 Object[] args2 = new Object[args.length + 1];
730 System.arraycopy(args, 0, args2, 1, args.length);
731 args2[0] = inferenceContext.inferenceVars();
732 args = args2;
733 }
734 throw ex.setMessage(inferDiag ? diag.inferKey : diag.basicKey, args);
735 }
737 private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
738 if (inferenceContext.free(t)) {
739 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
740 @Override
741 public void typesInferred(InferenceContext inferenceContext) {
742 varargsAccessible(env, inferenceContext.asInstType(t, types), inferenceContext);
743 }
744 });
745 } else {
746 if (!isAccessible(env, t)) {
747 Symbol location = env.enclClass.sym;
748 report(MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
749 }
750 }
751 }
753 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
754 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
755 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
756 MethodCheckDiag methodDiag = varargsCheck ?
757 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
759 @Override
760 public void report(DiagnosticPosition pos, JCDiagnostic details) {
761 report(methodDiag, deferredAttrContext.inferenceContext, details);
762 }
763 };
764 return new MethodResultInfo(to, checkContext);
765 }
766 };
768 /**
769 * Check context to be used during method applicability checks. A method check
770 * context might contain inference variables.
771 */
772 abstract class MethodCheckContext implements CheckContext {
774 boolean strict;
775 DeferredAttrContext deferredAttrContext;
776 Warner rsWarner;
778 public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
779 this.strict = strict;
780 this.deferredAttrContext = deferredAttrContext;
781 this.rsWarner = rsWarner;
782 }
784 public boolean compatible(Type found, Type req, Warner warn) {
785 return strict ?
786 types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req, types), warn) :
787 types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req, types), warn);
788 }
790 public void report(DiagnosticPosition pos, JCDiagnostic details) {
791 throw inapplicableMethodException.setMessage(details);
792 }
794 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
795 return rsWarner;
796 }
798 public InferenceContext inferenceContext() {
799 return deferredAttrContext.inferenceContext;
800 }
802 public DeferredAttrContext deferredAttrContext() {
803 return deferredAttrContext;
804 }
805 }
807 /**
808 * ResultInfo class to be used during method applicability checks. Check
809 * for deferred types goes through special path.
810 */
811 class MethodResultInfo extends ResultInfo {
813 public MethodResultInfo(Type pt, CheckContext checkContext) {
814 attr.super(VAL, pt, checkContext);
815 }
817 @Override
818 protected Type check(DiagnosticPosition pos, Type found) {
819 if (found.hasTag(DEFERRED)) {
820 DeferredType dt = (DeferredType)found;
821 return dt.check(this);
822 } else {
823 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
824 }
825 }
827 @Override
828 protected MethodResultInfo dup(Type newPt) {
829 return new MethodResultInfo(newPt, checkContext);
830 }
832 @Override
833 protected ResultInfo dup(CheckContext newContext) {
834 return new MethodResultInfo(pt, newContext);
835 }
836 }
838 public static class InapplicableMethodException extends RuntimeException {
839 private static final long serialVersionUID = 0;
841 JCDiagnostic diagnostic;
842 JCDiagnostic.Factory diags;
844 InapplicableMethodException(JCDiagnostic.Factory diags) {
845 this.diagnostic = null;
846 this.diags = diags;
847 }
848 InapplicableMethodException setMessage() {
849 return setMessage((JCDiagnostic)null);
850 }
851 InapplicableMethodException setMessage(String key) {
852 return setMessage(key != null ? diags.fragment(key) : null);
853 }
854 InapplicableMethodException setMessage(String key, Object... args) {
855 return setMessage(key != null ? diags.fragment(key, args) : null);
856 }
857 InapplicableMethodException setMessage(JCDiagnostic diag) {
858 this.diagnostic = diag;
859 return this;
860 }
862 public JCDiagnostic getDiagnostic() {
863 return diagnostic;
864 }
865 }
866 private final InapplicableMethodException inapplicableMethodException;
868 /* ***************************************************************************
869 * Symbol lookup
870 * the following naming conventions for arguments are used
871 *
872 * env is the environment where the symbol was mentioned
873 * site is the type of which the symbol is a member
874 * name is the symbol's name
875 * if no arguments are given
876 * argtypes are the value arguments, if we search for a method
877 *
878 * If no symbol was found, a ResolveError detailing the problem is returned.
879 ****************************************************************************/
881 /** Find field. Synthetic fields are always skipped.
882 * @param env The current environment.
883 * @param site The original type from where the selection takes place.
884 * @param name The name of the field.
885 * @param c The class to search for the field. This is always
886 * a superclass or implemented interface of site's class.
887 */
888 Symbol findField(Env<AttrContext> env,
889 Type site,
890 Name name,
891 TypeSymbol c) {
892 while (c.type.hasTag(TYPEVAR))
893 c = c.type.getUpperBound().tsym;
894 Symbol bestSoFar = varNotFound;
895 Symbol sym;
896 Scope.Entry e = c.members().lookup(name);
897 while (e.scope != null) {
898 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
899 return isAccessible(env, site, e.sym)
900 ? e.sym : new AccessError(env, site, e.sym);
901 }
902 e = e.next();
903 }
904 Type st = types.supertype(c.type);
905 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
906 sym = findField(env, site, name, st.tsym);
907 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
908 }
909 for (List<Type> l = types.interfaces(c.type);
910 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
911 l = l.tail) {
912 sym = findField(env, site, name, l.head.tsym);
913 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
914 sym.owner != bestSoFar.owner)
915 bestSoFar = new AmbiguityError(bestSoFar, sym);
916 else if (sym.kind < bestSoFar.kind)
917 bestSoFar = sym;
918 }
919 return bestSoFar;
920 }
922 /** Resolve a field identifier, throw a fatal error if not found.
923 * @param pos The position to use for error reporting.
924 * @param env The environment current at the method invocation.
925 * @param site The type of the qualifying expression, in which
926 * identifier is searched.
927 * @param name The identifier's name.
928 */
929 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
930 Type site, Name name) {
931 Symbol sym = findField(env, site, name, site.tsym);
932 if (sym.kind == VAR) return (VarSymbol)sym;
933 else throw new FatalError(
934 diags.fragment("fatal.err.cant.locate.field",
935 name));
936 }
938 /** Find unqualified variable or field with given name.
939 * Synthetic fields always skipped.
940 * @param env The current environment.
941 * @param name The name of the variable or field.
942 */
943 Symbol findVar(Env<AttrContext> env, Name name) {
944 Symbol bestSoFar = varNotFound;
945 Symbol sym;
946 Env<AttrContext> env1 = env;
947 boolean staticOnly = false;
948 while (env1.outer != null) {
949 if (isStatic(env1)) staticOnly = true;
950 Scope.Entry e = env1.info.scope.lookup(name);
951 while (e.scope != null &&
952 (e.sym.kind != VAR ||
953 (e.sym.flags_field & SYNTHETIC) != 0))
954 e = e.next();
955 sym = (e.scope != null)
956 ? e.sym
957 : findField(
958 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
959 if (sym.exists()) {
960 if (staticOnly &&
961 sym.kind == VAR &&
962 sym.owner.kind == TYP &&
963 (sym.flags() & STATIC) == 0)
964 return new StaticError(sym);
965 else
966 return sym;
967 } else if (sym.kind < bestSoFar.kind) {
968 bestSoFar = sym;
969 }
971 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
972 env1 = env1.outer;
973 }
975 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
976 if (sym.exists())
977 return sym;
978 if (bestSoFar.exists())
979 return bestSoFar;
981 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
982 for (; e.scope != null; e = e.next()) {
983 sym = e.sym;
984 Type origin = e.getOrigin().owner.type;
985 if (sym.kind == VAR) {
986 if (e.sym.owner.type != origin)
987 sym = sym.clone(e.getOrigin().owner);
988 return isAccessible(env, origin, sym)
989 ? sym : new AccessError(env, origin, sym);
990 }
991 }
993 Symbol origin = null;
994 e = env.toplevel.starImportScope.lookup(name);
995 for (; e.scope != null; e = e.next()) {
996 sym = e.sym;
997 if (sym.kind != VAR)
998 continue;
999 // invariant: sym.kind == VAR
1000 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
1001 return new AmbiguityError(bestSoFar, sym);
1002 else if (bestSoFar.kind >= VAR) {
1003 origin = e.getOrigin().owner;
1004 bestSoFar = isAccessible(env, origin.type, sym)
1005 ? sym : new AccessError(env, origin.type, sym);
1006 }
1007 }
1008 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1009 return bestSoFar.clone(origin);
1010 else
1011 return bestSoFar;
1012 }
1014 Warner noteWarner = new Warner();
1016 /** Select the best method for a call site among two choices.
1017 * @param env The current environment.
1018 * @param site The original type from where the
1019 * selection takes place.
1020 * @param argtypes The invocation's value arguments,
1021 * @param typeargtypes The invocation's type arguments,
1022 * @param sym Proposed new best match.
1023 * @param bestSoFar Previously found best match.
1024 * @param allowBoxing Allow boxing conversions of arguments.
1025 * @param useVarargs Box trailing arguments into an array for varargs.
1026 */
1027 @SuppressWarnings("fallthrough")
1028 Symbol selectBest(Env<AttrContext> env,
1029 Type site,
1030 List<Type> argtypes,
1031 List<Type> typeargtypes,
1032 Symbol sym,
1033 Symbol bestSoFar,
1034 boolean allowBoxing,
1035 boolean useVarargs,
1036 boolean operator) {
1037 if (sym.kind == ERR ||
1038 !sym.isInheritedIn(site.tsym, types) ||
1039 (useVarargs && (sym.flags() & VARARGS) == 0)) {
1040 return bestSoFar;
1041 }
1042 Assert.check(sym.kind < AMBIGUOUS);
1043 try {
1044 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1045 allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
1046 if (!operator)
1047 currentResolutionContext.addApplicableCandidate(sym, mt);
1048 } catch (InapplicableMethodException ex) {
1049 if (!operator)
1050 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1051 switch (bestSoFar.kind) {
1052 case ABSENT_MTH:
1053 return new InapplicableSymbolError(currentResolutionContext);
1054 case WRONG_MTH:
1055 if (operator) return bestSoFar;
1056 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1057 default:
1058 return bestSoFar;
1059 }
1060 }
1061 if (!isAccessible(env, site, sym)) {
1062 return (bestSoFar.kind == ABSENT_MTH)
1063 ? new AccessError(env, site, sym)
1064 : bestSoFar;
1065 }
1066 return (bestSoFar.kind > AMBIGUOUS)
1067 ? sym
1068 : mostSpecific(argtypes, sym, bestSoFar, env, site,
1069 allowBoxing && operator, useVarargs);
1070 }
1072 /* Return the most specific of the two methods for a call,
1073 * given that both are accessible and applicable.
1074 * @param m1 A new candidate for most specific.
1075 * @param m2 The previous most specific candidate.
1076 * @param env The current environment.
1077 * @param site The original type from where the selection
1078 * takes place.
1079 * @param allowBoxing Allow boxing conversions of arguments.
1080 * @param useVarargs Box trailing arguments into an array for varargs.
1081 */
1082 Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1083 Symbol m2,
1084 Env<AttrContext> env,
1085 final Type site,
1086 boolean allowBoxing,
1087 boolean useVarargs) {
1088 switch (m2.kind) {
1089 case MTH:
1090 if (m1 == m2) return m1;
1091 boolean m1SignatureMoreSpecific =
1092 signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1093 boolean m2SignatureMoreSpecific =
1094 signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1095 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1096 Type mt1 = types.memberType(site, m1);
1097 Type mt2 = types.memberType(site, m2);
1098 if (!types.overrideEquivalent(mt1, mt2))
1099 return ambiguityError(m1, m2);
1101 // same signature; select (a) the non-bridge method, or
1102 // (b) the one that overrides the other, or (c) the concrete
1103 // one, or (d) merge both abstract signatures
1104 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1105 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1107 // if one overrides or hides the other, use it
1108 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1109 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1110 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1111 ((m1.owner.flags_field & INTERFACE) == 0 ||
1112 (m2.owner.flags_field & INTERFACE) != 0) &&
1113 m1.overrides(m2, m1Owner, types, false))
1114 return m1;
1115 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1116 ((m2.owner.flags_field & INTERFACE) == 0 ||
1117 (m1.owner.flags_field & INTERFACE) != 0) &&
1118 m2.overrides(m1, m2Owner, types, false))
1119 return m2;
1120 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1121 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1122 if (m1Abstract && !m2Abstract) return m2;
1123 if (m2Abstract && !m1Abstract) return m1;
1124 // both abstract or both concrete
1125 return ambiguityError(m1, m2);
1126 }
1127 if (m1SignatureMoreSpecific) return m1;
1128 if (m2SignatureMoreSpecific) return m2;
1129 return ambiguityError(m1, m2);
1130 case AMBIGUOUS:
1131 //check if m1 is more specific than all ambiguous methods in m2
1132 AmbiguityError e = (AmbiguityError)m2;
1133 for (Symbol s : e.ambiguousSyms) {
1134 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
1135 return e.addAmbiguousSymbol(m1);
1136 }
1137 }
1138 return m1;
1139 default:
1140 throw new AssertionError();
1141 }
1142 }
1143 //where
1144 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1145 Symbol m12 = adjustVarargs(m1, m2, useVarargs);
1146 Symbol m22 = adjustVarargs(m2, m1, useVarargs);
1147 Type mtype1 = types.memberType(site, m12);
1148 Type mtype2 = types.memberType(site, m22);
1150 //check if invocation is more specific
1151 if (invocationMoreSpecific(env, site, m22, mtype1.getParameterTypes(), allowBoxing, useVarargs)) {
1152 return true;
1153 }
1155 //perform structural check
1157 List<Type> formals1 = mtype1.getParameterTypes();
1158 Type lastFormal1 = formals1.last();
1159 List<Type> formals2 = mtype2.getParameterTypes();
1160 Type lastFormal2 = formals2.last();
1161 ListBuffer<Type> newFormals = ListBuffer.lb();
1163 boolean hasStructuralPoly = false;
1164 for (Type actual : actuals) {
1165 //perform formal argument adaptation in case actuals > formals (varargs)
1166 Type f1 = formals1.isEmpty() ?
1167 lastFormal1 : formals1.head;
1168 Type f2 = formals2.isEmpty() ?
1169 lastFormal2 : formals2.head;
1171 //is this a structural actual argument?
1172 boolean isStructuralPoly = actual.hasTag(DEFERRED) &&
1173 (((DeferredType)actual).tree.hasTag(LAMBDA) ||
1174 ((DeferredType)actual).tree.hasTag(REFERENCE));
1176 Type newFormal = f1;
1178 if (isStructuralPoly) {
1179 //for structural arguments only - check that corresponding formals
1180 //are related - if so replace formal with <null>
1181 hasStructuralPoly = true;
1182 DeferredType dt = (DeferredType)actual;
1183 Type t1 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m1, currentResolutionContext.step).apply(dt);
1184 Type t2 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m2, currentResolutionContext.step).apply(dt);
1185 if (t1.isErroneous() || t2.isErroneous() || !isStructuralSubtype(t1, t2)) {
1186 //not structural subtypes - simply fail
1187 return false;
1188 } else {
1189 newFormal = syms.botType;
1190 }
1191 }
1193 newFormals.append(newFormal);
1194 if (newFormals.length() > mtype2.getParameterTypes().length()) {
1195 //expand m2's type so as to fit the new formal arity (varargs)
1196 m22.type = types.createMethodTypeWithParameters(m22.type, m22.type.getParameterTypes().append(f2));
1197 }
1199 formals1 = formals1.isEmpty() ? formals1 : formals1.tail;
1200 formals2 = formals2.isEmpty() ? formals2 : formals2.tail;
1201 }
1203 if (!hasStructuralPoly) {
1204 //if no structural actual was found, we're done
1205 return false;
1206 }
1207 //perform additional adaptation if actuals < formals (varargs)
1208 for (Type t : formals1) {
1209 newFormals.append(t);
1210 }
1211 //check if invocation (with tweaked args) is more specific
1212 return invocationMoreSpecific(env, site, m22, newFormals.toList(), allowBoxing, useVarargs);
1213 }
1214 //where
1215 private boolean invocationMoreSpecific(Env<AttrContext> env, Type site, Symbol m2, List<Type> argtypes1, boolean allowBoxing, boolean useVarargs) {
1216 MethodResolutionContext prevContext = currentResolutionContext;
1217 try {
1218 currentResolutionContext = new MethodResolutionContext();
1219 currentResolutionContext.step = allowBoxing ? BOX : BASIC;
1220 noteWarner.clear();
1221 Type mst = instantiate(env, site, m2, null,
1222 types.lowerBounds(argtypes1), null,
1223 allowBoxing, false, resolveMethodCheck, noteWarner);
1224 return mst != null &&
1225 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1226 } finally {
1227 currentResolutionContext = prevContext;
1228 }
1229 }
1230 //where
1231 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
1232 List<Type> fromArgs = from.type.getParameterTypes();
1233 List<Type> toArgs = to.type.getParameterTypes();
1234 if (useVarargs &&
1235 (from.flags() & VARARGS) != 0 &&
1236 (to.flags() & VARARGS) != 0) {
1237 Type varargsTypeFrom = fromArgs.last();
1238 Type varargsTypeTo = toArgs.last();
1239 ListBuffer<Type> args = ListBuffer.lb();
1240 if (toArgs.length() < fromArgs.length()) {
1241 //if we are checking a varargs method 'from' against another varargs
1242 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
1243 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
1244 //until 'to' signature has the same arity as 'from')
1245 while (fromArgs.head != varargsTypeFrom) {
1246 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
1247 fromArgs = fromArgs.tail;
1248 toArgs = toArgs.head == varargsTypeTo ?
1249 toArgs :
1250 toArgs.tail;
1251 }
1252 } else {
1253 //formal argument list is same as original list where last
1254 //argument (array type) is removed
1255 args.appendList(toArgs.reverse().tail.reverse());
1256 }
1257 //append varargs element type as last synthetic formal
1258 args.append(types.elemtype(varargsTypeTo));
1259 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
1260 return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
1261 } else {
1262 return to;
1263 }
1264 }
1265 //where
1266 boolean isStructuralSubtype(Type s, Type t) {
1268 Type ret_s = types.findDescriptorType(s).getReturnType();
1269 Type ret_t = types.findDescriptorType(t).getReturnType();
1271 //covariant most specific check for function descriptor return type
1272 if (!types.isSubtype(ret_s, ret_t)) {
1273 return false;
1274 }
1276 List<Type> args_s = types.findDescriptorType(s).getParameterTypes();
1277 List<Type> args_t = types.findDescriptorType(t).getParameterTypes();
1279 //arity must be identical
1280 if (args_s.length() != args_t.length()) {
1281 return false;
1282 }
1284 //invariant most specific check for function descriptor parameter types
1285 if (!types.isSameTypes(args_t, args_s)) {
1286 return false;
1287 }
1289 return true;
1290 }
1291 //where
1292 Type mostSpecificReturnType(Type mt1, Type mt2) {
1293 Type rt1 = mt1.getReturnType();
1294 Type rt2 = mt2.getReturnType();
1296 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1297 //if both are generic methods, adjust return type ahead of subtyping check
1298 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1299 }
1300 //first use subtyping, then return type substitutability
1301 if (types.isSubtype(rt1, rt2)) {
1302 return mt1;
1303 } else if (types.isSubtype(rt2, rt1)) {
1304 return mt2;
1305 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1306 return mt1;
1307 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1308 return mt2;
1309 } else {
1310 return null;
1311 }
1312 }
1313 //where
1314 Symbol ambiguityError(Symbol m1, Symbol m2) {
1315 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1316 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1317 } else {
1318 return new AmbiguityError(m1, m2);
1319 }
1320 }
1322 Symbol findMethodInScope(Env<AttrContext> env,
1323 Type site,
1324 Name name,
1325 List<Type> argtypes,
1326 List<Type> typeargtypes,
1327 Scope sc,
1328 Symbol bestSoFar,
1329 boolean allowBoxing,
1330 boolean useVarargs,
1331 boolean operator,
1332 boolean abstractok) {
1333 for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
1334 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1335 bestSoFar, allowBoxing, useVarargs, operator);
1336 }
1337 return bestSoFar;
1338 }
1339 //where
1340 class LookupFilter implements Filter<Symbol> {
1342 boolean abstractOk;
1344 LookupFilter(boolean abstractOk) {
1345 this.abstractOk = abstractOk;
1346 }
1348 public boolean accepts(Symbol s) {
1349 long flags = s.flags();
1350 return s.kind == MTH &&
1351 (flags & SYNTHETIC) == 0 &&
1352 (abstractOk ||
1353 (flags & DEFAULT) != 0 ||
1354 (flags & ABSTRACT) == 0);
1355 }
1356 };
1358 /** Find best qualified method matching given name, type and value
1359 * arguments.
1360 * @param env The current environment.
1361 * @param site The original type from where the selection
1362 * takes place.
1363 * @param name The method's name.
1364 * @param argtypes The method's value arguments.
1365 * @param typeargtypes The method's type arguments
1366 * @param allowBoxing Allow boxing conversions of arguments.
1367 * @param useVarargs Box trailing arguments into an array for varargs.
1368 */
1369 Symbol findMethod(Env<AttrContext> env,
1370 Type site,
1371 Name name,
1372 List<Type> argtypes,
1373 List<Type> typeargtypes,
1374 boolean allowBoxing,
1375 boolean useVarargs,
1376 boolean operator) {
1377 Symbol bestSoFar = methodNotFound;
1378 bestSoFar = findMethod(env,
1379 site,
1380 name,
1381 argtypes,
1382 typeargtypes,
1383 site.tsym.type,
1384 bestSoFar,
1385 allowBoxing,
1386 useVarargs,
1387 operator);
1388 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1389 return bestSoFar;
1390 }
1391 // where
1392 private Symbol findMethod(Env<AttrContext> env,
1393 Type site,
1394 Name name,
1395 List<Type> argtypes,
1396 List<Type> typeargtypes,
1397 Type intype,
1398 Symbol bestSoFar,
1399 boolean allowBoxing,
1400 boolean useVarargs,
1401 boolean operator) {
1402 @SuppressWarnings({"unchecked","rawtypes"})
1403 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1404 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1405 for (TypeSymbol s : superclasses(intype)) {
1406 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1407 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1408 if (name == names.init) return bestSoFar;
1409 iphase = (iphase == null) ? null : iphase.update(s, this);
1410 if (iphase != null) {
1411 for (Type itype : types.interfaces(s.type)) {
1412 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1413 }
1414 }
1415 }
1417 Symbol concrete = bestSoFar.kind < ERR &&
1418 (bestSoFar.flags() & ABSTRACT) == 0 ?
1419 bestSoFar : methodNotFound;
1421 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1422 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
1423 //keep searching for abstract methods
1424 for (Type itype : itypes[iphase2.ordinal()]) {
1425 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1426 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1427 (itype.tsym.flags() & DEFAULT) == 0) continue;
1428 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1429 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1430 if (concrete != bestSoFar &&
1431 concrete.kind < ERR && bestSoFar.kind < ERR &&
1432 types.isSubSignature(concrete.type, bestSoFar.type)) {
1433 //this is an hack - as javac does not do full membership checks
1434 //most specific ends up comparing abstract methods that might have
1435 //been implemented by some concrete method in a subclass and,
1436 //because of raw override, it is possible for an abstract method
1437 //to be more specific than the concrete method - so we need
1438 //to explicitly call that out (see CR 6178365)
1439 bestSoFar = concrete;
1440 }
1441 }
1442 }
1443 return bestSoFar;
1444 }
1446 enum InterfaceLookupPhase {
1447 ABSTRACT_OK() {
1448 @Override
1449 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1450 //We should not look for abstract methods if receiver is a concrete class
1451 //(as concrete classes are expected to implement all abstracts coming
1452 //from superinterfaces)
1453 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1454 return this;
1455 } else if (rs.allowDefaultMethods) {
1456 return DEFAULT_OK;
1457 } else {
1458 return null;
1459 }
1460 }
1461 },
1462 DEFAULT_OK() {
1463 @Override
1464 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1465 return this;
1466 }
1467 };
1469 abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1470 }
1472 /**
1473 * Return an Iterable object to scan the superclasses of a given type.
1474 * It's crucial that the scan is done lazily, as we don't want to accidentally
1475 * access more supertypes than strictly needed (as this could trigger completion
1476 * errors if some of the not-needed supertypes are missing/ill-formed).
1477 */
1478 Iterable<TypeSymbol> superclasses(final Type intype) {
1479 return new Iterable<TypeSymbol>() {
1480 public Iterator<TypeSymbol> iterator() {
1481 return new Iterator<TypeSymbol>() {
1483 List<TypeSymbol> seen = List.nil();
1484 TypeSymbol currentSym = symbolFor(intype);
1485 TypeSymbol prevSym = null;
1487 public boolean hasNext() {
1488 if (currentSym == syms.noSymbol) {
1489 currentSym = symbolFor(types.supertype(prevSym.type));
1490 }
1491 return currentSym != null;
1492 }
1494 public TypeSymbol next() {
1495 prevSym = currentSym;
1496 currentSym = syms.noSymbol;
1497 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1498 return prevSym;
1499 }
1501 public void remove() {
1502 throw new UnsupportedOperationException();
1503 }
1505 TypeSymbol symbolFor(Type t) {
1506 if (!t.hasTag(CLASS) &&
1507 !t.hasTag(TYPEVAR)) {
1508 return null;
1509 }
1510 while (t.hasTag(TYPEVAR))
1511 t = t.getUpperBound();
1512 if (seen.contains(t.tsym)) {
1513 //degenerate case in which we have a circular
1514 //class hierarchy - because of ill-formed classfiles
1515 return null;
1516 }
1517 seen = seen.prepend(t.tsym);
1518 return t.tsym;
1519 }
1520 };
1521 }
1522 };
1523 }
1525 /** Find unqualified method matching given name, type and value arguments.
1526 * @param env The current environment.
1527 * @param name The method's name.
1528 * @param argtypes The method's value arguments.
1529 * @param typeargtypes The method's type arguments.
1530 * @param allowBoxing Allow boxing conversions of arguments.
1531 * @param useVarargs Box trailing arguments into an array for varargs.
1532 */
1533 Symbol findFun(Env<AttrContext> env, Name name,
1534 List<Type> argtypes, List<Type> typeargtypes,
1535 boolean allowBoxing, boolean useVarargs) {
1536 Symbol bestSoFar = methodNotFound;
1537 Symbol sym;
1538 Env<AttrContext> env1 = env;
1539 boolean staticOnly = false;
1540 while (env1.outer != null) {
1541 if (isStatic(env1)) staticOnly = true;
1542 sym = findMethod(
1543 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1544 allowBoxing, useVarargs, false);
1545 if (sym.exists()) {
1546 if (staticOnly &&
1547 sym.kind == MTH &&
1548 sym.owner.kind == TYP &&
1549 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1550 else return sym;
1551 } else if (sym.kind < bestSoFar.kind) {
1552 bestSoFar = sym;
1553 }
1554 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1555 env1 = env1.outer;
1556 }
1558 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1559 typeargtypes, allowBoxing, useVarargs, false);
1560 if (sym.exists())
1561 return sym;
1563 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1564 for (; e.scope != null; e = e.next()) {
1565 sym = e.sym;
1566 Type origin = e.getOrigin().owner.type;
1567 if (sym.kind == MTH) {
1568 if (e.sym.owner.type != origin)
1569 sym = sym.clone(e.getOrigin().owner);
1570 if (!isAccessible(env, origin, sym))
1571 sym = new AccessError(env, origin, sym);
1572 bestSoFar = selectBest(env, origin,
1573 argtypes, typeargtypes,
1574 sym, bestSoFar,
1575 allowBoxing, useVarargs, false);
1576 }
1577 }
1578 if (bestSoFar.exists())
1579 return bestSoFar;
1581 e = env.toplevel.starImportScope.lookup(name);
1582 for (; e.scope != null; e = e.next()) {
1583 sym = e.sym;
1584 Type origin = e.getOrigin().owner.type;
1585 if (sym.kind == MTH) {
1586 if (e.sym.owner.type != origin)
1587 sym = sym.clone(e.getOrigin().owner);
1588 if (!isAccessible(env, origin, sym))
1589 sym = new AccessError(env, origin, sym);
1590 bestSoFar = selectBest(env, origin,
1591 argtypes, typeargtypes,
1592 sym, bestSoFar,
1593 allowBoxing, useVarargs, false);
1594 }
1595 }
1596 return bestSoFar;
1597 }
1599 /** Load toplevel or member class with given fully qualified name and
1600 * verify that it is accessible.
1601 * @param env The current environment.
1602 * @param name The fully qualified name of the class to be loaded.
1603 */
1604 Symbol loadClass(Env<AttrContext> env, Name name) {
1605 try {
1606 ClassSymbol c = reader.loadClass(name);
1607 return isAccessible(env, c) ? c : new AccessError(c);
1608 } catch (ClassReader.BadClassFile err) {
1609 throw err;
1610 } catch (CompletionFailure ex) {
1611 return typeNotFound;
1612 }
1613 }
1615 /** Find qualified member type.
1616 * @param env The current environment.
1617 * @param site The original type from where the selection takes
1618 * place.
1619 * @param name The type's name.
1620 * @param c The class to search for the member type. This is
1621 * always a superclass or implemented interface of
1622 * site's class.
1623 */
1624 Symbol findMemberType(Env<AttrContext> env,
1625 Type site,
1626 Name name,
1627 TypeSymbol c) {
1628 Symbol bestSoFar = typeNotFound;
1629 Symbol sym;
1630 Scope.Entry e = c.members().lookup(name);
1631 while (e.scope != null) {
1632 if (e.sym.kind == TYP) {
1633 return isAccessible(env, site, e.sym)
1634 ? e.sym
1635 : new AccessError(env, site, e.sym);
1636 }
1637 e = e.next();
1638 }
1639 Type st = types.supertype(c.type);
1640 if (st != null && st.hasTag(CLASS)) {
1641 sym = findMemberType(env, site, name, st.tsym);
1642 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1643 }
1644 for (List<Type> l = types.interfaces(c.type);
1645 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1646 l = l.tail) {
1647 sym = findMemberType(env, site, name, l.head.tsym);
1648 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1649 sym.owner != bestSoFar.owner)
1650 bestSoFar = new AmbiguityError(bestSoFar, sym);
1651 else if (sym.kind < bestSoFar.kind)
1652 bestSoFar = sym;
1653 }
1654 return bestSoFar;
1655 }
1657 /** Find a global type in given scope and load corresponding class.
1658 * @param env The current environment.
1659 * @param scope The scope in which to look for the type.
1660 * @param name The type's name.
1661 */
1662 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1663 Symbol bestSoFar = typeNotFound;
1664 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1665 Symbol sym = loadClass(env, e.sym.flatName());
1666 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1667 bestSoFar != sym)
1668 return new AmbiguityError(bestSoFar, sym);
1669 else if (sym.kind < bestSoFar.kind)
1670 bestSoFar = sym;
1671 }
1672 return bestSoFar;
1673 }
1675 /** Find an unqualified type symbol.
1676 * @param env The current environment.
1677 * @param name The type's name.
1678 */
1679 Symbol findType(Env<AttrContext> env, Name name) {
1680 Symbol bestSoFar = typeNotFound;
1681 Symbol sym;
1682 boolean staticOnly = false;
1683 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1684 if (isStatic(env1)) staticOnly = true;
1685 for (Scope.Entry e = env1.info.scope.lookup(name);
1686 e.scope != null;
1687 e = e.next()) {
1688 if (e.sym.kind == TYP) {
1689 if (staticOnly &&
1690 e.sym.type.hasTag(TYPEVAR) &&
1691 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1692 return e.sym;
1693 }
1694 }
1696 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1697 env1.enclClass.sym);
1698 if (staticOnly && sym.kind == TYP &&
1699 sym.type.hasTag(CLASS) &&
1700 sym.type.getEnclosingType().hasTag(CLASS) &&
1701 env1.enclClass.sym.type.isParameterized() &&
1702 sym.type.getEnclosingType().isParameterized())
1703 return new StaticError(sym);
1704 else if (sym.exists()) return sym;
1705 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1707 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1708 if ((encl.sym.flags() & STATIC) != 0)
1709 staticOnly = true;
1710 }
1712 if (!env.tree.hasTag(IMPORT)) {
1713 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1714 if (sym.exists()) return sym;
1715 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1717 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1718 if (sym.exists()) return sym;
1719 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1721 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1722 if (sym.exists()) return sym;
1723 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1724 }
1726 return bestSoFar;
1727 }
1729 /** Find an unqualified identifier which matches a specified kind set.
1730 * @param env The current environment.
1731 * @param name The identifier's name.
1732 * @param kind Indicates the possible symbol kinds
1733 * (a subset of VAL, TYP, PCK).
1734 */
1735 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1736 Symbol bestSoFar = typeNotFound;
1737 Symbol sym;
1739 if ((kind & VAR) != 0) {
1740 sym = findVar(env, name);
1741 if (sym.exists()) return sym;
1742 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1743 }
1745 if ((kind & TYP) != 0) {
1746 sym = findType(env, name);
1747 if (sym.kind==TYP) {
1748 reportDependence(env.enclClass.sym, sym);
1749 }
1750 if (sym.exists()) return sym;
1751 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1752 }
1754 if ((kind & PCK) != 0) return reader.enterPackage(name);
1755 else return bestSoFar;
1756 }
1758 /** Report dependencies.
1759 * @param from The enclosing class sym
1760 * @param to The found identifier that the class depends on.
1761 */
1762 public void reportDependence(Symbol from, Symbol to) {
1763 // Override if you want to collect the reported dependencies.
1764 }
1766 /** Find an identifier in a package which matches a specified kind set.
1767 * @param env The current environment.
1768 * @param name The identifier's name.
1769 * @param kind Indicates the possible symbol kinds
1770 * (a nonempty subset of TYP, PCK).
1771 */
1772 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1773 Name name, int kind) {
1774 Name fullname = TypeSymbol.formFullName(name, pck);
1775 Symbol bestSoFar = typeNotFound;
1776 PackageSymbol pack = null;
1777 if ((kind & PCK) != 0) {
1778 pack = reader.enterPackage(fullname);
1779 if (pack.exists()) return pack;
1780 }
1781 if ((kind & TYP) != 0) {
1782 Symbol sym = loadClass(env, fullname);
1783 if (sym.exists()) {
1784 // don't allow programs to use flatnames
1785 if (name == sym.name) return sym;
1786 }
1787 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1788 }
1789 return (pack != null) ? pack : bestSoFar;
1790 }
1792 /** Find an identifier among the members of a given type `site'.
1793 * @param env The current environment.
1794 * @param site The type containing the symbol to be found.
1795 * @param name The identifier's name.
1796 * @param kind Indicates the possible symbol kinds
1797 * (a subset of VAL, TYP).
1798 */
1799 Symbol findIdentInType(Env<AttrContext> env, Type site,
1800 Name name, int kind) {
1801 Symbol bestSoFar = typeNotFound;
1802 Symbol sym;
1803 if ((kind & VAR) != 0) {
1804 sym = findField(env, site, name, site.tsym);
1805 if (sym.exists()) return sym;
1806 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1807 }
1809 if ((kind & TYP) != 0) {
1810 sym = findMemberType(env, site, name, site.tsym);
1811 if (sym.exists()) return sym;
1812 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1813 }
1814 return bestSoFar;
1815 }
1817 /* ***************************************************************************
1818 * Access checking
1819 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1820 * an error message in the process
1821 ****************************************************************************/
1823 /** If `sym' is a bad symbol: report error and return errSymbol
1824 * else pass through unchanged,
1825 * additional arguments duplicate what has been used in trying to find the
1826 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
1827 * expect misses to happen frequently.
1828 *
1829 * @param sym The symbol that was found, or a ResolveError.
1830 * @param pos The position to use for error reporting.
1831 * @param location The symbol the served as a context for this lookup
1832 * @param site The original type from where the selection took place.
1833 * @param name The symbol's name.
1834 * @param qualified Did we get here through a qualified expression resolution?
1835 * @param argtypes The invocation's value arguments,
1836 * if we looked for a method.
1837 * @param typeargtypes The invocation's type arguments,
1838 * if we looked for a method.
1839 * @param logResolveHelper helper class used to log resolve errors
1840 */
1841 Symbol accessInternal(Symbol sym,
1842 DiagnosticPosition pos,
1843 Symbol location,
1844 Type site,
1845 Name name,
1846 boolean qualified,
1847 List<Type> argtypes,
1848 List<Type> typeargtypes,
1849 LogResolveHelper logResolveHelper) {
1850 if (sym.kind >= AMBIGUOUS) {
1851 ResolveError errSym = (ResolveError)sym;
1852 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1853 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
1854 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
1855 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1856 }
1857 }
1858 return sym;
1859 }
1861 /**
1862 * Variant of the generalized access routine, to be used for generating method
1863 * resolution diagnostics
1864 */
1865 Symbol accessMethod(Symbol sym,
1866 DiagnosticPosition pos,
1867 Symbol location,
1868 Type site,
1869 Name name,
1870 boolean qualified,
1871 List<Type> argtypes,
1872 List<Type> typeargtypes) {
1873 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
1874 }
1876 /** Same as original accessMethod(), but without location.
1877 */
1878 Symbol accessMethod(Symbol sym,
1879 DiagnosticPosition pos,
1880 Type site,
1881 Name name,
1882 boolean qualified,
1883 List<Type> argtypes,
1884 List<Type> typeargtypes) {
1885 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1886 }
1888 /**
1889 * Variant of the generalized access routine, to be used for generating variable,
1890 * type resolution diagnostics
1891 */
1892 Symbol accessBase(Symbol sym,
1893 DiagnosticPosition pos,
1894 Symbol location,
1895 Type site,
1896 Name name,
1897 boolean qualified) {
1898 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
1899 }
1901 /** Same as original accessBase(), but without location.
1902 */
1903 Symbol accessBase(Symbol sym,
1904 DiagnosticPosition pos,
1905 Type site,
1906 Name name,
1907 boolean qualified) {
1908 return accessBase(sym, pos, site.tsym, site, name, qualified);
1909 }
1911 interface LogResolveHelper {
1912 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
1913 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
1914 }
1916 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
1917 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1918 return !site.isErroneous();
1919 }
1920 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1921 return argtypes;
1922 }
1923 };
1925 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
1926 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1927 return !site.isErroneous() &&
1928 !Type.isErroneous(argtypes) &&
1929 (typeargtypes == null || !Type.isErroneous(typeargtypes));
1930 }
1931 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1932 return (syms.operatorNames.contains(name)) ?
1933 argtypes :
1934 Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
1935 }
1937 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
1939 public ResolveDeferredRecoveryMap(Symbol msym) {
1940 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
1941 }
1943 @Override
1944 protected Type typeOf(DeferredType dt) {
1945 Type res = super.typeOf(dt);
1946 if (!res.isErroneous()) {
1947 switch (TreeInfo.skipParens(dt.tree).getTag()) {
1948 case LAMBDA:
1949 case REFERENCE:
1950 return dt;
1951 case CONDEXPR:
1952 return res == Type.recoveryType ?
1953 dt : res;
1954 }
1955 }
1956 return res;
1957 }
1958 }
1959 };
1961 /** Check that sym is not an abstract method.
1962 */
1963 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1964 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
1965 log.error(pos, "abstract.cant.be.accessed.directly",
1966 kindName(sym), sym, sym.location());
1967 }
1969 /* ***************************************************************************
1970 * Debugging
1971 ****************************************************************************/
1973 /** print all scopes starting with scope s and proceeding outwards.
1974 * used for debugging.
1975 */
1976 public void printscopes(Scope s) {
1977 while (s != null) {
1978 if (s.owner != null)
1979 System.err.print(s.owner + ": ");
1980 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1981 if ((e.sym.flags() & ABSTRACT) != 0)
1982 System.err.print("abstract ");
1983 System.err.print(e.sym + " ");
1984 }
1985 System.err.println();
1986 s = s.next;
1987 }
1988 }
1990 void printscopes(Env<AttrContext> env) {
1991 while (env.outer != null) {
1992 System.err.println("------------------------------");
1993 printscopes(env.info.scope);
1994 env = env.outer;
1995 }
1996 }
1998 public void printscopes(Type t) {
1999 while (t.hasTag(CLASS)) {
2000 printscopes(t.tsym.members());
2001 t = types.supertype(t);
2002 }
2003 }
2005 /* ***************************************************************************
2006 * Name resolution
2007 * Naming conventions are as for symbol lookup
2008 * Unlike the find... methods these methods will report access errors
2009 ****************************************************************************/
2011 /** Resolve an unqualified (non-method) identifier.
2012 * @param pos The position to use for error reporting.
2013 * @param env The environment current at the identifier use.
2014 * @param name The identifier's name.
2015 * @param kind The set of admissible symbol kinds for the identifier.
2016 */
2017 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2018 Name name, int kind) {
2019 return accessBase(
2020 findIdent(env, name, kind),
2021 pos, env.enclClass.sym.type, name, false);
2022 }
2024 /** Resolve an unqualified method identifier.
2025 * @param pos The position to use for error reporting.
2026 * @param env The environment current at the method invocation.
2027 * @param name The identifier's name.
2028 * @param argtypes The types of the invocation's value arguments.
2029 * @param typeargtypes The types of the invocation's type arguments.
2030 */
2031 Symbol resolveMethod(DiagnosticPosition pos,
2032 Env<AttrContext> env,
2033 Name name,
2034 List<Type> argtypes,
2035 List<Type> typeargtypes) {
2036 return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2037 @Override
2038 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2039 return findFun(env, name, argtypes, typeargtypes,
2040 phase.isBoxingRequired(),
2041 phase.isVarargsRequired());
2042 }
2043 });
2044 }
2046 /** Resolve a qualified method identifier
2047 * @param pos The position to use for error reporting.
2048 * @param env The environment current at the method invocation.
2049 * @param site The type of the qualifying expression, in which
2050 * identifier is searched.
2051 * @param name The identifier's name.
2052 * @param argtypes The types of the invocation's value arguments.
2053 * @param typeargtypes The types of the invocation's type arguments.
2054 */
2055 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2056 Type site, Name name, List<Type> argtypes,
2057 List<Type> typeargtypes) {
2058 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2059 }
2060 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2061 Symbol location, Type site, Name name, List<Type> argtypes,
2062 List<Type> typeargtypes) {
2063 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2064 }
2065 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2066 DiagnosticPosition pos, Env<AttrContext> env,
2067 Symbol location, Type site, Name name, List<Type> argtypes,
2068 List<Type> typeargtypes) {
2069 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2070 @Override
2071 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2072 return findMethod(env, site, name, argtypes, typeargtypes,
2073 phase.isBoxingRequired(),
2074 phase.isVarargsRequired(), false);
2075 }
2076 @Override
2077 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2078 if (sym.kind >= AMBIGUOUS) {
2079 sym = super.access(env, pos, location, sym);
2080 } else if (allowMethodHandles) {
2081 MethodSymbol msym = (MethodSymbol)sym;
2082 if (msym.isSignaturePolymorphic(types)) {
2083 return findPolymorphicSignatureInstance(env, sym, argtypes);
2084 }
2085 }
2086 return sym;
2087 }
2088 });
2089 }
2091 /** Find or create an implicit method of exactly the given type (after erasure).
2092 * Searches in a side table, not the main scope of the site.
2093 * This emulates the lookup process required by JSR 292 in JVM.
2094 * @param env Attribution environment
2095 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
2096 * @param argtypes The required argument types
2097 */
2098 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2099 final Symbol spMethod,
2100 List<Type> argtypes) {
2101 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2102 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2103 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
2104 if (types.isSameType(mtype, sym.type)) {
2105 return sym;
2106 }
2107 }
2109 // create the desired method
2110 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2111 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2112 @Override
2113 public Symbol baseSymbol() {
2114 return spMethod;
2115 }
2116 };
2117 polymorphicSignatureScope.enter(msym);
2118 return msym;
2119 }
2121 /** Resolve a qualified method identifier, throw a fatal error if not
2122 * found.
2123 * @param pos The position to use for error reporting.
2124 * @param env The environment current at the method invocation.
2125 * @param site The type of the qualifying expression, in which
2126 * identifier is searched.
2127 * @param name The identifier's name.
2128 * @param argtypes The types of the invocation's value arguments.
2129 * @param typeargtypes The types of the invocation's type arguments.
2130 */
2131 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2132 Type site, Name name,
2133 List<Type> argtypes,
2134 List<Type> typeargtypes) {
2135 MethodResolutionContext resolveContext = new MethodResolutionContext();
2136 resolveContext.internalResolution = true;
2137 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2138 site, name, argtypes, typeargtypes);
2139 if (sym.kind == MTH) return (MethodSymbol)sym;
2140 else throw new FatalError(
2141 diags.fragment("fatal.err.cant.locate.meth",
2142 name));
2143 }
2145 /** Resolve constructor.
2146 * @param pos The position to use for error reporting.
2147 * @param env The environment current at the constructor invocation.
2148 * @param site The type of class for which a constructor is searched.
2149 * @param argtypes The types of the constructor invocation's value
2150 * arguments.
2151 * @param typeargtypes The types of the constructor invocation's type
2152 * arguments.
2153 */
2154 Symbol resolveConstructor(DiagnosticPosition pos,
2155 Env<AttrContext> env,
2156 Type site,
2157 List<Type> argtypes,
2158 List<Type> typeargtypes) {
2159 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2160 }
2162 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2163 final DiagnosticPosition pos,
2164 Env<AttrContext> env,
2165 Type site,
2166 List<Type> argtypes,
2167 List<Type> typeargtypes) {
2168 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2169 @Override
2170 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2171 return findConstructor(pos, env, site, argtypes, typeargtypes,
2172 phase.isBoxingRequired(),
2173 phase.isVarargsRequired());
2174 }
2175 });
2176 }
2178 /** Resolve a constructor, throw a fatal error if not found.
2179 * @param pos The position to use for error reporting.
2180 * @param env The environment current at the method invocation.
2181 * @param site The type to be constructed.
2182 * @param argtypes The types of the invocation's value arguments.
2183 * @param typeargtypes The types of the invocation's type arguments.
2184 */
2185 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2186 Type site,
2187 List<Type> argtypes,
2188 List<Type> typeargtypes) {
2189 MethodResolutionContext resolveContext = new MethodResolutionContext();
2190 resolveContext.internalResolution = true;
2191 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2192 if (sym.kind == MTH) return (MethodSymbol)sym;
2193 else throw new FatalError(
2194 diags.fragment("fatal.err.cant.locate.ctor", site));
2195 }
2197 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2198 Type site, List<Type> argtypes,
2199 List<Type> typeargtypes,
2200 boolean allowBoxing,
2201 boolean useVarargs) {
2202 Symbol sym = findMethod(env, site,
2203 names.init, argtypes,
2204 typeargtypes, allowBoxing,
2205 useVarargs, false);
2206 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2207 return sym;
2208 }
2210 /** Resolve constructor using diamond inference.
2211 * @param pos The position to use for error reporting.
2212 * @param env The environment current at the constructor invocation.
2213 * @param site The type of class for which a constructor is searched.
2214 * The scope of this class has been touched in attribution.
2215 * @param argtypes The types of the constructor invocation's value
2216 * arguments.
2217 * @param typeargtypes The types of the constructor invocation's type
2218 * arguments.
2219 */
2220 Symbol resolveDiamond(DiagnosticPosition pos,
2221 Env<AttrContext> env,
2222 Type site,
2223 List<Type> argtypes,
2224 List<Type> typeargtypes) {
2225 return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2226 @Override
2227 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2228 return findDiamond(env, site, argtypes, typeargtypes,
2229 phase.isBoxingRequired(),
2230 phase.isVarargsRequired());
2231 }
2232 @Override
2233 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2234 if (sym.kind >= AMBIGUOUS) {
2235 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2236 ((InapplicableSymbolError)sym).errCandidate().details :
2237 null;
2238 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2239 @Override
2240 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2241 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2242 String key = details == null ?
2243 "cant.apply.diamond" :
2244 "cant.apply.diamond.1";
2245 return diags.create(dkind, log.currentSource(), pos, key,
2246 diags.fragment("diamond", site.tsym), details);
2247 }
2248 };
2249 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2250 env.info.pendingResolutionPhase = currentResolutionContext.step;
2251 }
2252 return sym;
2253 }
2254 });
2255 }
2257 /** This method scans all the constructor symbol in a given class scope -
2258 * assuming that the original scope contains a constructor of the kind:
2259 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2260 * a method check is executed against the modified constructor type:
2261 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2262 * inference. The inferred return type of the synthetic constructor IS
2263 * the inferred type for the diamond operator.
2264 */
2265 private Symbol findDiamond(Env<AttrContext> env,
2266 Type site,
2267 List<Type> argtypes,
2268 List<Type> typeargtypes,
2269 boolean allowBoxing,
2270 boolean useVarargs) {
2271 Symbol bestSoFar = methodNotFound;
2272 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2273 e.scope != null;
2274 e = e.next()) {
2275 final Symbol sym = e.sym;
2276 //- System.out.println(" e " + e.sym);
2277 if (sym.kind == MTH &&
2278 (sym.flags_field & SYNTHETIC) == 0) {
2279 List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
2280 ((ForAll)sym.type).tvars :
2281 List.<Type>nil();
2282 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2283 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2284 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2285 @Override
2286 public Symbol baseSymbol() {
2287 return sym;
2288 }
2289 };
2290 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2291 newConstr,
2292 bestSoFar,
2293 allowBoxing,
2294 useVarargs,
2295 false);
2296 }
2297 }
2298 return bestSoFar;
2299 }
2303 /** Resolve operator.
2304 * @param pos The position to use for error reporting.
2305 * @param optag The tag of the operation tree.
2306 * @param env The environment current at the operation.
2307 * @param argtypes The types of the operands.
2308 */
2309 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2310 Env<AttrContext> env, List<Type> argtypes) {
2311 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2312 try {
2313 currentResolutionContext = new MethodResolutionContext();
2314 Name name = treeinfo.operatorName(optag);
2315 env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
2316 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2317 null, false, false, true);
2318 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2319 env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
2320 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2321 null, true, false, true);
2322 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2323 false, argtypes, null);
2324 }
2325 finally {
2326 currentResolutionContext = prevResolutionContext;
2327 }
2328 }
2330 /** Resolve operator.
2331 * @param pos The position to use for error reporting.
2332 * @param optag The tag of the operation tree.
2333 * @param env The environment current at the operation.
2334 * @param arg The type of the operand.
2335 */
2336 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2337 return resolveOperator(pos, optag, env, List.of(arg));
2338 }
2340 /** Resolve binary operator.
2341 * @param pos The position to use for error reporting.
2342 * @param optag The tag of the operation tree.
2343 * @param env The environment current at the operation.
2344 * @param left The types of the left operand.
2345 * @param right The types of the right operand.
2346 */
2347 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2348 JCTree.Tag optag,
2349 Env<AttrContext> env,
2350 Type left,
2351 Type right) {
2352 return resolveOperator(pos, optag, env, List.of(left, right));
2353 }
2355 /**
2356 * Resolution of member references is typically done as a single
2357 * overload resolution step, where the argument types A are inferred from
2358 * the target functional descriptor.
2359 *
2360 * If the member reference is a method reference with a type qualifier,
2361 * a two-step lookup process is performed. The first step uses the
2362 * expected argument list A, while the second step discards the first
2363 * type from A (which is treated as a receiver type).
2364 *
2365 * There are two cases in which inference is performed: (i) if the member
2366 * reference is a constructor reference and the qualifier type is raw - in
2367 * which case diamond inference is used to infer a parameterization for the
2368 * type qualifier; (ii) if the member reference is an unbound reference
2369 * where the type qualifier is raw - in that case, during the unbound lookup
2370 * the receiver argument type is used to infer an instantiation for the raw
2371 * qualifier type.
2372 *
2373 * When a multi-step resolution process is exploited, it is an error
2374 * if two candidates are found (ambiguity).
2375 *
2376 * This routine returns a pair (T,S), where S is the member reference symbol,
2377 * and T is the type of the class in which S is defined. This is necessary as
2378 * the type T might be dynamically inferred (i.e. if constructor reference
2379 * has a raw qualifier).
2380 */
2381 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
2382 Env<AttrContext> env,
2383 JCMemberReference referenceTree,
2384 Type site,
2385 Name name, List<Type> argtypes,
2386 List<Type> typeargtypes,
2387 boolean boxingAllowed) {
2388 MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
2389 //step 1 - bound lookup
2390 ReferenceLookupHelper boundLookupHelper = name.equals(names.init) ?
2391 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase) :
2392 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2393 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2394 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
2396 //step 2 - unbound lookup
2397 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
2398 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2399 Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
2401 //merge results
2402 Pair<Symbol, ReferenceLookupHelper> res;
2403 if (unboundSym.kind != MTH) {
2404 res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
2405 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2406 } else if (boundSym.kind == MTH) {
2407 res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
2408 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2409 } else {
2410 res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
2411 env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
2412 }
2414 return res;
2415 }
2417 /**
2418 * Helper for defining custom method-like lookup logic; a lookup helper
2419 * provides hooks for (i) the actual lookup logic and (ii) accessing the
2420 * lookup result (this step might result in compiler diagnostics to be generated)
2421 */
2422 abstract class LookupHelper {
2424 /** name of the symbol to lookup */
2425 Name name;
2427 /** location in which the lookup takes place */
2428 Type site;
2430 /** actual types used during the lookup */
2431 List<Type> argtypes;
2433 /** type arguments used during the lookup */
2434 List<Type> typeargtypes;
2436 /** Max overload resolution phase handled by this helper */
2437 MethodResolutionPhase maxPhase;
2439 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2440 this.name = name;
2441 this.site = site;
2442 this.argtypes = argtypes;
2443 this.typeargtypes = typeargtypes;
2444 this.maxPhase = maxPhase;
2445 }
2447 /**
2448 * Should lookup stop at given phase with given result
2449 */
2450 protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2451 return phase.ordinal() > maxPhase.ordinal() ||
2452 sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
2453 }
2455 /**
2456 * Search for a symbol under a given overload resolution phase - this method
2457 * is usually called several times, once per each overload resolution phase
2458 */
2459 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
2461 /**
2462 * Validate the result of the lookup
2463 */
2464 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
2465 }
2467 abstract class BasicLookupHelper extends LookupHelper {
2469 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
2470 super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
2471 }
2473 @Override
2474 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2475 if (sym.kind == AMBIGUOUS) {
2476 AmbiguityError a_err = (AmbiguityError)sym;
2477 sym = a_err.mergeAbstracts(site);
2478 }
2479 if (sym.kind >= AMBIGUOUS) {
2480 //if nothing is found return the 'first' error
2481 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
2482 }
2483 return sym;
2484 }
2485 }
2487 /**
2488 * Helper class for member reference lookup. A reference lookup helper
2489 * defines the basic logic for member reference lookup; a method gives
2490 * access to an 'unbound' helper used to perform an unbound member
2491 * reference lookup.
2492 */
2493 abstract class ReferenceLookupHelper extends LookupHelper {
2495 /** The member reference tree */
2496 JCMemberReference referenceTree;
2498 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2499 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2500 super(name, site, argtypes, typeargtypes, maxPhase);
2501 this.referenceTree = referenceTree;
2503 }
2505 /**
2506 * Returns an unbound version of this lookup helper. By default, this
2507 * method returns an dummy lookup helper.
2508 */
2509 ReferenceLookupHelper unboundLookup() {
2510 //dummy loopkup helper that always return 'methodNotFound'
2511 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
2512 @Override
2513 ReferenceLookupHelper unboundLookup() {
2514 return this;
2515 }
2516 @Override
2517 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2518 return methodNotFound;
2519 }
2520 @Override
2521 ReferenceKind referenceKind(Symbol sym) {
2522 Assert.error();
2523 return null;
2524 }
2525 };
2526 }
2528 /**
2529 * Get the kind of the member reference
2530 */
2531 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
2533 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2534 if (sym.kind == AMBIGUOUS) {
2535 AmbiguityError a_err = (AmbiguityError)sym;
2536 sym = a_err.mergeAbstracts(site);
2537 }
2538 //skip error reporting
2539 return sym;
2540 }
2541 }
2543 /**
2544 * Helper class for method reference lookup. The lookup logic is based
2545 * upon Resolve.findMethod; in certain cases, this helper class has a
2546 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
2547 * In such cases, non-static lookup results are thrown away.
2548 */
2549 class MethodReferenceLookupHelper extends ReferenceLookupHelper {
2551 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2552 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2553 super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2554 }
2556 protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
2557 return findMethod(env, site, name, argtypes, typeargtypes,
2558 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2559 }
2561 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2562 return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
2563 sym.kind != MTH ||
2564 sym.isStatic() ? sym : new StaticError(sym);
2565 }
2567 @Override
2568 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2569 return adjustLookupResult(env, lookupReferenceInternal(env, phase));
2570 }
2572 @Override
2573 ReferenceLookupHelper unboundLookup() {
2574 if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
2575 argtypes.nonEmpty() &&
2576 types.isSubtypeUnchecked(argtypes.head, site)) {
2577 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
2578 site, argtypes, typeargtypes, maxPhase);
2579 } else {
2580 return super.unboundLookup();
2581 }
2582 }
2584 @Override
2585 ReferenceKind referenceKind(Symbol sym) {
2586 if (sym.isStatic()) {
2587 return ReferenceKind.STATIC;
2588 } else {
2589 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
2590 return selName != null && selName == names._super ?
2591 ReferenceKind.SUPER :
2592 ReferenceKind.BOUND;
2593 }
2594 }
2595 }
2597 /**
2598 * Helper class for unbound method reference lookup. Essentially the same
2599 * as the basic method reference lookup helper; main difference is that static
2600 * lookup results are thrown away. If qualifier type is raw, an attempt to
2601 * infer a parameterized type is made using the first actual argument (that
2602 * would otherwise be ignored during the lookup).
2603 */
2604 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
2606 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2607 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2608 super(referenceTree, name,
2609 site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
2610 argtypes.tail, typeargtypes, maxPhase);
2611 }
2613 @Override
2614 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2615 return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
2616 }
2618 @Override
2619 ReferenceLookupHelper unboundLookup() {
2620 return this;
2621 }
2623 @Override
2624 ReferenceKind referenceKind(Symbol sym) {
2625 return ReferenceKind.UNBOUND;
2626 }
2627 }
2629 /**
2630 * Helper class for constructor reference lookup. The lookup logic is based
2631 * upon either Resolve.findMethod or Resolve.findDiamond - depending on
2632 * whether the constructor reference needs diamond inference (this is the case
2633 * if the qualifier type is raw). A special erroneous symbol is returned
2634 * if the lookup returns the constructor of an inner class and there's no
2635 * enclosing instance in scope.
2636 */
2637 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2639 boolean needsInference;
2641 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2642 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2643 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2644 if (site.isRaw()) {
2645 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
2646 needsInference = true;
2647 }
2648 }
2650 @Override
2651 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2652 Symbol sym = needsInference ?
2653 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
2654 findMethod(env, site, name, argtypes, typeargtypes,
2655 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2656 return sym.kind != MTH ||
2657 site.getEnclosingType().hasTag(NONE) ||
2658 hasEnclosingInstance(env, site) ?
2659 sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
2660 @Override
2661 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2662 return diags.create(dkind, log.currentSource(), pos,
2663 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
2664 }
2665 };
2666 }
2668 @Override
2669 ReferenceKind referenceKind(Symbol sym) {
2670 return site.getEnclosingType().hasTag(NONE) ?
2671 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
2672 }
2673 }
2675 /**
2676 * Main overload resolution routine. On each overload resolution step, a
2677 * lookup helper class is used to perform the method/constructor lookup;
2678 * at the end of the lookup, the helper is used to validate the results
2679 * (this last step might trigger overload resolution diagnostics).
2680 */
2681 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
2682 return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
2683 }
2685 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
2686 MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
2687 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2688 try {
2689 Symbol bestSoFar = methodNotFound;
2690 currentResolutionContext = resolveContext;
2691 for (MethodResolutionPhase phase : methodResolutionSteps) {
2692 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
2693 lookupHelper.shouldStop(bestSoFar, phase)) break;
2694 MethodResolutionPhase prevPhase = currentResolutionContext.step;
2695 Symbol prevBest = bestSoFar;
2696 currentResolutionContext.step = phase;
2697 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
2698 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
2699 }
2700 return lookupHelper.access(env, pos, location, bestSoFar);
2701 } finally {
2702 currentResolutionContext = prevResolutionContext;
2703 }
2704 }
2706 /**
2707 * Resolve `c.name' where name == this or name == super.
2708 * @param pos The position to use for error reporting.
2709 * @param env The environment current at the expression.
2710 * @param c The qualifier.
2711 * @param name The identifier's name.
2712 */
2713 Symbol resolveSelf(DiagnosticPosition pos,
2714 Env<AttrContext> env,
2715 TypeSymbol c,
2716 Name name) {
2717 Env<AttrContext> env1 = env;
2718 boolean staticOnly = false;
2719 while (env1.outer != null) {
2720 if (isStatic(env1)) staticOnly = true;
2721 if (env1.enclClass.sym == c) {
2722 Symbol sym = env1.info.scope.lookup(name).sym;
2723 if (sym != null) {
2724 if (staticOnly) sym = new StaticError(sym);
2725 return accessBase(sym, pos, env.enclClass.sym.type,
2726 name, true);
2727 }
2728 }
2729 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2730 env1 = env1.outer;
2731 }
2732 if (allowDefaultMethods && c.isInterface() &&
2733 name == names._super && !isStatic(env) &&
2734 types.isDirectSuperInterface(c, env.enclClass.sym)) {
2735 //this might be a default super call if one of the superinterfaces is 'c'
2736 for (Type t : pruneInterfaces(env.enclClass.type)) {
2737 if (t.tsym == c) {
2738 env.info.defaultSuperCallSite = t;
2739 return new VarSymbol(0, names._super,
2740 types.asSuper(env.enclClass.type, c), env.enclClass.sym);
2741 }
2742 }
2743 //find a direct superinterface that is a subtype of 'c'
2744 for (Type i : types.interfaces(env.enclClass.type)) {
2745 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
2746 log.error(pos, "illegal.default.super.call", c,
2747 diags.fragment("redundant.supertype", c, i));
2748 return syms.errSymbol;
2749 }
2750 }
2751 Assert.error();
2752 }
2753 log.error(pos, "not.encl.class", c);
2754 return syms.errSymbol;
2755 }
2756 //where
2757 private List<Type> pruneInterfaces(Type t) {
2758 ListBuffer<Type> result = ListBuffer.lb();
2759 for (Type t1 : types.interfaces(t)) {
2760 boolean shouldAdd = true;
2761 for (Type t2 : types.interfaces(t)) {
2762 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
2763 shouldAdd = false;
2764 }
2765 }
2766 if (shouldAdd) {
2767 result.append(t1);
2768 }
2769 }
2770 return result.toList();
2771 }
2774 /**
2775 * Resolve `c.this' for an enclosing class c that contains the
2776 * named member.
2777 * @param pos The position to use for error reporting.
2778 * @param env The environment current at the expression.
2779 * @param member The member that must be contained in the result.
2780 */
2781 Symbol resolveSelfContaining(DiagnosticPosition pos,
2782 Env<AttrContext> env,
2783 Symbol member,
2784 boolean isSuperCall) {
2785 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
2786 if (sym == null) {
2787 log.error(pos, "encl.class.required", member);
2788 return syms.errSymbol;
2789 } else {
2790 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
2791 }
2792 }
2794 boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
2795 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
2796 return encl != null && encl.kind < ERRONEOUS;
2797 }
2799 private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
2800 Symbol member,
2801 boolean isSuperCall) {
2802 Name name = names._this;
2803 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2804 boolean staticOnly = false;
2805 if (env1 != null) {
2806 while (env1 != null && env1.outer != null) {
2807 if (isStatic(env1)) staticOnly = true;
2808 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2809 Symbol sym = env1.info.scope.lookup(name).sym;
2810 if (sym != null) {
2811 if (staticOnly) sym = new StaticError(sym);
2812 return sym;
2813 }
2814 }
2815 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2816 staticOnly = true;
2817 env1 = env1.outer;
2818 }
2819 }
2820 return null;
2821 }
2823 /**
2824 * Resolve an appropriate implicit this instance for t's container.
2825 * JLS 8.8.5.1 and 15.9.2
2826 */
2827 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2828 return resolveImplicitThis(pos, env, t, false);
2829 }
2831 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2832 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2833 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2834 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2835 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2836 log.error(pos, "cant.ref.before.ctor.called", "this");
2837 return thisType;
2838 }
2840 /* ***************************************************************************
2841 * ResolveError classes, indicating error situations when accessing symbols
2842 ****************************************************************************/
2844 //used by TransTypes when checking target type of synthetic cast
2845 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2846 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2847 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2848 }
2849 //where
2850 private void logResolveError(ResolveError error,
2851 DiagnosticPosition pos,
2852 Symbol location,
2853 Type site,
2854 Name name,
2855 List<Type> argtypes,
2856 List<Type> typeargtypes) {
2857 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2858 pos, location, site, name, argtypes, typeargtypes);
2859 if (d != null) {
2860 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2861 log.report(d);
2862 }
2863 }
2865 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2867 public Object methodArguments(List<Type> argtypes) {
2868 if (argtypes == null || argtypes.isEmpty()) {
2869 return noArgs;
2870 } else {
2871 ListBuffer<Object> diagArgs = ListBuffer.lb();
2872 for (Type t : argtypes) {
2873 if (t.hasTag(DEFERRED)) {
2874 diagArgs.append(((DeferredAttr.DeferredType)t).tree);
2875 } else {
2876 diagArgs.append(t);
2877 }
2878 }
2879 return diagArgs;
2880 }
2881 }
2883 /**
2884 * Root class for resolution errors. Subclass of ResolveError
2885 * represent a different kinds of resolution error - as such they must
2886 * specify how they map into concrete compiler diagnostics.
2887 */
2888 abstract class ResolveError extends Symbol {
2890 /** The name of the kind of error, for debugging only. */
2891 final String debugName;
2893 ResolveError(int kind, String debugName) {
2894 super(kind, 0, null, null, null);
2895 this.debugName = debugName;
2896 }
2898 @Override
2899 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2900 throw new AssertionError();
2901 }
2903 @Override
2904 public String toString() {
2905 return debugName;
2906 }
2908 @Override
2909 public boolean exists() {
2910 return false;
2911 }
2913 /**
2914 * Create an external representation for this erroneous symbol to be
2915 * used during attribution - by default this returns the symbol of a
2916 * brand new error type which stores the original type found
2917 * during resolution.
2918 *
2919 * @param name the name used during resolution
2920 * @param location the location from which the symbol is accessed
2921 */
2922 protected Symbol access(Name name, TypeSymbol location) {
2923 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2924 }
2926 /**
2927 * Create a diagnostic representing this resolution error.
2928 *
2929 * @param dkind The kind of the diagnostic to be created (e.g error).
2930 * @param pos The position to be used for error reporting.
2931 * @param site The original type from where the selection took place.
2932 * @param name The name of the symbol to be resolved.
2933 * @param argtypes The invocation's value arguments,
2934 * if we looked for a method.
2935 * @param typeargtypes The invocation's type arguments,
2936 * if we looked for a method.
2937 */
2938 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2939 DiagnosticPosition pos,
2940 Symbol location,
2941 Type site,
2942 Name name,
2943 List<Type> argtypes,
2944 List<Type> typeargtypes);
2945 }
2947 /**
2948 * This class is the root class of all resolution errors caused by
2949 * an invalid symbol being found during resolution.
2950 */
2951 abstract class InvalidSymbolError extends ResolveError {
2953 /** The invalid symbol found during resolution */
2954 Symbol sym;
2956 InvalidSymbolError(int kind, Symbol sym, String debugName) {
2957 super(kind, debugName);
2958 this.sym = sym;
2959 }
2961 @Override
2962 public boolean exists() {
2963 return true;
2964 }
2966 @Override
2967 public String toString() {
2968 return super.toString() + " wrongSym=" + sym;
2969 }
2971 @Override
2972 public Symbol access(Name name, TypeSymbol location) {
2973 if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
2974 return types.createErrorType(name, location, sym.type).tsym;
2975 else
2976 return sym;
2977 }
2978 }
2980 /**
2981 * InvalidSymbolError error class indicating that a symbol matching a
2982 * given name does not exists in a given site.
2983 */
2984 class SymbolNotFoundError extends ResolveError {
2986 SymbolNotFoundError(int kind) {
2987 super(kind, "symbol not found error");
2988 }
2990 @Override
2991 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2992 DiagnosticPosition pos,
2993 Symbol location,
2994 Type site,
2995 Name name,
2996 List<Type> argtypes,
2997 List<Type> typeargtypes) {
2998 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
2999 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3000 if (name == names.error)
3001 return null;
3003 if (syms.operatorNames.contains(name)) {
3004 boolean isUnaryOp = argtypes.size() == 1;
3005 String key = argtypes.size() == 1 ?
3006 "operator.cant.be.applied" :
3007 "operator.cant.be.applied.1";
3008 Type first = argtypes.head;
3009 Type second = !isUnaryOp ? argtypes.tail.head : null;
3010 return diags.create(dkind, log.currentSource(), pos,
3011 key, name, first, second);
3012 }
3013 boolean hasLocation = false;
3014 if (location == null) {
3015 location = site.tsym;
3016 }
3017 if (!location.name.isEmpty()) {
3018 if (location.kind == PCK && !site.tsym.exists()) {
3019 return diags.create(dkind, log.currentSource(), pos,
3020 "doesnt.exist", location);
3021 }
3022 hasLocation = !location.name.equals(names._this) &&
3023 !location.name.equals(names._super);
3024 }
3025 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
3026 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
3027 Name idname = isConstructor ? site.tsym.name : name;
3028 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3029 if (hasLocation) {
3030 return diags.create(dkind, log.currentSource(), pos,
3031 errKey, kindname, idname, //symbol kindname, name
3032 typeargtypes, args(argtypes), //type parameters and arguments (if any)
3033 getLocationDiag(location, site)); //location kindname, type
3034 }
3035 else {
3036 return diags.create(dkind, log.currentSource(), pos,
3037 errKey, kindname, idname, //symbol kindname, name
3038 typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3039 }
3040 }
3041 //where
3042 private Object args(List<Type> args) {
3043 return args.isEmpty() ? args : methodArguments(args);
3044 }
3046 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3047 String key = "cant.resolve";
3048 String suffix = hasLocation ? ".location" : "";
3049 switch (kindname) {
3050 case METHOD:
3051 case CONSTRUCTOR: {
3052 suffix += ".args";
3053 suffix += hasTypeArgs ? ".params" : "";
3054 }
3055 }
3056 return key + suffix;
3057 }
3058 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3059 if (location.kind == VAR) {
3060 return diags.fragment("location.1",
3061 kindName(location),
3062 location,
3063 location.type);
3064 } else {
3065 return diags.fragment("location",
3066 typeKindName(site),
3067 site,
3068 null);
3069 }
3070 }
3071 }
3073 /**
3074 * InvalidSymbolError error class indicating that a given symbol
3075 * (either a method, a constructor or an operand) is not applicable
3076 * given an actual arguments/type argument list.
3077 */
3078 class InapplicableSymbolError extends ResolveError {
3080 protected MethodResolutionContext resolveContext;
3082 InapplicableSymbolError(MethodResolutionContext context) {
3083 this(WRONG_MTH, "inapplicable symbol error", context);
3084 }
3086 protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
3087 super(kind, debugName);
3088 this.resolveContext = context;
3089 }
3091 @Override
3092 public String toString() {
3093 return super.toString();
3094 }
3096 @Override
3097 public boolean exists() {
3098 return true;
3099 }
3101 @Override
3102 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3103 DiagnosticPosition pos,
3104 Symbol location,
3105 Type site,
3106 Name name,
3107 List<Type> argtypes,
3108 List<Type> typeargtypes) {
3109 if (name == names.error)
3110 return null;
3112 if (syms.operatorNames.contains(name)) {
3113 boolean isUnaryOp = argtypes.size() == 1;
3114 String key = argtypes.size() == 1 ?
3115 "operator.cant.be.applied" :
3116 "operator.cant.be.applied.1";
3117 Type first = argtypes.head;
3118 Type second = !isUnaryOp ? argtypes.tail.head : null;
3119 return diags.create(dkind, log.currentSource(), pos,
3120 key, name, first, second);
3121 }
3122 else {
3123 Candidate c = errCandidate();
3124 Symbol ws = c.sym.asMemberOf(site, types);
3125 return diags.create(dkind, log.currentSource(), pos,
3126 "cant.apply.symbol",
3127 kindName(ws),
3128 ws.name == names.init ? ws.owner.name : ws.name,
3129 methodArguments(ws.type.getParameterTypes()),
3130 methodArguments(argtypes),
3131 kindName(ws.owner),
3132 ws.owner.type,
3133 c.details);
3134 }
3135 }
3137 @Override
3138 public Symbol access(Name name, TypeSymbol location) {
3139 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3140 }
3142 private Candidate errCandidate() {
3143 Candidate bestSoFar = null;
3144 for (Candidate c : resolveContext.candidates) {
3145 if (c.isApplicable()) continue;
3146 bestSoFar = c;
3147 }
3148 Assert.checkNonNull(bestSoFar);
3149 return bestSoFar;
3150 }
3151 }
3153 /**
3154 * ResolveError error class indicating that a set of symbols
3155 * (either methods, constructors or operands) is not applicable
3156 * given an actual arguments/type argument list.
3157 */
3158 class InapplicableSymbolsError extends InapplicableSymbolError {
3160 InapplicableSymbolsError(MethodResolutionContext context) {
3161 super(WRONG_MTHS, "inapplicable symbols", context);
3162 }
3164 @Override
3165 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3166 DiagnosticPosition pos,
3167 Symbol location,
3168 Type site,
3169 Name name,
3170 List<Type> argtypes,
3171 List<Type> typeargtypes) {
3172 if (!resolveContext.candidates.isEmpty()) {
3173 JCDiagnostic err = diags.create(dkind,
3174 log.currentSource(),
3175 pos,
3176 "cant.apply.symbols",
3177 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
3178 name == names.init ? site.tsym.name : name,
3179 methodArguments(argtypes));
3180 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
3181 } else {
3182 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3183 location, site, name, argtypes, typeargtypes);
3184 }
3185 }
3187 //where
3188 List<JCDiagnostic> candidateDetails(Type site) {
3189 Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
3190 for (Candidate c : resolveContext.candidates) {
3191 if (c.isApplicable()) continue;
3192 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3193 Kinds.kindName(c.sym),
3194 c.sym.location(site, types),
3195 c.sym.asMemberOf(site, types),
3196 c.details);
3197 details.put(c.sym, detailDiag);
3198 }
3199 return List.from(details.values());
3200 }
3201 }
3203 /**
3204 * An InvalidSymbolError error class indicating that a symbol is not
3205 * accessible from a given site
3206 */
3207 class AccessError extends InvalidSymbolError {
3209 private Env<AttrContext> env;
3210 private Type site;
3212 AccessError(Symbol sym) {
3213 this(null, null, sym);
3214 }
3216 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3217 super(HIDDEN, sym, "access error");
3218 this.env = env;
3219 this.site = site;
3220 if (debugResolve)
3221 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3222 }
3224 @Override
3225 public boolean exists() {
3226 return false;
3227 }
3229 @Override
3230 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3231 DiagnosticPosition pos,
3232 Symbol location,
3233 Type site,
3234 Name name,
3235 List<Type> argtypes,
3236 List<Type> typeargtypes) {
3237 if (sym.owner.type.hasTag(ERROR))
3238 return null;
3240 if (sym.name == names.init && sym.owner != site.tsym) {
3241 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3242 pos, location, site, name, argtypes, typeargtypes);
3243 }
3244 else if ((sym.flags() & PUBLIC) != 0
3245 || (env != null && this.site != null
3246 && !isAccessible(env, this.site))) {
3247 return diags.create(dkind, log.currentSource(),
3248 pos, "not.def.access.class.intf.cant.access",
3249 sym, sym.location());
3250 }
3251 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3252 return diags.create(dkind, log.currentSource(),
3253 pos, "report.access", sym,
3254 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3255 sym.location());
3256 }
3257 else {
3258 return diags.create(dkind, log.currentSource(),
3259 pos, "not.def.public.cant.access", sym, sym.location());
3260 }
3261 }
3262 }
3264 /**
3265 * InvalidSymbolError error class indicating that an instance member
3266 * has erroneously been accessed from a static context.
3267 */
3268 class StaticError extends InvalidSymbolError {
3270 StaticError(Symbol sym) {
3271 super(STATICERR, sym, "static error");
3272 }
3274 @Override
3275 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3276 DiagnosticPosition pos,
3277 Symbol location,
3278 Type site,
3279 Name name,
3280 List<Type> argtypes,
3281 List<Type> typeargtypes) {
3282 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3283 ? types.erasure(sym.type).tsym
3284 : sym);
3285 return diags.create(dkind, log.currentSource(), pos,
3286 "non-static.cant.be.ref", kindName(sym), errSym);
3287 }
3288 }
3290 /**
3291 * InvalidSymbolError error class indicating that a pair of symbols
3292 * (either methods, constructors or operands) are ambiguous
3293 * given an actual arguments/type argument list.
3294 */
3295 class AmbiguityError extends ResolveError {
3297 /** The other maximally specific symbol */
3298 List<Symbol> ambiguousSyms = List.nil();
3300 @Override
3301 public boolean exists() {
3302 return true;
3303 }
3305 AmbiguityError(Symbol sym1, Symbol sym2) {
3306 super(AMBIGUOUS, "ambiguity error");
3307 ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3308 }
3310 private List<Symbol> flatten(Symbol sym) {
3311 if (sym.kind == AMBIGUOUS) {
3312 return ((AmbiguityError)sym).ambiguousSyms;
3313 } else {
3314 return List.of(sym);
3315 }
3316 }
3318 AmbiguityError addAmbiguousSymbol(Symbol s) {
3319 ambiguousSyms = ambiguousSyms.prepend(s);
3320 return this;
3321 }
3323 @Override
3324 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3325 DiagnosticPosition pos,
3326 Symbol location,
3327 Type site,
3328 Name name,
3329 List<Type> argtypes,
3330 List<Type> typeargtypes) {
3331 List<Symbol> diagSyms = ambiguousSyms.reverse();
3332 Symbol s1 = diagSyms.head;
3333 Symbol s2 = diagSyms.tail.head;
3334 Name sname = s1.name;
3335 if (sname == names.init) sname = s1.owner.name;
3336 return diags.create(dkind, log.currentSource(),
3337 pos, "ref.ambiguous", sname,
3338 kindName(s1),
3339 s1,
3340 s1.location(site, types),
3341 kindName(s2),
3342 s2,
3343 s2.location(site, types));
3344 }
3346 /**
3347 * If multiple applicable methods are found during overload and none of them
3348 * is more specific than the others, attempt to merge their signatures.
3349 */
3350 Symbol mergeAbstracts(Type site) {
3351 Symbol fst = ambiguousSyms.last();
3352 Symbol res = fst;
3353 for (Symbol s : ambiguousSyms.reverse()) {
3354 Type mt1 = types.memberType(site, res);
3355 Type mt2 = types.memberType(site, s);
3356 if ((s.flags() & ABSTRACT) == 0 ||
3357 !types.overrideEquivalent(mt1, mt2) ||
3358 !types.isSameTypes(fst.erasure(types).getParameterTypes(),
3359 s.erasure(types).getParameterTypes())) {
3360 //ambiguity cannot be resolved
3361 return this;
3362 } else {
3363 Type mst = mostSpecificReturnType(mt1, mt2);
3364 if (mst == null) {
3365 // Theoretically, this can't happen, but it is possible
3366 // due to error recovery or mixing incompatible class files
3367 return this;
3368 }
3369 Symbol mostSpecific = mst == mt1 ? res : s;
3370 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
3371 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
3372 res = new MethodSymbol(
3373 mostSpecific.flags(),
3374 mostSpecific.name,
3375 newSig,
3376 mostSpecific.owner);
3377 }
3378 }
3379 return res;
3380 }
3382 @Override
3383 protected Symbol access(Name name, TypeSymbol location) {
3384 return ambiguousSyms.last();
3385 }
3386 }
3388 enum MethodResolutionPhase {
3389 BASIC(false, false),
3390 BOX(true, false),
3391 VARARITY(true, true) {
3392 @Override
3393 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
3394 switch (sym.kind) {
3395 case WRONG_MTH:
3396 return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
3397 bestSoFar :
3398 sym;
3399 case ABSENT_MTH:
3400 return bestSoFar;
3401 default:
3402 return sym;
3403 }
3404 }
3405 };
3407 final boolean isBoxingRequired;
3408 final boolean isVarargsRequired;
3410 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
3411 this.isBoxingRequired = isBoxingRequired;
3412 this.isVarargsRequired = isVarargsRequired;
3413 }
3415 public boolean isBoxingRequired() {
3416 return isBoxingRequired;
3417 }
3419 public boolean isVarargsRequired() {
3420 return isVarargsRequired;
3421 }
3423 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
3424 return (varargsEnabled || !isVarargsRequired) &&
3425 (boxingEnabled || !isBoxingRequired);
3426 }
3428 public Symbol mergeResults(Symbol prev, Symbol sym) {
3429 return sym;
3430 }
3431 }
3433 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
3435 /**
3436 * A resolution context is used to keep track of intermediate results of
3437 * overload resolution, such as list of method that are not applicable
3438 * (used to generate more precise diagnostics) and so on. Resolution contexts
3439 * can be nested - this means that when each overload resolution routine should
3440 * work within the resolution context it created.
3441 */
3442 class MethodResolutionContext {
3444 private List<Candidate> candidates = List.nil();
3446 MethodResolutionPhase step = null;
3448 private boolean internalResolution = false;
3449 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
3451 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
3452 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
3453 candidates = candidates.append(c);
3454 }
3456 void addApplicableCandidate(Symbol sym, Type mtype) {
3457 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
3458 candidates = candidates.append(c);
3459 }
3461 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext) {
3462 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext);
3463 }
3465 /**
3466 * This class represents an overload resolution candidate. There are two
3467 * kinds of candidates: applicable methods and inapplicable methods;
3468 * applicable methods have a pointer to the instantiated method type,
3469 * while inapplicable candidates contain further details about the
3470 * reason why the method has been considered inapplicable.
3471 */
3472 class Candidate {
3474 final MethodResolutionPhase step;
3475 final Symbol sym;
3476 final JCDiagnostic details;
3477 final Type mtype;
3479 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
3480 this.step = step;
3481 this.sym = sym;
3482 this.details = details;
3483 this.mtype = mtype;
3484 }
3486 @Override
3487 public boolean equals(Object o) {
3488 if (o instanceof Candidate) {
3489 Symbol s1 = this.sym;
3490 Symbol s2 = ((Candidate)o).sym;
3491 if ((s1 != s2 &&
3492 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
3493 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
3494 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
3495 return true;
3496 }
3497 return false;
3498 }
3500 boolean isApplicable() {
3501 return mtype != null;
3502 }
3503 }
3505 DeferredAttr.AttrMode attrMode() {
3506 return attrMode;
3507 }
3509 boolean internal() {
3510 return internalResolution;
3511 }
3512 }
3514 MethodResolutionContext currentResolutionContext = null;
3515 }