Wed, 06 Feb 2013 14:04:43 +0000
8007479: Refactor DeferredAttrContext so that it points to parent context
Summary: Move DeferredAttrNode out of DeferredAttrContext; add support for nested deferred contexts
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2013, 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.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.tree.JCTree.JCPolyExpression.*;
45 import com.sun.tools.javac.util.*;
46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
48 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
50 import java.util.Arrays;
51 import java.util.Collection;
52 import java.util.EnumMap;
53 import java.util.EnumSet;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.LinkedHashSet;
57 import java.util.Map;
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 public final boolean allowStructuralMostSpecific;
96 private final boolean debugResolve;
97 final EnumSet<VerboseResolutionMode> verboseResolutionMode;
99 Scope polymorphicSignatureScope;
101 protected Resolve(Context context) {
102 context.put(resolveKey, this);
103 syms = Symtab.instance(context);
105 varNotFound = new
106 SymbolNotFoundError(ABSENT_VAR);
107 methodNotFound = new
108 SymbolNotFoundError(ABSENT_MTH);
109 typeNotFound = new
110 SymbolNotFoundError(ABSENT_TYP);
112 names = Names.instance(context);
113 log = Log.instance(context);
114 attr = Attr.instance(context);
115 deferredAttr = DeferredAttr.instance(context);
116 chk = Check.instance(context);
117 infer = Infer.instance(context);
118 reader = ClassReader.instance(context);
119 treeinfo = TreeInfo.instance(context);
120 types = Types.instance(context);
121 diags = JCDiagnostic.Factory.instance(context);
122 Source source = Source.instance(context);
123 boxingEnabled = source.allowBoxing();
124 varargsEnabled = source.allowVarargs();
125 Options options = Options.instance(context);
126 debugResolve = options.isSet("debugresolve");
127 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
128 Target target = Target.instance(context);
129 allowMethodHandles = target.hasMethodHandles();
130 allowDefaultMethods = source.allowDefaultMethods();
131 allowStructuralMostSpecific = source.allowStructuralMostSpecific();
132 polymorphicSignatureScope = new Scope(syms.noSymbol);
134 inapplicableMethodException = new InapplicableMethodException(diags);
135 }
137 /** error symbols, which are returned when resolution fails
138 */
139 private final SymbolNotFoundError varNotFound;
140 private final SymbolNotFoundError methodNotFound;
141 private final SymbolNotFoundError typeNotFound;
143 public static Resolve instance(Context context) {
144 Resolve instance = context.get(resolveKey);
145 if (instance == null)
146 instance = new Resolve(context);
147 return instance;
148 }
150 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
151 enum VerboseResolutionMode {
152 SUCCESS("success"),
153 FAILURE("failure"),
154 APPLICABLE("applicable"),
155 INAPPLICABLE("inapplicable"),
156 DEFERRED_INST("deferred-inference"),
157 PREDEF("predef"),
158 OBJECT_INIT("object-init"),
159 INTERNAL("internal");
161 final String opt;
163 private VerboseResolutionMode(String opt) {
164 this.opt = opt;
165 }
167 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
168 String s = opts.get("verboseResolution");
169 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
170 if (s == null) return res;
171 if (s.contains("all")) {
172 res = EnumSet.allOf(VerboseResolutionMode.class);
173 }
174 Collection<String> args = Arrays.asList(s.split(","));
175 for (VerboseResolutionMode mode : values()) {
176 if (args.contains(mode.opt)) {
177 res.add(mode);
178 } else if (args.contains("-" + mode.opt)) {
179 res.remove(mode);
180 }
181 }
182 return res;
183 }
184 }
186 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
187 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
188 boolean success = bestSoFar.kind < ERRONEOUS;
190 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
191 return;
192 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
193 return;
194 }
196 if (bestSoFar.name == names.init &&
197 bestSoFar.owner == syms.objectType.tsym &&
198 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
199 return; //skip diags for Object constructor resolution
200 } else if (site == syms.predefClass.type &&
201 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
202 return; //skip spurious diags for predef symbols (i.e. operators)
203 } else if (currentResolutionContext.internalResolution &&
204 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
205 return;
206 }
208 int pos = 0;
209 int mostSpecificPos = -1;
210 ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
211 for (Candidate c : currentResolutionContext.candidates) {
212 if (currentResolutionContext.step != c.step ||
213 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
214 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
215 continue;
216 } else {
217 subDiags.append(c.isApplicable() ?
218 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
219 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
220 if (c.sym == bestSoFar)
221 mostSpecificPos = pos;
222 pos++;
223 }
224 }
225 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
226 List<Type> argtypes2 = Type.map(argtypes,
227 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
228 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
229 site.tsym, mostSpecificPos, currentResolutionContext.step,
230 methodArguments(argtypes2),
231 methodArguments(typeargtypes));
232 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
233 log.report(d);
234 }
236 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
237 JCDiagnostic subDiag = null;
238 if (sym.type.hasTag(FORALL)) {
239 subDiag = diags.fragment("partial.inst.sig", inst);
240 }
242 String key = subDiag == null ?
243 "applicable.method.found" :
244 "applicable.method.found.1";
246 return diags.fragment(key, pos, sym, subDiag);
247 }
249 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
250 return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
251 }
252 // </editor-fold>
254 /* ************************************************************************
255 * Identifier resolution
256 *************************************************************************/
258 /** An environment is "static" if its static level is greater than
259 * the one of its outer environment
260 */
261 protected static boolean isStatic(Env<AttrContext> env) {
262 return env.info.staticLevel > env.outer.info.staticLevel;
263 }
265 /** An environment is an "initializer" if it is a constructor or
266 * an instance initializer.
267 */
268 static boolean isInitializer(Env<AttrContext> env) {
269 Symbol owner = env.info.scope.owner;
270 return owner.isConstructor() ||
271 owner.owner.kind == TYP &&
272 (owner.kind == VAR ||
273 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
274 (owner.flags() & STATIC) == 0;
275 }
277 /** Is class accessible in given evironment?
278 * @param env The current environment.
279 * @param c The class whose accessibility is checked.
280 */
281 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
282 return isAccessible(env, c, false);
283 }
285 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
286 boolean isAccessible = false;
287 switch ((short)(c.flags() & AccessFlags)) {
288 case PRIVATE:
289 isAccessible =
290 env.enclClass.sym.outermostClass() ==
291 c.owner.outermostClass();
292 break;
293 case 0:
294 isAccessible =
295 env.toplevel.packge == c.owner // fast special case
296 ||
297 env.toplevel.packge == c.packge()
298 ||
299 // Hack: this case is added since synthesized default constructors
300 // of anonymous classes should be allowed to access
301 // classes which would be inaccessible otherwise.
302 env.enclMethod != null &&
303 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
304 break;
305 default: // error recovery
306 case PUBLIC:
307 isAccessible = true;
308 break;
309 case PROTECTED:
310 isAccessible =
311 env.toplevel.packge == c.owner // fast special case
312 ||
313 env.toplevel.packge == c.packge()
314 ||
315 isInnerSubClass(env.enclClass.sym, c.owner);
316 break;
317 }
318 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
319 isAccessible :
320 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
321 }
322 //where
323 /** Is given class a subclass of given base class, or an inner class
324 * of a subclass?
325 * Return null if no such class exists.
326 * @param c The class which is the subclass or is contained in it.
327 * @param base The base class
328 */
329 private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
330 while (c != null && !c.isSubClass(base, types)) {
331 c = c.owner.enclClass();
332 }
333 return c != null;
334 }
336 boolean isAccessible(Env<AttrContext> env, Type t) {
337 return isAccessible(env, t, false);
338 }
340 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
341 return (t.hasTag(ARRAY))
342 ? isAccessible(env, types.elemtype(t))
343 : isAccessible(env, t.tsym, checkInner);
344 }
346 /** Is symbol accessible as a member of given type in given evironment?
347 * @param env The current environment.
348 * @param site The type of which the tested symbol is regarded
349 * as a member.
350 * @param sym The symbol.
351 */
352 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
353 return isAccessible(env, site, sym, false);
354 }
355 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
356 if (sym.name == names.init && sym.owner != site.tsym) return false;
357 switch ((short)(sym.flags() & AccessFlags)) {
358 case PRIVATE:
359 return
360 (env.enclClass.sym == sym.owner // fast special case
361 ||
362 env.enclClass.sym.outermostClass() ==
363 sym.owner.outermostClass())
364 &&
365 sym.isInheritedIn(site.tsym, types);
366 case 0:
367 return
368 (env.toplevel.packge == sym.owner.owner // fast special case
369 ||
370 env.toplevel.packge == sym.packge())
371 &&
372 isAccessible(env, site, checkInner)
373 &&
374 sym.isInheritedIn(site.tsym, types)
375 &&
376 notOverriddenIn(site, sym);
377 case PROTECTED:
378 return
379 (env.toplevel.packge == sym.owner.owner // fast special case
380 ||
381 env.toplevel.packge == sym.packge()
382 ||
383 isProtectedAccessible(sym, env.enclClass.sym, site)
384 ||
385 // OK to select instance method or field from 'super' or type name
386 // (but type names should be disallowed elsewhere!)
387 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
388 &&
389 isAccessible(env, site, checkInner)
390 &&
391 notOverriddenIn(site, sym);
392 default: // this case includes erroneous combinations as well
393 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
394 }
395 }
396 //where
397 /* `sym' is accessible only if not overridden by
398 * another symbol which is a member of `site'
399 * (because, if it is overridden, `sym' is not strictly
400 * speaking a member of `site'). A polymorphic signature method
401 * cannot be overridden (e.g. MH.invokeExact(Object[])).
402 */
403 private boolean notOverriddenIn(Type site, Symbol sym) {
404 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
405 return true;
406 else {
407 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
408 return (s2 == null || s2 == sym || sym.owner == s2.owner ||
409 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
410 }
411 }
412 //where
413 /** Is given protected symbol accessible if it is selected from given site
414 * and the selection takes place in given class?
415 * @param sym The symbol with protected access
416 * @param c The class where the access takes place
417 * @site The type of the qualifier
418 */
419 private
420 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
421 while (c != null &&
422 !(c.isSubClass(sym.owner, types) &&
423 (c.flags() & INTERFACE) == 0 &&
424 // In JLS 2e 6.6.2.1, the subclass restriction applies
425 // only to instance fields and methods -- types are excluded
426 // regardless of whether they are declared 'static' or not.
427 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
428 c = c.owner.enclClass();
429 return c != null;
430 }
432 /**
433 * Performs a recursive scan of a type looking for accessibility problems
434 * from current attribution environment
435 */
436 void checkAccessibleType(Env<AttrContext> env, Type t) {
437 accessibilityChecker.visit(t, env);
438 }
440 /**
441 * Accessibility type-visitor
442 */
443 Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
444 new Types.SimpleVisitor<Void, Env<AttrContext>>() {
446 void visit(List<Type> ts, Env<AttrContext> env) {
447 for (Type t : ts) {
448 visit(t, env);
449 }
450 }
452 public Void visitType(Type t, Env<AttrContext> env) {
453 return null;
454 }
456 @Override
457 public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
458 visit(t.elemtype, env);
459 return null;
460 }
462 @Override
463 public Void visitClassType(ClassType t, Env<AttrContext> env) {
464 visit(t.getTypeArguments(), env);
465 if (!isAccessible(env, t, true)) {
466 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
467 }
468 return null;
469 }
471 @Override
472 public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
473 visit(t.type, env);
474 return null;
475 }
477 @Override
478 public Void visitMethodType(MethodType t, Env<AttrContext> env) {
479 visit(t.getParameterTypes(), env);
480 visit(t.getReturnType(), env);
481 visit(t.getThrownTypes(), env);
482 return null;
483 }
484 };
486 /** Try to instantiate the type of a method so that it fits
487 * given type arguments and argument types. If succesful, return
488 * the method's instantiated type, else return null.
489 * The instantiation will take into account an additional leading
490 * formal parameter if the method is an instance method seen as a member
491 * of un underdetermined site In this case, we treat site as an additional
492 * parameter and the parameters of the class containing the method as
493 * additional type variables that get instantiated.
494 *
495 * @param env The current environment
496 * @param site The type of which the method is a member.
497 * @param m The method symbol.
498 * @param argtypes The invocation's given value arguments.
499 * @param typeargtypes The invocation's given type arguments.
500 * @param allowBoxing Allow boxing conversions of arguments.
501 * @param useVarargs Box trailing arguments into an array for varargs.
502 */
503 Type rawInstantiate(Env<AttrContext> env,
504 Type site,
505 Symbol m,
506 ResultInfo resultInfo,
507 List<Type> argtypes,
508 List<Type> typeargtypes,
509 boolean allowBoxing,
510 boolean useVarargs,
511 MethodCheck methodCheck,
512 Warner warn) throws Infer.InferenceException {
514 Type mt = types.memberType(site, m);
515 // tvars is the list of formal type variables for which type arguments
516 // need to inferred.
517 List<Type> tvars = List.nil();
518 if (typeargtypes == null) typeargtypes = List.nil();
519 if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
520 // This is not a polymorphic method, but typeargs are supplied
521 // which is fine, see JLS 15.12.2.1
522 } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
523 ForAll pmt = (ForAll) mt;
524 if (typeargtypes.length() != pmt.tvars.length())
525 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
526 // Check type arguments are within bounds
527 List<Type> formals = pmt.tvars;
528 List<Type> actuals = typeargtypes;
529 while (formals.nonEmpty() && actuals.nonEmpty()) {
530 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
531 pmt.tvars, typeargtypes);
532 for (; bounds.nonEmpty(); bounds = bounds.tail)
533 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
534 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
535 formals = formals.tail;
536 actuals = actuals.tail;
537 }
538 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
539 } else if (mt.hasTag(FORALL)) {
540 ForAll pmt = (ForAll) mt;
541 List<Type> tvars1 = types.newInstances(pmt.tvars);
542 tvars = tvars.appendList(tvars1);
543 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
544 }
546 // find out whether we need to go the slow route via infer
547 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
548 for (List<Type> l = argtypes;
549 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
550 l = l.tail) {
551 if (l.head.hasTag(FORALL)) instNeeded = true;
552 }
554 if (instNeeded)
555 return infer.instantiateMethod(env,
556 tvars,
557 (MethodType)mt,
558 resultInfo,
559 m,
560 argtypes,
561 allowBoxing,
562 useVarargs,
563 currentResolutionContext,
564 methodCheck,
565 warn);
567 methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn),
568 argtypes, mt.getParameterTypes(), warn);
569 return mt;
570 }
572 Type checkMethod(Env<AttrContext> env,
573 Type site,
574 Symbol m,
575 ResultInfo resultInfo,
576 List<Type> argtypes,
577 List<Type> typeargtypes,
578 Warner warn) {
579 MethodResolutionContext prevContext = currentResolutionContext;
580 try {
581 currentResolutionContext = new MethodResolutionContext();
582 currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
583 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
584 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
585 step.isBoxingRequired(), step.isVarargsRequired(), resolveMethodCheck, warn);
586 }
587 finally {
588 currentResolutionContext = prevContext;
589 }
590 }
592 /** Same but returns null instead throwing a NoInstanceException
593 */
594 Type instantiate(Env<AttrContext> env,
595 Type site,
596 Symbol m,
597 ResultInfo resultInfo,
598 List<Type> argtypes,
599 List<Type> typeargtypes,
600 boolean allowBoxing,
601 boolean useVarargs,
602 MethodCheck methodCheck,
603 Warner warn) {
604 try {
605 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
606 allowBoxing, useVarargs, methodCheck, warn);
607 } catch (InapplicableMethodException ex) {
608 return null;
609 }
610 }
612 /**
613 * This interface defines an entry point that should be used to perform a
614 * method check. A method check usually consist in determining as to whether
615 * a set of types (actuals) is compatible with another set of types (formals).
616 * Since the notion of compatibility can vary depending on the circumstances,
617 * this interfaces allows to easily add new pluggable method check routines.
618 */
619 interface MethodCheck {
620 /**
621 * Main method check routine. A method check usually consist in determining
622 * as to whether a set of types (actuals) is compatible with another set of
623 * types (formals). If an incompatibility is found, an unchecked exception
624 * is assumed to be thrown.
625 */
626 void argumentsAcceptable(Env<AttrContext> env,
627 DeferredAttrContext deferredAttrContext,
628 List<Type> argtypes,
629 List<Type> formals,
630 Warner warn);
631 }
633 /**
634 * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
635 */
636 enum MethodCheckDiag {
637 /**
638 * Actuals and formals differs in length.
639 */
640 ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
641 /**
642 * An actual is incompatible with a formal.
643 */
644 ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
645 /**
646 * An actual is incompatible with the varargs element type.
647 */
648 VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
649 /**
650 * The varargs element type is inaccessible.
651 */
652 INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
654 final String basicKey;
655 final String inferKey;
657 MethodCheckDiag(String basicKey, String inferKey) {
658 this.basicKey = basicKey;
659 this.inferKey = inferKey;
660 }
661 }
663 /**
664 * Main method applicability routine. Given a list of actual types A,
665 * a list of formal types F, determines whether the types in A are
666 * compatible (by method invocation conversion) with the types in F.
667 *
668 * Since this routine is shared between overload resolution and method
669 * type-inference, a (possibly empty) inference context is used to convert
670 * formal types to the corresponding 'undet' form ahead of a compatibility
671 * check so that constraints can be propagated and collected.
672 *
673 * Moreover, if one or more types in A is a deferred type, this routine uses
674 * DeferredAttr in order to perform deferred attribution. If one or more actual
675 * deferred types are stuck, they are placed in a queue and revisited later
676 * after the remainder of the arguments have been seen. If this is not sufficient
677 * to 'unstuck' the argument, a cyclic inference error is called out.
678 *
679 * A method check handler (see above) is used in order to report errors.
680 */
681 MethodCheck resolveMethodCheck = new MethodCheck() {
682 @Override
683 public void argumentsAcceptable(final Env<AttrContext> env,
684 DeferredAttrContext deferredAttrContext,
685 List<Type> argtypes,
686 List<Type> formals,
687 Warner warn) {
688 //should we expand formals?
689 boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
691 //inference context used during this method check
692 InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
694 Type varargsFormal = useVarargs ? formals.last() : null;
696 if (varargsFormal == null &&
697 argtypes.size() != formals.size()) {
698 reportMC(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
699 }
701 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
702 ResultInfo mresult = methodCheckResult(false, formals.head, deferredAttrContext, warn);
703 mresult.check(null, argtypes.head);
704 argtypes = argtypes.tail;
705 formals = formals.tail;
706 }
708 if (formals.head != varargsFormal) {
709 reportMC(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
710 }
712 if (useVarargs) {
713 //note: if applicability check is triggered by most specific test,
714 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
715 final Type elt = types.elemtype(varargsFormal);
716 ResultInfo mresult = methodCheckResult(true, elt, deferredAttrContext, warn);
717 while (argtypes.nonEmpty()) {
718 mresult.check(null, argtypes.head);
719 argtypes = argtypes.tail;
720 }
721 //check varargs element type accessibility
722 varargsAccessible(env, elt, inferenceContext);
723 }
724 }
726 private void reportMC(MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
727 boolean inferDiag = inferenceContext != infer.emptyContext;
728 InapplicableMethodException ex = inferDiag ?
729 infer.inferenceException : inapplicableMethodException;
730 if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
731 Object[] args2 = new Object[args.length + 1];
732 System.arraycopy(args, 0, args2, 1, args.length);
733 args2[0] = inferenceContext.inferenceVars();
734 args = args2;
735 }
736 throw ex.setMessage(inferDiag ? diag.inferKey : diag.basicKey, args);
737 }
739 private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
740 if (inferenceContext.free(t)) {
741 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
742 @Override
743 public void typesInferred(InferenceContext inferenceContext) {
744 varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
745 }
746 });
747 } else {
748 if (!isAccessible(env, t)) {
749 Symbol location = env.enclClass.sym;
750 reportMC(MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
751 }
752 }
753 }
755 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
756 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
757 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
758 MethodCheckDiag methodDiag = varargsCheck ?
759 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
761 @Override
762 public void report(DiagnosticPosition pos, JCDiagnostic details) {
763 reportMC(methodDiag, deferredAttrContext.inferenceContext, details);
764 }
765 };
766 return new MethodResultInfo(to, checkContext);
767 }
768 };
770 /**
771 * Check context to be used during method applicability checks. A method check
772 * context might contain inference variables.
773 */
774 abstract class MethodCheckContext implements CheckContext {
776 boolean strict;
777 DeferredAttrContext deferredAttrContext;
778 Warner rsWarner;
780 public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
781 this.strict = strict;
782 this.deferredAttrContext = deferredAttrContext;
783 this.rsWarner = rsWarner;
784 }
786 public boolean compatible(Type found, Type req, Warner warn) {
787 return strict ?
788 types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
789 types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
790 }
792 public void report(DiagnosticPosition pos, JCDiagnostic details) {
793 throw inapplicableMethodException.setMessage(details);
794 }
796 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
797 return rsWarner;
798 }
800 public InferenceContext inferenceContext() {
801 return deferredAttrContext.inferenceContext;
802 }
804 public DeferredAttrContext deferredAttrContext() {
805 return deferredAttrContext;
806 }
807 }
809 /**
810 * ResultInfo class to be used during method applicability checks. Check
811 * for deferred types goes through special path.
812 */
813 class MethodResultInfo extends ResultInfo {
815 public MethodResultInfo(Type pt, CheckContext checkContext) {
816 attr.super(VAL, pt, checkContext);
817 }
819 @Override
820 protected Type check(DiagnosticPosition pos, Type found) {
821 if (found.hasTag(DEFERRED)) {
822 DeferredType dt = (DeferredType)found;
823 return dt.check(this);
824 } else {
825 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
826 }
827 }
829 @Override
830 protected MethodResultInfo dup(Type newPt) {
831 return new MethodResultInfo(newPt, checkContext);
832 }
834 @Override
835 protected ResultInfo dup(CheckContext newContext) {
836 return new MethodResultInfo(pt, newContext);
837 }
838 }
840 /**
841 * Most specific method applicability routine. Given a list of actual types A,
842 * a list of formal types F1, and a list of formal types F2, the routine determines
843 * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
844 * argument types A.
845 */
846 class MostSpecificCheck implements MethodCheck {
848 boolean strict;
849 List<Type> actuals;
851 MostSpecificCheck(boolean strict, List<Type> actuals) {
852 this.strict = strict;
853 this.actuals = actuals;
854 }
856 @Override
857 public void argumentsAcceptable(final Env<AttrContext> env,
858 DeferredAttrContext deferredAttrContext,
859 List<Type> formals1,
860 List<Type> formals2,
861 Warner warn) {
862 formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
863 while (formals2.nonEmpty()) {
864 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
865 mresult.check(null, formals1.head);
866 formals1 = formals1.tail;
867 formals2 = formals2.tail;
868 actuals = actuals.isEmpty() ? actuals : actuals.tail;
869 }
870 }
872 /**
873 * Create a method check context to be used during the most specific applicability check
874 */
875 ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
876 Warner rsWarner, Type actual) {
877 return attr.new ResultInfo(Kinds.VAL, to,
878 new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
879 }
881 /**
882 * Subclass of method check context class that implements most specific
883 * method conversion. If the actual type under analysis is a deferred type
884 * a full blown structural analysis is carried out.
885 */
886 class MostSpecificCheckContext extends MethodCheckContext {
888 Type actual;
890 public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
891 super(strict, deferredAttrContext, rsWarner);
892 this.actual = actual;
893 }
895 public boolean compatible(Type found, Type req, Warner warn) {
896 if (!allowStructuralMostSpecific || actual == null) {
897 return super.compatible(found, req, warn);
898 } else {
899 switch (actual.getTag()) {
900 case DEFERRED:
901 DeferredType dt = (DeferredType) actual;
902 DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
903 return (e == null || e.speculativeTree == deferredAttr.stuckTree)
904 ? false : mostSpecific(found, req, e.speculativeTree, warn);
905 default:
906 return standaloneMostSpecific(found, req, actual, warn);
907 }
908 }
909 }
911 private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
912 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
913 msc.scan(tree);
914 return msc.result;
915 }
917 boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
918 return (!t1.isPrimitive() && t2.isPrimitive())
919 ? true : super.compatible(t1, t2, warn);
920 }
922 boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
923 return (exprType.isPrimitive() == t1.isPrimitive()
924 && exprType.isPrimitive() != t2.isPrimitive())
925 ? true : super.compatible(t1, t2, warn);
926 }
928 /**
929 * Structural checker for most specific.
930 */
931 class MostSpecificChecker extends DeferredAttr.PolyScanner {
933 final Type t;
934 final Type s;
935 final Warner warn;
936 boolean result;
938 MostSpecificChecker(Type t, Type s, Warner warn) {
939 this.t = t;
940 this.s = s;
941 this.warn = warn;
942 result = true;
943 }
945 @Override
946 void skip(JCTree tree) {
947 result &= standaloneMostSpecific(t, s, tree.type, warn);
948 }
950 @Override
951 public void visitConditional(JCConditional tree) {
952 if (tree.polyKind == PolyKind.STANDALONE) {
953 result &= standaloneMostSpecific(t, s, tree.type, warn);
954 } else {
955 super.visitConditional(tree);
956 }
957 }
959 @Override
960 public void visitApply(JCMethodInvocation tree) {
961 result &= (tree.polyKind == PolyKind.STANDALONE)
962 ? standaloneMostSpecific(t, s, tree.type, warn)
963 : polyMostSpecific(t, s, warn);
964 }
966 @Override
967 public void visitNewClass(JCNewClass tree) {
968 result &= (tree.polyKind == PolyKind.STANDALONE)
969 ? standaloneMostSpecific(t, s, tree.type, warn)
970 : polyMostSpecific(t, s, warn);
971 }
973 @Override
974 public void visitReference(JCMemberReference tree) {
975 if (types.isFunctionalInterface(t.tsym) &&
976 types.isFunctionalInterface(s.tsym) &&
977 types.asSuper(t, s.tsym) == null &&
978 types.asSuper(s, t.tsym) == null) {
979 Type desc_t = types.findDescriptorType(t);
980 Type desc_s = types.findDescriptorType(s);
981 if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
982 if (!desc_s.getReturnType().hasTag(VOID)) {
983 //perform structural comparison
984 Type ret_t = desc_t.getReturnType();
985 Type ret_s = desc_s.getReturnType();
986 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
987 ? standaloneMostSpecific(ret_t, ret_s, tree.type, warn)
988 : polyMostSpecific(ret_t, ret_s, warn));
989 } else {
990 return;
991 }
992 } else {
993 result &= false;
994 }
995 } else {
996 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
997 }
998 }
1000 @Override
1001 public void visitLambda(JCLambda tree) {
1002 if (types.isFunctionalInterface(t.tsym) &&
1003 types.isFunctionalInterface(s.tsym) &&
1004 types.asSuper(t, s.tsym) == null &&
1005 types.asSuper(s, t.tsym) == null) {
1006 Type desc_t = types.findDescriptorType(t);
1007 Type desc_s = types.findDescriptorType(s);
1008 if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
1009 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
1010 if (!desc_s.getReturnType().hasTag(VOID)) {
1011 //perform structural comparison
1012 Type ret_t = desc_t.getReturnType();
1013 Type ret_s = desc_s.getReturnType();
1014 scanLambdaBody(tree, ret_t, ret_s);
1015 } else {
1016 return;
1017 }
1018 } else {
1019 result &= false;
1020 }
1021 } else {
1022 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
1023 }
1024 }
1025 //where
1027 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
1028 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
1029 result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
1030 } else {
1031 DeferredAttr.LambdaReturnScanner lambdaScanner =
1032 new DeferredAttr.LambdaReturnScanner() {
1033 @Override
1034 public void visitReturn(JCReturn tree) {
1035 if (tree.expr != null) {
1036 result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
1037 }
1038 }
1039 };
1040 lambdaScanner.scan(lambda.body);
1041 }
1042 }
1043 }
1044 }
1045 }
1047 public static class InapplicableMethodException extends RuntimeException {
1048 private static final long serialVersionUID = 0;
1050 JCDiagnostic diagnostic;
1051 JCDiagnostic.Factory diags;
1053 InapplicableMethodException(JCDiagnostic.Factory diags) {
1054 this.diagnostic = null;
1055 this.diags = diags;
1056 }
1057 InapplicableMethodException setMessage() {
1058 return setMessage((JCDiagnostic)null);
1059 }
1060 InapplicableMethodException setMessage(String key) {
1061 return setMessage(key != null ? diags.fragment(key) : null);
1062 }
1063 InapplicableMethodException setMessage(String key, Object... args) {
1064 return setMessage(key != null ? diags.fragment(key, args) : null);
1065 }
1066 InapplicableMethodException setMessage(JCDiagnostic diag) {
1067 this.diagnostic = diag;
1068 return this;
1069 }
1071 public JCDiagnostic getDiagnostic() {
1072 return diagnostic;
1073 }
1074 }
1075 private final InapplicableMethodException inapplicableMethodException;
1077 /* ***************************************************************************
1078 * Symbol lookup
1079 * the following naming conventions for arguments are used
1080 *
1081 * env is the environment where the symbol was mentioned
1082 * site is the type of which the symbol is a member
1083 * name is the symbol's name
1084 * if no arguments are given
1085 * argtypes are the value arguments, if we search for a method
1086 *
1087 * If no symbol was found, a ResolveError detailing the problem is returned.
1088 ****************************************************************************/
1090 /** Find field. Synthetic fields are always skipped.
1091 * @param env The current environment.
1092 * @param site The original type from where the selection takes place.
1093 * @param name The name of the field.
1094 * @param c The class to search for the field. This is always
1095 * a superclass or implemented interface of site's class.
1096 */
1097 Symbol findField(Env<AttrContext> env,
1098 Type site,
1099 Name name,
1100 TypeSymbol c) {
1101 while (c.type.hasTag(TYPEVAR))
1102 c = c.type.getUpperBound().tsym;
1103 Symbol bestSoFar = varNotFound;
1104 Symbol sym;
1105 Scope.Entry e = c.members().lookup(name);
1106 while (e.scope != null) {
1107 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
1108 return isAccessible(env, site, e.sym)
1109 ? e.sym : new AccessError(env, site, e.sym);
1110 }
1111 e = e.next();
1112 }
1113 Type st = types.supertype(c.type);
1114 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
1115 sym = findField(env, site, name, st.tsym);
1116 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1117 }
1118 for (List<Type> l = types.interfaces(c.type);
1119 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1120 l = l.tail) {
1121 sym = findField(env, site, name, l.head.tsym);
1122 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1123 sym.owner != bestSoFar.owner)
1124 bestSoFar = new AmbiguityError(bestSoFar, sym);
1125 else if (sym.kind < bestSoFar.kind)
1126 bestSoFar = sym;
1127 }
1128 return bestSoFar;
1129 }
1131 /** Resolve a field identifier, throw a fatal error if not found.
1132 * @param pos The position to use for error reporting.
1133 * @param env The environment current at the method invocation.
1134 * @param site The type of the qualifying expression, in which
1135 * identifier is searched.
1136 * @param name The identifier's name.
1137 */
1138 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
1139 Type site, Name name) {
1140 Symbol sym = findField(env, site, name, site.tsym);
1141 if (sym.kind == VAR) return (VarSymbol)sym;
1142 else throw new FatalError(
1143 diags.fragment("fatal.err.cant.locate.field",
1144 name));
1145 }
1147 /** Find unqualified variable or field with given name.
1148 * Synthetic fields always skipped.
1149 * @param env The current environment.
1150 * @param name The name of the variable or field.
1151 */
1152 Symbol findVar(Env<AttrContext> env, Name name) {
1153 Symbol bestSoFar = varNotFound;
1154 Symbol sym;
1155 Env<AttrContext> env1 = env;
1156 boolean staticOnly = false;
1157 while (env1.outer != null) {
1158 if (isStatic(env1)) staticOnly = true;
1159 Scope.Entry e = env1.info.scope.lookup(name);
1160 while (e.scope != null &&
1161 (e.sym.kind != VAR ||
1162 (e.sym.flags_field & SYNTHETIC) != 0))
1163 e = e.next();
1164 sym = (e.scope != null)
1165 ? e.sym
1166 : findField(
1167 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
1168 if (sym.exists()) {
1169 if (staticOnly &&
1170 sym.kind == VAR &&
1171 sym.owner.kind == TYP &&
1172 (sym.flags() & STATIC) == 0)
1173 return new StaticError(sym);
1174 else
1175 return sym;
1176 } else if (sym.kind < bestSoFar.kind) {
1177 bestSoFar = sym;
1178 }
1180 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1181 env1 = env1.outer;
1182 }
1184 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1185 if (sym.exists())
1186 return sym;
1187 if (bestSoFar.exists())
1188 return bestSoFar;
1190 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1191 for (; e.scope != null; e = e.next()) {
1192 sym = e.sym;
1193 Type origin = e.getOrigin().owner.type;
1194 if (sym.kind == VAR) {
1195 if (e.sym.owner.type != origin)
1196 sym = sym.clone(e.getOrigin().owner);
1197 return isAccessible(env, origin, sym)
1198 ? sym : new AccessError(env, origin, sym);
1199 }
1200 }
1202 Symbol origin = null;
1203 e = env.toplevel.starImportScope.lookup(name);
1204 for (; e.scope != null; e = e.next()) {
1205 sym = e.sym;
1206 if (sym.kind != VAR)
1207 continue;
1208 // invariant: sym.kind == VAR
1209 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
1210 return new AmbiguityError(bestSoFar, sym);
1211 else if (bestSoFar.kind >= VAR) {
1212 origin = e.getOrigin().owner;
1213 bestSoFar = isAccessible(env, origin.type, sym)
1214 ? sym : new AccessError(env, origin.type, sym);
1215 }
1216 }
1217 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1218 return bestSoFar.clone(origin);
1219 else
1220 return bestSoFar;
1221 }
1223 Warner noteWarner = new Warner();
1225 /** Select the best method for a call site among two choices.
1226 * @param env The current environment.
1227 * @param site The original type from where the
1228 * selection takes place.
1229 * @param argtypes The invocation's value arguments,
1230 * @param typeargtypes The invocation's type arguments,
1231 * @param sym Proposed new best match.
1232 * @param bestSoFar Previously found best match.
1233 * @param allowBoxing Allow boxing conversions of arguments.
1234 * @param useVarargs Box trailing arguments into an array for varargs.
1235 */
1236 @SuppressWarnings("fallthrough")
1237 Symbol selectBest(Env<AttrContext> env,
1238 Type site,
1239 List<Type> argtypes,
1240 List<Type> typeargtypes,
1241 Symbol sym,
1242 Symbol bestSoFar,
1243 boolean allowBoxing,
1244 boolean useVarargs,
1245 boolean operator) {
1246 if (sym.kind == ERR ||
1247 !sym.isInheritedIn(site.tsym, types) ||
1248 (useVarargs && (sym.flags() & VARARGS) == 0)) {
1249 return bestSoFar;
1250 }
1251 Assert.check(sym.kind < AMBIGUOUS);
1252 try {
1253 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1254 allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
1255 if (!operator)
1256 currentResolutionContext.addApplicableCandidate(sym, mt);
1257 } catch (InapplicableMethodException ex) {
1258 if (!operator)
1259 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1260 switch (bestSoFar.kind) {
1261 case ABSENT_MTH:
1262 return new InapplicableSymbolError(currentResolutionContext);
1263 case WRONG_MTH:
1264 if (operator) return bestSoFar;
1265 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1266 default:
1267 return bestSoFar;
1268 }
1269 }
1270 if (!isAccessible(env, site, sym)) {
1271 return (bestSoFar.kind == ABSENT_MTH)
1272 ? new AccessError(env, site, sym)
1273 : bestSoFar;
1274 }
1275 return (bestSoFar.kind > AMBIGUOUS)
1276 ? sym
1277 : mostSpecific(argtypes, sym, bestSoFar, env, site,
1278 allowBoxing && operator, useVarargs);
1279 }
1281 /* Return the most specific of the two methods for a call,
1282 * given that both are accessible and applicable.
1283 * @param m1 A new candidate for most specific.
1284 * @param m2 The previous most specific candidate.
1285 * @param env The current environment.
1286 * @param site The original type from where the selection
1287 * takes place.
1288 * @param allowBoxing Allow boxing conversions of arguments.
1289 * @param useVarargs Box trailing arguments into an array for varargs.
1290 */
1291 Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1292 Symbol m2,
1293 Env<AttrContext> env,
1294 final Type site,
1295 boolean allowBoxing,
1296 boolean useVarargs) {
1297 switch (m2.kind) {
1298 case MTH:
1299 if (m1 == m2) return m1;
1300 boolean m1SignatureMoreSpecific =
1301 signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1302 boolean m2SignatureMoreSpecific =
1303 signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1304 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1305 Type mt1 = types.memberType(site, m1);
1306 Type mt2 = types.memberType(site, m2);
1307 if (!types.overrideEquivalent(mt1, mt2))
1308 return ambiguityError(m1, m2);
1310 // same signature; select (a) the non-bridge method, or
1311 // (b) the one that overrides the other, or (c) the concrete
1312 // one, or (d) merge both abstract signatures
1313 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1314 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1316 // if one overrides or hides the other, use it
1317 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1318 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1319 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1320 ((m1.owner.flags_field & INTERFACE) == 0 ||
1321 (m2.owner.flags_field & INTERFACE) != 0) &&
1322 m1.overrides(m2, m1Owner, types, false))
1323 return m1;
1324 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1325 ((m2.owner.flags_field & INTERFACE) == 0 ||
1326 (m1.owner.flags_field & INTERFACE) != 0) &&
1327 m2.overrides(m1, m2Owner, types, false))
1328 return m2;
1329 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1330 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1331 if (m1Abstract && !m2Abstract) return m2;
1332 if (m2Abstract && !m1Abstract) return m1;
1333 // both abstract or both concrete
1334 return ambiguityError(m1, m2);
1335 }
1336 if (m1SignatureMoreSpecific) return m1;
1337 if (m2SignatureMoreSpecific) return m2;
1338 return ambiguityError(m1, m2);
1339 case AMBIGUOUS:
1340 //check if m1 is more specific than all ambiguous methods in m2
1341 AmbiguityError e = (AmbiguityError)m2;
1342 for (Symbol s : e.ambiguousSyms) {
1343 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
1344 return e.addAmbiguousSymbol(m1);
1345 }
1346 }
1347 return m1;
1348 default:
1349 throw new AssertionError();
1350 }
1351 }
1352 //where
1353 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1354 noteWarner.clear();
1355 int maxLength = Math.max(
1356 Math.max(m1.type.getParameterTypes().length(), actuals.length()),
1357 m2.type.getParameterTypes().length());
1358 Type mst = instantiate(env, site, m2, null,
1359 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
1360 allowBoxing, useVarargs, new MostSpecificCheck(!allowBoxing, actuals), noteWarner);
1361 return mst != null &&
1362 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1363 }
1364 private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
1365 if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
1366 Type varargsElem = types.elemtype(args.last());
1367 if (varargsElem == null) {
1368 Assert.error("Bad varargs = " + args.last() + " " + msym);
1369 }
1370 List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
1371 while (newArgs.length() < length) {
1372 newArgs = newArgs.append(newArgs.last());
1373 }
1374 return newArgs;
1375 } else {
1376 return args;
1377 }
1378 }
1379 //where
1380 Type mostSpecificReturnType(Type mt1, Type mt2) {
1381 Type rt1 = mt1.getReturnType();
1382 Type rt2 = mt2.getReturnType();
1384 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1385 //if both are generic methods, adjust return type ahead of subtyping check
1386 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1387 }
1388 //first use subtyping, then return type substitutability
1389 if (types.isSubtype(rt1, rt2)) {
1390 return mt1;
1391 } else if (types.isSubtype(rt2, rt1)) {
1392 return mt2;
1393 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1394 return mt1;
1395 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1396 return mt2;
1397 } else {
1398 return null;
1399 }
1400 }
1401 //where
1402 Symbol ambiguityError(Symbol m1, Symbol m2) {
1403 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1404 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1405 } else {
1406 return new AmbiguityError(m1, m2);
1407 }
1408 }
1410 Symbol findMethodInScope(Env<AttrContext> env,
1411 Type site,
1412 Name name,
1413 List<Type> argtypes,
1414 List<Type> typeargtypes,
1415 Scope sc,
1416 Symbol bestSoFar,
1417 boolean allowBoxing,
1418 boolean useVarargs,
1419 boolean operator,
1420 boolean abstractok) {
1421 for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
1422 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1423 bestSoFar, allowBoxing, useVarargs, operator);
1424 }
1425 return bestSoFar;
1426 }
1427 //where
1428 class LookupFilter implements Filter<Symbol> {
1430 boolean abstractOk;
1432 LookupFilter(boolean abstractOk) {
1433 this.abstractOk = abstractOk;
1434 }
1436 public boolean accepts(Symbol s) {
1437 long flags = s.flags();
1438 return s.kind == MTH &&
1439 (flags & SYNTHETIC) == 0 &&
1440 (abstractOk ||
1441 (flags & DEFAULT) != 0 ||
1442 (flags & ABSTRACT) == 0);
1443 }
1444 };
1446 /** Find best qualified method matching given name, type and value
1447 * arguments.
1448 * @param env The current environment.
1449 * @param site The original type from where the selection
1450 * takes place.
1451 * @param name The method's name.
1452 * @param argtypes The method's value arguments.
1453 * @param typeargtypes The method's type arguments
1454 * @param allowBoxing Allow boxing conversions of arguments.
1455 * @param useVarargs Box trailing arguments into an array for varargs.
1456 */
1457 Symbol findMethod(Env<AttrContext> env,
1458 Type site,
1459 Name name,
1460 List<Type> argtypes,
1461 List<Type> typeargtypes,
1462 boolean allowBoxing,
1463 boolean useVarargs,
1464 boolean operator) {
1465 Symbol bestSoFar = methodNotFound;
1466 bestSoFar = findMethod(env,
1467 site,
1468 name,
1469 argtypes,
1470 typeargtypes,
1471 site.tsym.type,
1472 bestSoFar,
1473 allowBoxing,
1474 useVarargs,
1475 operator);
1476 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1477 return bestSoFar;
1478 }
1479 // where
1480 private Symbol findMethod(Env<AttrContext> env,
1481 Type site,
1482 Name name,
1483 List<Type> argtypes,
1484 List<Type> typeargtypes,
1485 Type intype,
1486 Symbol bestSoFar,
1487 boolean allowBoxing,
1488 boolean useVarargs,
1489 boolean operator) {
1490 @SuppressWarnings({"unchecked","rawtypes"})
1491 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1492 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1493 for (TypeSymbol s : superclasses(intype)) {
1494 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1495 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1496 if (name == names.init) return bestSoFar;
1497 iphase = (iphase == null) ? null : iphase.update(s, this);
1498 if (iphase != null) {
1499 for (Type itype : types.interfaces(s.type)) {
1500 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1501 }
1502 }
1503 }
1505 Symbol concrete = bestSoFar.kind < ERR &&
1506 (bestSoFar.flags() & ABSTRACT) == 0 ?
1507 bestSoFar : methodNotFound;
1509 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1510 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
1511 //keep searching for abstract methods
1512 for (Type itype : itypes[iphase2.ordinal()]) {
1513 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1514 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1515 (itype.tsym.flags() & DEFAULT) == 0) continue;
1516 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1517 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1518 if (concrete != bestSoFar &&
1519 concrete.kind < ERR && bestSoFar.kind < ERR &&
1520 types.isSubSignature(concrete.type, bestSoFar.type)) {
1521 //this is an hack - as javac does not do full membership checks
1522 //most specific ends up comparing abstract methods that might have
1523 //been implemented by some concrete method in a subclass and,
1524 //because of raw override, it is possible for an abstract method
1525 //to be more specific than the concrete method - so we need
1526 //to explicitly call that out (see CR 6178365)
1527 bestSoFar = concrete;
1528 }
1529 }
1530 }
1531 return bestSoFar;
1532 }
1534 enum InterfaceLookupPhase {
1535 ABSTRACT_OK() {
1536 @Override
1537 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1538 //We should not look for abstract methods if receiver is a concrete class
1539 //(as concrete classes are expected to implement all abstracts coming
1540 //from superinterfaces)
1541 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1542 return this;
1543 } else if (rs.allowDefaultMethods) {
1544 return DEFAULT_OK;
1545 } else {
1546 return null;
1547 }
1548 }
1549 },
1550 DEFAULT_OK() {
1551 @Override
1552 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1553 return this;
1554 }
1555 };
1557 abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1558 }
1560 /**
1561 * Return an Iterable object to scan the superclasses of a given type.
1562 * It's crucial that the scan is done lazily, as we don't want to accidentally
1563 * access more supertypes than strictly needed (as this could trigger completion
1564 * errors if some of the not-needed supertypes are missing/ill-formed).
1565 */
1566 Iterable<TypeSymbol> superclasses(final Type intype) {
1567 return new Iterable<TypeSymbol>() {
1568 public Iterator<TypeSymbol> iterator() {
1569 return new Iterator<TypeSymbol>() {
1571 List<TypeSymbol> seen = List.nil();
1572 TypeSymbol currentSym = symbolFor(intype);
1573 TypeSymbol prevSym = null;
1575 public boolean hasNext() {
1576 if (currentSym == syms.noSymbol) {
1577 currentSym = symbolFor(types.supertype(prevSym.type));
1578 }
1579 return currentSym != null;
1580 }
1582 public TypeSymbol next() {
1583 prevSym = currentSym;
1584 currentSym = syms.noSymbol;
1585 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1586 return prevSym;
1587 }
1589 public void remove() {
1590 throw new UnsupportedOperationException();
1591 }
1593 TypeSymbol symbolFor(Type t) {
1594 if (!t.hasTag(CLASS) &&
1595 !t.hasTag(TYPEVAR)) {
1596 return null;
1597 }
1598 while (t.hasTag(TYPEVAR))
1599 t = t.getUpperBound();
1600 if (seen.contains(t.tsym)) {
1601 //degenerate case in which we have a circular
1602 //class hierarchy - because of ill-formed classfiles
1603 return null;
1604 }
1605 seen = seen.prepend(t.tsym);
1606 return t.tsym;
1607 }
1608 };
1609 }
1610 };
1611 }
1613 /** Find unqualified method matching given name, type and value arguments.
1614 * @param env The current environment.
1615 * @param name The method's name.
1616 * @param argtypes The method's value arguments.
1617 * @param typeargtypes The method's type arguments.
1618 * @param allowBoxing Allow boxing conversions of arguments.
1619 * @param useVarargs Box trailing arguments into an array for varargs.
1620 */
1621 Symbol findFun(Env<AttrContext> env, Name name,
1622 List<Type> argtypes, List<Type> typeargtypes,
1623 boolean allowBoxing, boolean useVarargs) {
1624 Symbol bestSoFar = methodNotFound;
1625 Symbol sym;
1626 Env<AttrContext> env1 = env;
1627 boolean staticOnly = false;
1628 while (env1.outer != null) {
1629 if (isStatic(env1)) staticOnly = true;
1630 sym = findMethod(
1631 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1632 allowBoxing, useVarargs, false);
1633 if (sym.exists()) {
1634 if (staticOnly &&
1635 sym.kind == MTH &&
1636 sym.owner.kind == TYP &&
1637 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1638 else return sym;
1639 } else if (sym.kind < bestSoFar.kind) {
1640 bestSoFar = sym;
1641 }
1642 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1643 env1 = env1.outer;
1644 }
1646 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1647 typeargtypes, allowBoxing, useVarargs, false);
1648 if (sym.exists())
1649 return sym;
1651 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1652 for (; e.scope != null; e = e.next()) {
1653 sym = e.sym;
1654 Type origin = e.getOrigin().owner.type;
1655 if (sym.kind == MTH) {
1656 if (e.sym.owner.type != origin)
1657 sym = sym.clone(e.getOrigin().owner);
1658 if (!isAccessible(env, origin, sym))
1659 sym = new AccessError(env, origin, sym);
1660 bestSoFar = selectBest(env, origin,
1661 argtypes, typeargtypes,
1662 sym, bestSoFar,
1663 allowBoxing, useVarargs, false);
1664 }
1665 }
1666 if (bestSoFar.exists())
1667 return bestSoFar;
1669 e = env.toplevel.starImportScope.lookup(name);
1670 for (; e.scope != null; e = e.next()) {
1671 sym = e.sym;
1672 Type origin = e.getOrigin().owner.type;
1673 if (sym.kind == MTH) {
1674 if (e.sym.owner.type != origin)
1675 sym = sym.clone(e.getOrigin().owner);
1676 if (!isAccessible(env, origin, sym))
1677 sym = new AccessError(env, origin, sym);
1678 bestSoFar = selectBest(env, origin,
1679 argtypes, typeargtypes,
1680 sym, bestSoFar,
1681 allowBoxing, useVarargs, false);
1682 }
1683 }
1684 return bestSoFar;
1685 }
1687 /** Load toplevel or member class with given fully qualified name and
1688 * verify that it is accessible.
1689 * @param env The current environment.
1690 * @param name The fully qualified name of the class to be loaded.
1691 */
1692 Symbol loadClass(Env<AttrContext> env, Name name) {
1693 try {
1694 ClassSymbol c = reader.loadClass(name);
1695 return isAccessible(env, c) ? c : new AccessError(c);
1696 } catch (ClassReader.BadClassFile err) {
1697 throw err;
1698 } catch (CompletionFailure ex) {
1699 return typeNotFound;
1700 }
1701 }
1703 /** Find qualified member type.
1704 * @param env The current environment.
1705 * @param site The original type from where the selection takes
1706 * place.
1707 * @param name The type's name.
1708 * @param c The class to search for the member type. This is
1709 * always a superclass or implemented interface of
1710 * site's class.
1711 */
1712 Symbol findMemberType(Env<AttrContext> env,
1713 Type site,
1714 Name name,
1715 TypeSymbol c) {
1716 Symbol bestSoFar = typeNotFound;
1717 Symbol sym;
1718 Scope.Entry e = c.members().lookup(name);
1719 while (e.scope != null) {
1720 if (e.sym.kind == TYP) {
1721 return isAccessible(env, site, e.sym)
1722 ? e.sym
1723 : new AccessError(env, site, e.sym);
1724 }
1725 e = e.next();
1726 }
1727 Type st = types.supertype(c.type);
1728 if (st != null && st.hasTag(CLASS)) {
1729 sym = findMemberType(env, site, name, st.tsym);
1730 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1731 }
1732 for (List<Type> l = types.interfaces(c.type);
1733 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1734 l = l.tail) {
1735 sym = findMemberType(env, site, name, l.head.tsym);
1736 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1737 sym.owner != bestSoFar.owner)
1738 bestSoFar = new AmbiguityError(bestSoFar, sym);
1739 else if (sym.kind < bestSoFar.kind)
1740 bestSoFar = sym;
1741 }
1742 return bestSoFar;
1743 }
1745 /** Find a global type in given scope and load corresponding class.
1746 * @param env The current environment.
1747 * @param scope The scope in which to look for the type.
1748 * @param name The type's name.
1749 */
1750 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1751 Symbol bestSoFar = typeNotFound;
1752 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1753 Symbol sym = loadClass(env, e.sym.flatName());
1754 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1755 bestSoFar != sym)
1756 return new AmbiguityError(bestSoFar, sym);
1757 else if (sym.kind < bestSoFar.kind)
1758 bestSoFar = sym;
1759 }
1760 return bestSoFar;
1761 }
1763 /** Find an unqualified type symbol.
1764 * @param env The current environment.
1765 * @param name The type's name.
1766 */
1767 Symbol findType(Env<AttrContext> env, Name name) {
1768 Symbol bestSoFar = typeNotFound;
1769 Symbol sym;
1770 boolean staticOnly = false;
1771 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1772 if (isStatic(env1)) staticOnly = true;
1773 for (Scope.Entry e = env1.info.scope.lookup(name);
1774 e.scope != null;
1775 e = e.next()) {
1776 if (e.sym.kind == TYP) {
1777 if (staticOnly &&
1778 e.sym.type.hasTag(TYPEVAR) &&
1779 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1780 return e.sym;
1781 }
1782 }
1784 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1785 env1.enclClass.sym);
1786 if (staticOnly && sym.kind == TYP &&
1787 sym.type.hasTag(CLASS) &&
1788 sym.type.getEnclosingType().hasTag(CLASS) &&
1789 env1.enclClass.sym.type.isParameterized() &&
1790 sym.type.getEnclosingType().isParameterized())
1791 return new StaticError(sym);
1792 else if (sym.exists()) return sym;
1793 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1795 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1796 if ((encl.sym.flags() & STATIC) != 0)
1797 staticOnly = true;
1798 }
1800 if (!env.tree.hasTag(IMPORT)) {
1801 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1802 if (sym.exists()) return sym;
1803 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1805 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1806 if (sym.exists()) return sym;
1807 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1809 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1810 if (sym.exists()) return sym;
1811 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1812 }
1814 return bestSoFar;
1815 }
1817 /** Find an unqualified identifier which matches a specified kind set.
1818 * @param env The current environment.
1819 * @param name The identifier's name.
1820 * @param kind Indicates the possible symbol kinds
1821 * (a subset of VAL, TYP, PCK).
1822 */
1823 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1824 Symbol bestSoFar = typeNotFound;
1825 Symbol sym;
1827 if ((kind & VAR) != 0) {
1828 sym = findVar(env, name);
1829 if (sym.exists()) return sym;
1830 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1831 }
1833 if ((kind & TYP) != 0) {
1834 sym = findType(env, name);
1835 if (sym.kind==TYP) {
1836 reportDependence(env.enclClass.sym, sym);
1837 }
1838 if (sym.exists()) return sym;
1839 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1840 }
1842 if ((kind & PCK) != 0) return reader.enterPackage(name);
1843 else return bestSoFar;
1844 }
1846 /** Report dependencies.
1847 * @param from The enclosing class sym
1848 * @param to The found identifier that the class depends on.
1849 */
1850 public void reportDependence(Symbol from, Symbol to) {
1851 // Override if you want to collect the reported dependencies.
1852 }
1854 /** Find an identifier in a package which matches a specified kind set.
1855 * @param env The current environment.
1856 * @param name The identifier's name.
1857 * @param kind Indicates the possible symbol kinds
1858 * (a nonempty subset of TYP, PCK).
1859 */
1860 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1861 Name name, int kind) {
1862 Name fullname = TypeSymbol.formFullName(name, pck);
1863 Symbol bestSoFar = typeNotFound;
1864 PackageSymbol pack = null;
1865 if ((kind & PCK) != 0) {
1866 pack = reader.enterPackage(fullname);
1867 if (pack.exists()) return pack;
1868 }
1869 if ((kind & TYP) != 0) {
1870 Symbol sym = loadClass(env, fullname);
1871 if (sym.exists()) {
1872 // don't allow programs to use flatnames
1873 if (name == sym.name) return sym;
1874 }
1875 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1876 }
1877 return (pack != null) ? pack : bestSoFar;
1878 }
1880 /** Find an identifier among the members of a given type `site'.
1881 * @param env The current environment.
1882 * @param site The type containing the symbol to be found.
1883 * @param name The identifier's name.
1884 * @param kind Indicates the possible symbol kinds
1885 * (a subset of VAL, TYP).
1886 */
1887 Symbol findIdentInType(Env<AttrContext> env, Type site,
1888 Name name, int kind) {
1889 Symbol bestSoFar = typeNotFound;
1890 Symbol sym;
1891 if ((kind & VAR) != 0) {
1892 sym = findField(env, site, name, site.tsym);
1893 if (sym.exists()) return sym;
1894 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1895 }
1897 if ((kind & TYP) != 0) {
1898 sym = findMemberType(env, site, name, site.tsym);
1899 if (sym.exists()) return sym;
1900 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1901 }
1902 return bestSoFar;
1903 }
1905 /* ***************************************************************************
1906 * Access checking
1907 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1908 * an error message in the process
1909 ****************************************************************************/
1911 /** If `sym' is a bad symbol: report error and return errSymbol
1912 * else pass through unchanged,
1913 * additional arguments duplicate what has been used in trying to find the
1914 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
1915 * expect misses to happen frequently.
1916 *
1917 * @param sym The symbol that was found, or a ResolveError.
1918 * @param pos The position to use for error reporting.
1919 * @param location The symbol the served as a context for this lookup
1920 * @param site The original type from where the selection took place.
1921 * @param name The symbol's name.
1922 * @param qualified Did we get here through a qualified expression resolution?
1923 * @param argtypes The invocation's value arguments,
1924 * if we looked for a method.
1925 * @param typeargtypes The invocation's type arguments,
1926 * if we looked for a method.
1927 * @param logResolveHelper helper class used to log resolve errors
1928 */
1929 Symbol accessInternal(Symbol sym,
1930 DiagnosticPosition pos,
1931 Symbol location,
1932 Type site,
1933 Name name,
1934 boolean qualified,
1935 List<Type> argtypes,
1936 List<Type> typeargtypes,
1937 LogResolveHelper logResolveHelper) {
1938 if (sym.kind >= AMBIGUOUS) {
1939 ResolveError errSym = (ResolveError)sym;
1940 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1941 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
1942 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
1943 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1944 }
1945 }
1946 return sym;
1947 }
1949 /**
1950 * Variant of the generalized access routine, to be used for generating method
1951 * resolution diagnostics
1952 */
1953 Symbol accessMethod(Symbol sym,
1954 DiagnosticPosition pos,
1955 Symbol location,
1956 Type site,
1957 Name name,
1958 boolean qualified,
1959 List<Type> argtypes,
1960 List<Type> typeargtypes) {
1961 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
1962 }
1964 /** Same as original accessMethod(), but without location.
1965 */
1966 Symbol accessMethod(Symbol sym,
1967 DiagnosticPosition pos,
1968 Type site,
1969 Name name,
1970 boolean qualified,
1971 List<Type> argtypes,
1972 List<Type> typeargtypes) {
1973 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1974 }
1976 /**
1977 * Variant of the generalized access routine, to be used for generating variable,
1978 * type resolution diagnostics
1979 */
1980 Symbol accessBase(Symbol sym,
1981 DiagnosticPosition pos,
1982 Symbol location,
1983 Type site,
1984 Name name,
1985 boolean qualified) {
1986 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
1987 }
1989 /** Same as original accessBase(), but without location.
1990 */
1991 Symbol accessBase(Symbol sym,
1992 DiagnosticPosition pos,
1993 Type site,
1994 Name name,
1995 boolean qualified) {
1996 return accessBase(sym, pos, site.tsym, site, name, qualified);
1997 }
1999 interface LogResolveHelper {
2000 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2001 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2002 }
2004 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2005 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2006 return !site.isErroneous();
2007 }
2008 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2009 return argtypes;
2010 }
2011 };
2013 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2014 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2015 return !site.isErroneous() &&
2016 !Type.isErroneous(argtypes) &&
2017 (typeargtypes == null || !Type.isErroneous(typeargtypes));
2018 }
2019 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2020 return (syms.operatorNames.contains(name)) ?
2021 argtypes :
2022 Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
2023 }
2025 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2027 public ResolveDeferredRecoveryMap(Symbol msym) {
2028 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
2029 }
2031 @Override
2032 protected Type typeOf(DeferredType dt) {
2033 Type res = super.typeOf(dt);
2034 if (!res.isErroneous()) {
2035 switch (TreeInfo.skipParens(dt.tree).getTag()) {
2036 case LAMBDA:
2037 case REFERENCE:
2038 return dt;
2039 case CONDEXPR:
2040 return res == Type.recoveryType ?
2041 dt : res;
2042 }
2043 }
2044 return res;
2045 }
2046 }
2047 };
2049 /** Check that sym is not an abstract method.
2050 */
2051 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2052 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2053 log.error(pos, "abstract.cant.be.accessed.directly",
2054 kindName(sym), sym, sym.location());
2055 }
2057 /* ***************************************************************************
2058 * Debugging
2059 ****************************************************************************/
2061 /** print all scopes starting with scope s and proceeding outwards.
2062 * used for debugging.
2063 */
2064 public void printscopes(Scope s) {
2065 while (s != null) {
2066 if (s.owner != null)
2067 System.err.print(s.owner + ": ");
2068 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
2069 if ((e.sym.flags() & ABSTRACT) != 0)
2070 System.err.print("abstract ");
2071 System.err.print(e.sym + " ");
2072 }
2073 System.err.println();
2074 s = s.next;
2075 }
2076 }
2078 void printscopes(Env<AttrContext> env) {
2079 while (env.outer != null) {
2080 System.err.println("------------------------------");
2081 printscopes(env.info.scope);
2082 env = env.outer;
2083 }
2084 }
2086 public void printscopes(Type t) {
2087 while (t.hasTag(CLASS)) {
2088 printscopes(t.tsym.members());
2089 t = types.supertype(t);
2090 }
2091 }
2093 /* ***************************************************************************
2094 * Name resolution
2095 * Naming conventions are as for symbol lookup
2096 * Unlike the find... methods these methods will report access errors
2097 ****************************************************************************/
2099 /** Resolve an unqualified (non-method) identifier.
2100 * @param pos The position to use for error reporting.
2101 * @param env The environment current at the identifier use.
2102 * @param name The identifier's name.
2103 * @param kind The set of admissible symbol kinds for the identifier.
2104 */
2105 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2106 Name name, int kind) {
2107 return accessBase(
2108 findIdent(env, name, kind),
2109 pos, env.enclClass.sym.type, name, false);
2110 }
2112 /** Resolve an unqualified method identifier.
2113 * @param pos The position to use for error reporting.
2114 * @param env The environment current at the method invocation.
2115 * @param name The identifier's name.
2116 * @param argtypes The types of the invocation's value arguments.
2117 * @param typeargtypes The types of the invocation's type arguments.
2118 */
2119 Symbol resolveMethod(DiagnosticPosition pos,
2120 Env<AttrContext> env,
2121 Name name,
2122 List<Type> argtypes,
2123 List<Type> typeargtypes) {
2124 return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2125 @Override
2126 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2127 return findFun(env, name, argtypes, typeargtypes,
2128 phase.isBoxingRequired(),
2129 phase.isVarargsRequired());
2130 }
2131 });
2132 }
2134 /** Resolve a qualified method identifier
2135 * @param pos The position to use for error reporting.
2136 * @param env The environment current at the method invocation.
2137 * @param site The type of the qualifying expression, in which
2138 * identifier is searched.
2139 * @param name The identifier's name.
2140 * @param argtypes The types of the invocation's value arguments.
2141 * @param typeargtypes The types of the invocation's type arguments.
2142 */
2143 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2144 Type site, Name name, List<Type> argtypes,
2145 List<Type> typeargtypes) {
2146 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2147 }
2148 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2149 Symbol location, Type site, Name name, List<Type> argtypes,
2150 List<Type> typeargtypes) {
2151 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2152 }
2153 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2154 DiagnosticPosition pos, Env<AttrContext> env,
2155 Symbol location, Type site, Name name, List<Type> argtypes,
2156 List<Type> typeargtypes) {
2157 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2158 @Override
2159 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2160 return findMethod(env, site, name, argtypes, typeargtypes,
2161 phase.isBoxingRequired(),
2162 phase.isVarargsRequired(), false);
2163 }
2164 @Override
2165 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2166 if (sym.kind >= AMBIGUOUS) {
2167 sym = super.access(env, pos, location, sym);
2168 } else if (allowMethodHandles) {
2169 MethodSymbol msym = (MethodSymbol)sym;
2170 if (msym.isSignaturePolymorphic(types)) {
2171 return findPolymorphicSignatureInstance(env, sym, argtypes);
2172 }
2173 }
2174 return sym;
2175 }
2176 });
2177 }
2179 /** Find or create an implicit method of exactly the given type (after erasure).
2180 * Searches in a side table, not the main scope of the site.
2181 * This emulates the lookup process required by JSR 292 in JVM.
2182 * @param env Attribution environment
2183 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
2184 * @param argtypes The required argument types
2185 */
2186 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2187 final Symbol spMethod,
2188 List<Type> argtypes) {
2189 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2190 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2191 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
2192 if (types.isSameType(mtype, sym.type)) {
2193 return sym;
2194 }
2195 }
2197 // create the desired method
2198 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2199 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2200 @Override
2201 public Symbol baseSymbol() {
2202 return spMethod;
2203 }
2204 };
2205 polymorphicSignatureScope.enter(msym);
2206 return msym;
2207 }
2209 /** Resolve a qualified method identifier, throw a fatal error if not
2210 * found.
2211 * @param pos The position to use for error reporting.
2212 * @param env The environment current at the method invocation.
2213 * @param site The type of the qualifying expression, in which
2214 * identifier is searched.
2215 * @param name The identifier's name.
2216 * @param argtypes The types of the invocation's value arguments.
2217 * @param typeargtypes The types of the invocation's type arguments.
2218 */
2219 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2220 Type site, Name name,
2221 List<Type> argtypes,
2222 List<Type> typeargtypes) {
2223 MethodResolutionContext resolveContext = new MethodResolutionContext();
2224 resolveContext.internalResolution = true;
2225 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2226 site, name, argtypes, typeargtypes);
2227 if (sym.kind == MTH) return (MethodSymbol)sym;
2228 else throw new FatalError(
2229 diags.fragment("fatal.err.cant.locate.meth",
2230 name));
2231 }
2233 /** Resolve constructor.
2234 * @param pos The position to use for error reporting.
2235 * @param env The environment current at the constructor invocation.
2236 * @param site The type of class for which a constructor is searched.
2237 * @param argtypes The types of the constructor invocation's value
2238 * arguments.
2239 * @param typeargtypes The types of the constructor invocation's type
2240 * arguments.
2241 */
2242 Symbol resolveConstructor(DiagnosticPosition pos,
2243 Env<AttrContext> env,
2244 Type site,
2245 List<Type> argtypes,
2246 List<Type> typeargtypes) {
2247 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2248 }
2250 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2251 final DiagnosticPosition pos,
2252 Env<AttrContext> env,
2253 Type site,
2254 List<Type> argtypes,
2255 List<Type> typeargtypes) {
2256 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2257 @Override
2258 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2259 return findConstructor(pos, env, site, argtypes, typeargtypes,
2260 phase.isBoxingRequired(),
2261 phase.isVarargsRequired());
2262 }
2263 });
2264 }
2266 /** Resolve a constructor, throw a fatal error if not found.
2267 * @param pos The position to use for error reporting.
2268 * @param env The environment current at the method invocation.
2269 * @param site The type to be constructed.
2270 * @param argtypes The types of the invocation's value arguments.
2271 * @param typeargtypes The types of the invocation's type arguments.
2272 */
2273 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2274 Type site,
2275 List<Type> argtypes,
2276 List<Type> typeargtypes) {
2277 MethodResolutionContext resolveContext = new MethodResolutionContext();
2278 resolveContext.internalResolution = true;
2279 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2280 if (sym.kind == MTH) return (MethodSymbol)sym;
2281 else throw new FatalError(
2282 diags.fragment("fatal.err.cant.locate.ctor", site));
2283 }
2285 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2286 Type site, List<Type> argtypes,
2287 List<Type> typeargtypes,
2288 boolean allowBoxing,
2289 boolean useVarargs) {
2290 Symbol sym = findMethod(env, site,
2291 names.init, argtypes,
2292 typeargtypes, allowBoxing,
2293 useVarargs, false);
2294 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2295 return sym;
2296 }
2298 /** Resolve constructor using diamond inference.
2299 * @param pos The position to use for error reporting.
2300 * @param env The environment current at the constructor invocation.
2301 * @param site The type of class for which a constructor is searched.
2302 * The scope of this class has been touched in attribution.
2303 * @param argtypes The types of the constructor invocation's value
2304 * arguments.
2305 * @param typeargtypes The types of the constructor invocation's type
2306 * arguments.
2307 */
2308 Symbol resolveDiamond(DiagnosticPosition pos,
2309 Env<AttrContext> env,
2310 Type site,
2311 List<Type> argtypes,
2312 List<Type> typeargtypes) {
2313 return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2314 @Override
2315 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2316 return findDiamond(env, site, argtypes, typeargtypes,
2317 phase.isBoxingRequired(),
2318 phase.isVarargsRequired());
2319 }
2320 @Override
2321 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2322 if (sym.kind >= AMBIGUOUS) {
2323 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2324 ((InapplicableSymbolError)sym).errCandidate().details :
2325 null;
2326 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2327 @Override
2328 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2329 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2330 String key = details == null ?
2331 "cant.apply.diamond" :
2332 "cant.apply.diamond.1";
2333 return diags.create(dkind, log.currentSource(), pos, key,
2334 diags.fragment("diamond", site.tsym), details);
2335 }
2336 };
2337 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2338 env.info.pendingResolutionPhase = currentResolutionContext.step;
2339 }
2340 return sym;
2341 }
2342 });
2343 }
2345 /** This method scans all the constructor symbol in a given class scope -
2346 * assuming that the original scope contains a constructor of the kind:
2347 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2348 * a method check is executed against the modified constructor type:
2349 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2350 * inference. The inferred return type of the synthetic constructor IS
2351 * the inferred type for the diamond operator.
2352 */
2353 private Symbol findDiamond(Env<AttrContext> env,
2354 Type site,
2355 List<Type> argtypes,
2356 List<Type> typeargtypes,
2357 boolean allowBoxing,
2358 boolean useVarargs) {
2359 Symbol bestSoFar = methodNotFound;
2360 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2361 e.scope != null;
2362 e = e.next()) {
2363 final Symbol sym = e.sym;
2364 //- System.out.println(" e " + e.sym);
2365 if (sym.kind == MTH &&
2366 (sym.flags_field & SYNTHETIC) == 0) {
2367 List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
2368 ((ForAll)sym.type).tvars :
2369 List.<Type>nil();
2370 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2371 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2372 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2373 @Override
2374 public Symbol baseSymbol() {
2375 return sym;
2376 }
2377 };
2378 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2379 newConstr,
2380 bestSoFar,
2381 allowBoxing,
2382 useVarargs,
2383 false);
2384 }
2385 }
2386 return bestSoFar;
2387 }
2391 /** Resolve operator.
2392 * @param pos The position to use for error reporting.
2393 * @param optag The tag of the operation tree.
2394 * @param env The environment current at the operation.
2395 * @param argtypes The types of the operands.
2396 */
2397 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2398 Env<AttrContext> env, List<Type> argtypes) {
2399 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2400 try {
2401 currentResolutionContext = new MethodResolutionContext();
2402 Name name = treeinfo.operatorName(optag);
2403 env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
2404 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2405 null, false, false, true);
2406 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2407 env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
2408 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2409 null, true, false, true);
2410 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2411 false, argtypes, null);
2412 }
2413 finally {
2414 currentResolutionContext = prevResolutionContext;
2415 }
2416 }
2418 /** Resolve operator.
2419 * @param pos The position to use for error reporting.
2420 * @param optag The tag of the operation tree.
2421 * @param env The environment current at the operation.
2422 * @param arg The type of the operand.
2423 */
2424 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2425 return resolveOperator(pos, optag, env, List.of(arg));
2426 }
2428 /** Resolve binary operator.
2429 * @param pos The position to use for error reporting.
2430 * @param optag The tag of the operation tree.
2431 * @param env The environment current at the operation.
2432 * @param left The types of the left operand.
2433 * @param right The types of the right operand.
2434 */
2435 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2436 JCTree.Tag optag,
2437 Env<AttrContext> env,
2438 Type left,
2439 Type right) {
2440 return resolveOperator(pos, optag, env, List.of(left, right));
2441 }
2443 /**
2444 * Resolution of member references is typically done as a single
2445 * overload resolution step, where the argument types A are inferred from
2446 * the target functional descriptor.
2447 *
2448 * If the member reference is a method reference with a type qualifier,
2449 * a two-step lookup process is performed. The first step uses the
2450 * expected argument list A, while the second step discards the first
2451 * type from A (which is treated as a receiver type).
2452 *
2453 * There are two cases in which inference is performed: (i) if the member
2454 * reference is a constructor reference and the qualifier type is raw - in
2455 * which case diamond inference is used to infer a parameterization for the
2456 * type qualifier; (ii) if the member reference is an unbound reference
2457 * where the type qualifier is raw - in that case, during the unbound lookup
2458 * the receiver argument type is used to infer an instantiation for the raw
2459 * qualifier type.
2460 *
2461 * When a multi-step resolution process is exploited, it is an error
2462 * if two candidates are found (ambiguity).
2463 *
2464 * This routine returns a pair (T,S), where S is the member reference symbol,
2465 * and T is the type of the class in which S is defined. This is necessary as
2466 * the type T might be dynamically inferred (i.e. if constructor reference
2467 * has a raw qualifier).
2468 */
2469 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
2470 Env<AttrContext> env,
2471 JCMemberReference referenceTree,
2472 Type site,
2473 Name name, List<Type> argtypes,
2474 List<Type> typeargtypes,
2475 boolean boxingAllowed) {
2476 MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
2478 ReferenceLookupHelper boundLookupHelper;
2479 if (!name.equals(names.init)) {
2480 //method reference
2481 boundLookupHelper =
2482 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2483 } else if (site.hasTag(ARRAY)) {
2484 //array constructor reference
2485 boundLookupHelper =
2486 new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2487 } else {
2488 //class constructor reference
2489 boundLookupHelper =
2490 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2491 }
2493 //step 1 - bound lookup
2494 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2495 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
2497 //step 2 - unbound lookup
2498 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
2499 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2500 Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
2502 //merge results
2503 Pair<Symbol, ReferenceLookupHelper> res;
2504 if (unboundSym.kind != MTH) {
2505 res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
2506 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2507 } else if (boundSym.kind == MTH) {
2508 res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
2509 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2510 } else {
2511 res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
2512 env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
2513 }
2515 return res;
2516 }
2518 /**
2519 * Helper for defining custom method-like lookup logic; a lookup helper
2520 * provides hooks for (i) the actual lookup logic and (ii) accessing the
2521 * lookup result (this step might result in compiler diagnostics to be generated)
2522 */
2523 abstract class LookupHelper {
2525 /** name of the symbol to lookup */
2526 Name name;
2528 /** location in which the lookup takes place */
2529 Type site;
2531 /** actual types used during the lookup */
2532 List<Type> argtypes;
2534 /** type arguments used during the lookup */
2535 List<Type> typeargtypes;
2537 /** Max overload resolution phase handled by this helper */
2538 MethodResolutionPhase maxPhase;
2540 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2541 this.name = name;
2542 this.site = site;
2543 this.argtypes = argtypes;
2544 this.typeargtypes = typeargtypes;
2545 this.maxPhase = maxPhase;
2546 }
2548 /**
2549 * Should lookup stop at given phase with given result
2550 */
2551 protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2552 return phase.ordinal() > maxPhase.ordinal() ||
2553 sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
2554 }
2556 /**
2557 * Search for a symbol under a given overload resolution phase - this method
2558 * is usually called several times, once per each overload resolution phase
2559 */
2560 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
2562 /**
2563 * Validate the result of the lookup
2564 */
2565 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
2566 }
2568 abstract class BasicLookupHelper extends LookupHelper {
2570 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
2571 super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
2572 }
2574 @Override
2575 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2576 if (sym.kind == AMBIGUOUS) {
2577 AmbiguityError a_err = (AmbiguityError)sym;
2578 sym = a_err.mergeAbstracts(site);
2579 }
2580 if (sym.kind >= AMBIGUOUS) {
2581 //if nothing is found return the 'first' error
2582 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
2583 }
2584 return sym;
2585 }
2586 }
2588 /**
2589 * Helper class for member reference lookup. A reference lookup helper
2590 * defines the basic logic for member reference lookup; a method gives
2591 * access to an 'unbound' helper used to perform an unbound member
2592 * reference lookup.
2593 */
2594 abstract class ReferenceLookupHelper extends LookupHelper {
2596 /** The member reference tree */
2597 JCMemberReference referenceTree;
2599 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2600 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2601 super(name, site, argtypes, typeargtypes, maxPhase);
2602 this.referenceTree = referenceTree;
2604 }
2606 /**
2607 * Returns an unbound version of this lookup helper. By default, this
2608 * method returns an dummy lookup helper.
2609 */
2610 ReferenceLookupHelper unboundLookup() {
2611 //dummy loopkup helper that always return 'methodNotFound'
2612 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
2613 @Override
2614 ReferenceLookupHelper unboundLookup() {
2615 return this;
2616 }
2617 @Override
2618 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2619 return methodNotFound;
2620 }
2621 @Override
2622 ReferenceKind referenceKind(Symbol sym) {
2623 Assert.error();
2624 return null;
2625 }
2626 };
2627 }
2629 /**
2630 * Get the kind of the member reference
2631 */
2632 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
2634 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2635 if (sym.kind == AMBIGUOUS) {
2636 AmbiguityError a_err = (AmbiguityError)sym;
2637 sym = a_err.mergeAbstracts(site);
2638 }
2639 //skip error reporting
2640 return sym;
2641 }
2642 }
2644 /**
2645 * Helper class for method reference lookup. The lookup logic is based
2646 * upon Resolve.findMethod; in certain cases, this helper class has a
2647 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
2648 * In such cases, non-static lookup results are thrown away.
2649 */
2650 class MethodReferenceLookupHelper extends ReferenceLookupHelper {
2652 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2653 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2654 super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2655 }
2657 protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
2658 return findMethod(env, site, name, argtypes, typeargtypes,
2659 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2660 }
2662 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2663 return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
2664 sym.kind != MTH ||
2665 sym.isStatic() ? sym : new StaticError(sym);
2666 }
2668 @Override
2669 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2670 return adjustLookupResult(env, lookupReferenceInternal(env, phase));
2671 }
2673 @Override
2674 ReferenceLookupHelper unboundLookup() {
2675 if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
2676 argtypes.nonEmpty() &&
2677 types.isSubtypeUnchecked(argtypes.head, site)) {
2678 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
2679 site, argtypes, typeargtypes, maxPhase);
2680 } else {
2681 return super.unboundLookup();
2682 }
2683 }
2685 @Override
2686 ReferenceKind referenceKind(Symbol sym) {
2687 if (sym.isStatic()) {
2688 return ReferenceKind.STATIC;
2689 } else {
2690 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
2691 return selName != null && selName == names._super ?
2692 ReferenceKind.SUPER :
2693 ReferenceKind.BOUND;
2694 }
2695 }
2696 }
2698 /**
2699 * Helper class for unbound method reference lookup. Essentially the same
2700 * as the basic method reference lookup helper; main difference is that static
2701 * lookup results are thrown away. If qualifier type is raw, an attempt to
2702 * infer a parameterized type is made using the first actual argument (that
2703 * would otherwise be ignored during the lookup).
2704 */
2705 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
2707 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2708 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2709 super(referenceTree, name,
2710 site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
2711 argtypes.tail, typeargtypes, maxPhase);
2712 }
2714 @Override
2715 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2716 return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
2717 }
2719 @Override
2720 ReferenceLookupHelper unboundLookup() {
2721 return this;
2722 }
2724 @Override
2725 ReferenceKind referenceKind(Symbol sym) {
2726 return ReferenceKind.UNBOUND;
2727 }
2728 }
2730 /**
2731 * Helper class for array constructor lookup; an array constructor lookup
2732 * is simulated by looking up a method that returns the array type specified
2733 * as qualifier, and that accepts a single int parameter (size of the array).
2734 */
2735 class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2737 ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2738 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2739 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2740 }
2742 @Override
2743 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2744 Scope sc = new Scope(syms.arrayClass);
2745 MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
2746 arrayConstr.type = new MethodType(List.of(syms.intType), site, List.<Type>nil(), syms.methodClass);
2747 sc.enter(arrayConstr);
2748 return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
2749 }
2751 @Override
2752 ReferenceKind referenceKind(Symbol sym) {
2753 return ReferenceKind.ARRAY_CTOR;
2754 }
2755 }
2757 /**
2758 * Helper class for constructor reference lookup. The lookup logic is based
2759 * upon either Resolve.findMethod or Resolve.findDiamond - depending on
2760 * whether the constructor reference needs diamond inference (this is the case
2761 * if the qualifier type is raw). A special erroneous symbol is returned
2762 * if the lookup returns the constructor of an inner class and there's no
2763 * enclosing instance in scope.
2764 */
2765 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2767 boolean needsInference;
2769 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2770 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2771 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2772 if (site.isRaw()) {
2773 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
2774 needsInference = true;
2775 }
2776 }
2778 @Override
2779 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2780 Symbol sym = needsInference ?
2781 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
2782 findMethod(env, site, name, argtypes, typeargtypes,
2783 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2784 return sym.kind != MTH ||
2785 site.getEnclosingType().hasTag(NONE) ||
2786 hasEnclosingInstance(env, site) ?
2787 sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
2788 @Override
2789 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2790 return diags.create(dkind, log.currentSource(), pos,
2791 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
2792 }
2793 };
2794 }
2796 @Override
2797 ReferenceKind referenceKind(Symbol sym) {
2798 return site.getEnclosingType().hasTag(NONE) ?
2799 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
2800 }
2801 }
2803 /**
2804 * Main overload resolution routine. On each overload resolution step, a
2805 * lookup helper class is used to perform the method/constructor lookup;
2806 * at the end of the lookup, the helper is used to validate the results
2807 * (this last step might trigger overload resolution diagnostics).
2808 */
2809 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
2810 return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
2811 }
2813 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
2814 MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
2815 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2816 try {
2817 Symbol bestSoFar = methodNotFound;
2818 currentResolutionContext = resolveContext;
2819 for (MethodResolutionPhase phase : methodResolutionSteps) {
2820 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
2821 lookupHelper.shouldStop(bestSoFar, phase)) break;
2822 MethodResolutionPhase prevPhase = currentResolutionContext.step;
2823 Symbol prevBest = bestSoFar;
2824 currentResolutionContext.step = phase;
2825 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
2826 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
2827 }
2828 return lookupHelper.access(env, pos, location, bestSoFar);
2829 } finally {
2830 currentResolutionContext = prevResolutionContext;
2831 }
2832 }
2834 /**
2835 * Resolve `c.name' where name == this or name == super.
2836 * @param pos The position to use for error reporting.
2837 * @param env The environment current at the expression.
2838 * @param c The qualifier.
2839 * @param name The identifier's name.
2840 */
2841 Symbol resolveSelf(DiagnosticPosition pos,
2842 Env<AttrContext> env,
2843 TypeSymbol c,
2844 Name name) {
2845 Env<AttrContext> env1 = env;
2846 boolean staticOnly = false;
2847 while (env1.outer != null) {
2848 if (isStatic(env1)) staticOnly = true;
2849 if (env1.enclClass.sym == c) {
2850 Symbol sym = env1.info.scope.lookup(name).sym;
2851 if (sym != null) {
2852 if (staticOnly) sym = new StaticError(sym);
2853 return accessBase(sym, pos, env.enclClass.sym.type,
2854 name, true);
2855 }
2856 }
2857 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2858 env1 = env1.outer;
2859 }
2860 if (allowDefaultMethods && c.isInterface() &&
2861 name == names._super && !isStatic(env) &&
2862 types.isDirectSuperInterface(c, env.enclClass.sym)) {
2863 //this might be a default super call if one of the superinterfaces is 'c'
2864 for (Type t : pruneInterfaces(env.enclClass.type)) {
2865 if (t.tsym == c) {
2866 env.info.defaultSuperCallSite = t;
2867 return new VarSymbol(0, names._super,
2868 types.asSuper(env.enclClass.type, c), env.enclClass.sym);
2869 }
2870 }
2871 //find a direct superinterface that is a subtype of 'c'
2872 for (Type i : types.interfaces(env.enclClass.type)) {
2873 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
2874 log.error(pos, "illegal.default.super.call", c,
2875 diags.fragment("redundant.supertype", c, i));
2876 return syms.errSymbol;
2877 }
2878 }
2879 Assert.error();
2880 }
2881 log.error(pos, "not.encl.class", c);
2882 return syms.errSymbol;
2883 }
2884 //where
2885 private List<Type> pruneInterfaces(Type t) {
2886 ListBuffer<Type> result = ListBuffer.lb();
2887 for (Type t1 : types.interfaces(t)) {
2888 boolean shouldAdd = true;
2889 for (Type t2 : types.interfaces(t)) {
2890 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
2891 shouldAdd = false;
2892 }
2893 }
2894 if (shouldAdd) {
2895 result.append(t1);
2896 }
2897 }
2898 return result.toList();
2899 }
2902 /**
2903 * Resolve `c.this' for an enclosing class c that contains the
2904 * named member.
2905 * @param pos The position to use for error reporting.
2906 * @param env The environment current at the expression.
2907 * @param member The member that must be contained in the result.
2908 */
2909 Symbol resolveSelfContaining(DiagnosticPosition pos,
2910 Env<AttrContext> env,
2911 Symbol member,
2912 boolean isSuperCall) {
2913 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
2914 if (sym == null) {
2915 log.error(pos, "encl.class.required", member);
2916 return syms.errSymbol;
2917 } else {
2918 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
2919 }
2920 }
2922 boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
2923 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
2924 return encl != null && encl.kind < ERRONEOUS;
2925 }
2927 private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
2928 Symbol member,
2929 boolean isSuperCall) {
2930 Name name = names._this;
2931 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2932 boolean staticOnly = false;
2933 if (env1 != null) {
2934 while (env1 != null && env1.outer != null) {
2935 if (isStatic(env1)) staticOnly = true;
2936 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2937 Symbol sym = env1.info.scope.lookup(name).sym;
2938 if (sym != null) {
2939 if (staticOnly) sym = new StaticError(sym);
2940 return sym;
2941 }
2942 }
2943 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2944 staticOnly = true;
2945 env1 = env1.outer;
2946 }
2947 }
2948 return null;
2949 }
2951 /**
2952 * Resolve an appropriate implicit this instance for t's container.
2953 * JLS 8.8.5.1 and 15.9.2
2954 */
2955 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2956 return resolveImplicitThis(pos, env, t, false);
2957 }
2959 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2960 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2961 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2962 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2963 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2964 log.error(pos, "cant.ref.before.ctor.called", "this");
2965 return thisType;
2966 }
2968 /* ***************************************************************************
2969 * ResolveError classes, indicating error situations when accessing symbols
2970 ****************************************************************************/
2972 //used by TransTypes when checking target type of synthetic cast
2973 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2974 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2975 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2976 }
2977 //where
2978 private void logResolveError(ResolveError error,
2979 DiagnosticPosition pos,
2980 Symbol location,
2981 Type site,
2982 Name name,
2983 List<Type> argtypes,
2984 List<Type> typeargtypes) {
2985 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2986 pos, location, site, name, argtypes, typeargtypes);
2987 if (d != null) {
2988 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2989 log.report(d);
2990 }
2991 }
2993 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2995 public Object methodArguments(List<Type> argtypes) {
2996 if (argtypes == null || argtypes.isEmpty()) {
2997 return noArgs;
2998 } else {
2999 ListBuffer<Object> diagArgs = ListBuffer.lb();
3000 for (Type t : argtypes) {
3001 if (t.hasTag(DEFERRED)) {
3002 diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3003 } else {
3004 diagArgs.append(t);
3005 }
3006 }
3007 return diagArgs;
3008 }
3009 }
3011 /**
3012 * Root class for resolution errors. Subclass of ResolveError
3013 * represent a different kinds of resolution error - as such they must
3014 * specify how they map into concrete compiler diagnostics.
3015 */
3016 abstract class ResolveError extends Symbol {
3018 /** The name of the kind of error, for debugging only. */
3019 final String debugName;
3021 ResolveError(int kind, String debugName) {
3022 super(kind, 0, null, null, null);
3023 this.debugName = debugName;
3024 }
3026 @Override
3027 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3028 throw new AssertionError();
3029 }
3031 @Override
3032 public String toString() {
3033 return debugName;
3034 }
3036 @Override
3037 public boolean exists() {
3038 return false;
3039 }
3041 /**
3042 * Create an external representation for this erroneous symbol to be
3043 * used during attribution - by default this returns the symbol of a
3044 * brand new error type which stores the original type found
3045 * during resolution.
3046 *
3047 * @param name the name used during resolution
3048 * @param location the location from which the symbol is accessed
3049 */
3050 protected Symbol access(Name name, TypeSymbol location) {
3051 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3052 }
3054 /**
3055 * Create a diagnostic representing this resolution error.
3056 *
3057 * @param dkind The kind of the diagnostic to be created (e.g error).
3058 * @param pos The position to be used for error reporting.
3059 * @param site The original type from where the selection took place.
3060 * @param name The name of the symbol to be resolved.
3061 * @param argtypes The invocation's value arguments,
3062 * if we looked for a method.
3063 * @param typeargtypes The invocation's type arguments,
3064 * if we looked for a method.
3065 */
3066 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3067 DiagnosticPosition pos,
3068 Symbol location,
3069 Type site,
3070 Name name,
3071 List<Type> argtypes,
3072 List<Type> typeargtypes);
3073 }
3075 /**
3076 * This class is the root class of all resolution errors caused by
3077 * an invalid symbol being found during resolution.
3078 */
3079 abstract class InvalidSymbolError extends ResolveError {
3081 /** The invalid symbol found during resolution */
3082 Symbol sym;
3084 InvalidSymbolError(int kind, Symbol sym, String debugName) {
3085 super(kind, debugName);
3086 this.sym = sym;
3087 }
3089 @Override
3090 public boolean exists() {
3091 return true;
3092 }
3094 @Override
3095 public String toString() {
3096 return super.toString() + " wrongSym=" + sym;
3097 }
3099 @Override
3100 public Symbol access(Name name, TypeSymbol location) {
3101 if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
3102 return types.createErrorType(name, location, sym.type).tsym;
3103 else
3104 return sym;
3105 }
3106 }
3108 /**
3109 * InvalidSymbolError error class indicating that a symbol matching a
3110 * given name does not exists in a given site.
3111 */
3112 class SymbolNotFoundError extends ResolveError {
3114 SymbolNotFoundError(int kind) {
3115 super(kind, "symbol not found error");
3116 }
3118 @Override
3119 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3120 DiagnosticPosition pos,
3121 Symbol location,
3122 Type site,
3123 Name name,
3124 List<Type> argtypes,
3125 List<Type> typeargtypes) {
3126 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3127 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3128 if (name == names.error)
3129 return null;
3131 if (syms.operatorNames.contains(name)) {
3132 boolean isUnaryOp = argtypes.size() == 1;
3133 String key = argtypes.size() == 1 ?
3134 "operator.cant.be.applied" :
3135 "operator.cant.be.applied.1";
3136 Type first = argtypes.head;
3137 Type second = !isUnaryOp ? argtypes.tail.head : null;
3138 return diags.create(dkind, log.currentSource(), pos,
3139 key, name, first, second);
3140 }
3141 boolean hasLocation = false;
3142 if (location == null) {
3143 location = site.tsym;
3144 }
3145 if (!location.name.isEmpty()) {
3146 if (location.kind == PCK && !site.tsym.exists()) {
3147 return diags.create(dkind, log.currentSource(), pos,
3148 "doesnt.exist", location);
3149 }
3150 hasLocation = !location.name.equals(names._this) &&
3151 !location.name.equals(names._super);
3152 }
3153 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
3154 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
3155 Name idname = isConstructor ? site.tsym.name : name;
3156 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3157 if (hasLocation) {
3158 return diags.create(dkind, log.currentSource(), pos,
3159 errKey, kindname, idname, //symbol kindname, name
3160 typeargtypes, args(argtypes), //type parameters and arguments (if any)
3161 getLocationDiag(location, site)); //location kindname, type
3162 }
3163 else {
3164 return diags.create(dkind, log.currentSource(), pos,
3165 errKey, kindname, idname, //symbol kindname, name
3166 typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3167 }
3168 }
3169 //where
3170 private Object args(List<Type> args) {
3171 return args.isEmpty() ? args : methodArguments(args);
3172 }
3174 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3175 String key = "cant.resolve";
3176 String suffix = hasLocation ? ".location" : "";
3177 switch (kindname) {
3178 case METHOD:
3179 case CONSTRUCTOR: {
3180 suffix += ".args";
3181 suffix += hasTypeArgs ? ".params" : "";
3182 }
3183 }
3184 return key + suffix;
3185 }
3186 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3187 if (location.kind == VAR) {
3188 return diags.fragment("location.1",
3189 kindName(location),
3190 location,
3191 location.type);
3192 } else {
3193 return diags.fragment("location",
3194 typeKindName(site),
3195 site,
3196 null);
3197 }
3198 }
3199 }
3201 /**
3202 * InvalidSymbolError error class indicating that a given symbol
3203 * (either a method, a constructor or an operand) is not applicable
3204 * given an actual arguments/type argument list.
3205 */
3206 class InapplicableSymbolError extends ResolveError {
3208 protected MethodResolutionContext resolveContext;
3210 InapplicableSymbolError(MethodResolutionContext context) {
3211 this(WRONG_MTH, "inapplicable symbol error", context);
3212 }
3214 protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
3215 super(kind, debugName);
3216 this.resolveContext = context;
3217 }
3219 @Override
3220 public String toString() {
3221 return super.toString();
3222 }
3224 @Override
3225 public boolean exists() {
3226 return true;
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 (name == names.error)
3238 return null;
3240 if (syms.operatorNames.contains(name)) {
3241 boolean isUnaryOp = argtypes.size() == 1;
3242 String key = argtypes.size() == 1 ?
3243 "operator.cant.be.applied" :
3244 "operator.cant.be.applied.1";
3245 Type first = argtypes.head;
3246 Type second = !isUnaryOp ? argtypes.tail.head : null;
3247 return diags.create(dkind, log.currentSource(), pos,
3248 key, name, first, second);
3249 }
3250 else {
3251 Candidate c = errCandidate();
3252 Symbol ws = c.sym.asMemberOf(site, types);
3253 return diags.create(dkind, log.currentSource(), pos,
3254 "cant.apply.symbol",
3255 kindName(ws),
3256 ws.name == names.init ? ws.owner.name : ws.name,
3257 methodArguments(ws.type.getParameterTypes()),
3258 methodArguments(argtypes),
3259 kindName(ws.owner),
3260 ws.owner.type,
3261 c.details);
3262 }
3263 }
3265 @Override
3266 public Symbol access(Name name, TypeSymbol location) {
3267 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3268 }
3270 private Candidate errCandidate() {
3271 Candidate bestSoFar = null;
3272 for (Candidate c : resolveContext.candidates) {
3273 if (c.isApplicable()) continue;
3274 bestSoFar = c;
3275 }
3276 Assert.checkNonNull(bestSoFar);
3277 return bestSoFar;
3278 }
3279 }
3281 /**
3282 * ResolveError error class indicating that a set of symbols
3283 * (either methods, constructors or operands) is not applicable
3284 * given an actual arguments/type argument list.
3285 */
3286 class InapplicableSymbolsError extends InapplicableSymbolError {
3288 InapplicableSymbolsError(MethodResolutionContext context) {
3289 super(WRONG_MTHS, "inapplicable symbols", context);
3290 }
3292 @Override
3293 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3294 DiagnosticPosition pos,
3295 Symbol location,
3296 Type site,
3297 Name name,
3298 List<Type> argtypes,
3299 List<Type> typeargtypes) {
3300 if (!resolveContext.candidates.isEmpty()) {
3301 JCDiagnostic err = diags.create(dkind,
3302 log.currentSource(),
3303 pos,
3304 "cant.apply.symbols",
3305 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
3306 name == names.init ? site.tsym.name : name,
3307 methodArguments(argtypes));
3308 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
3309 } else {
3310 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3311 location, site, name, argtypes, typeargtypes);
3312 }
3313 }
3315 //where
3316 List<JCDiagnostic> candidateDetails(Type site) {
3317 Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
3318 for (Candidate c : resolveContext.candidates) {
3319 if (c.isApplicable()) continue;
3320 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3321 Kinds.kindName(c.sym),
3322 c.sym.location(site, types),
3323 c.sym.asMemberOf(site, types),
3324 c.details);
3325 details.put(c.sym, detailDiag);
3326 }
3327 return List.from(details.values());
3328 }
3329 }
3331 /**
3332 * An InvalidSymbolError error class indicating that a symbol is not
3333 * accessible from a given site
3334 */
3335 class AccessError extends InvalidSymbolError {
3337 private Env<AttrContext> env;
3338 private Type site;
3340 AccessError(Symbol sym) {
3341 this(null, null, sym);
3342 }
3344 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3345 super(HIDDEN, sym, "access error");
3346 this.env = env;
3347 this.site = site;
3348 if (debugResolve)
3349 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3350 }
3352 @Override
3353 public boolean exists() {
3354 return false;
3355 }
3357 @Override
3358 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3359 DiagnosticPosition pos,
3360 Symbol location,
3361 Type site,
3362 Name name,
3363 List<Type> argtypes,
3364 List<Type> typeargtypes) {
3365 if (sym.owner.type.hasTag(ERROR))
3366 return null;
3368 if (sym.name == names.init && sym.owner != site.tsym) {
3369 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3370 pos, location, site, name, argtypes, typeargtypes);
3371 }
3372 else if ((sym.flags() & PUBLIC) != 0
3373 || (env != null && this.site != null
3374 && !isAccessible(env, this.site))) {
3375 return diags.create(dkind, log.currentSource(),
3376 pos, "not.def.access.class.intf.cant.access",
3377 sym, sym.location());
3378 }
3379 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3380 return diags.create(dkind, log.currentSource(),
3381 pos, "report.access", sym,
3382 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3383 sym.location());
3384 }
3385 else {
3386 return diags.create(dkind, log.currentSource(),
3387 pos, "not.def.public.cant.access", sym, sym.location());
3388 }
3389 }
3390 }
3392 /**
3393 * InvalidSymbolError error class indicating that an instance member
3394 * has erroneously been accessed from a static context.
3395 */
3396 class StaticError extends InvalidSymbolError {
3398 StaticError(Symbol sym) {
3399 super(STATICERR, sym, "static error");
3400 }
3402 @Override
3403 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3404 DiagnosticPosition pos,
3405 Symbol location,
3406 Type site,
3407 Name name,
3408 List<Type> argtypes,
3409 List<Type> typeargtypes) {
3410 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3411 ? types.erasure(sym.type).tsym
3412 : sym);
3413 return diags.create(dkind, log.currentSource(), pos,
3414 "non-static.cant.be.ref", kindName(sym), errSym);
3415 }
3416 }
3418 /**
3419 * InvalidSymbolError error class indicating that a pair of symbols
3420 * (either methods, constructors or operands) are ambiguous
3421 * given an actual arguments/type argument list.
3422 */
3423 class AmbiguityError extends ResolveError {
3425 /** The other maximally specific symbol */
3426 List<Symbol> ambiguousSyms = List.nil();
3428 @Override
3429 public boolean exists() {
3430 return true;
3431 }
3433 AmbiguityError(Symbol sym1, Symbol sym2) {
3434 super(AMBIGUOUS, "ambiguity error");
3435 ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3436 }
3438 private List<Symbol> flatten(Symbol sym) {
3439 if (sym.kind == AMBIGUOUS) {
3440 return ((AmbiguityError)sym).ambiguousSyms;
3441 } else {
3442 return List.of(sym);
3443 }
3444 }
3446 AmbiguityError addAmbiguousSymbol(Symbol s) {
3447 ambiguousSyms = ambiguousSyms.prepend(s);
3448 return this;
3449 }
3451 @Override
3452 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3453 DiagnosticPosition pos,
3454 Symbol location,
3455 Type site,
3456 Name name,
3457 List<Type> argtypes,
3458 List<Type> typeargtypes) {
3459 List<Symbol> diagSyms = ambiguousSyms.reverse();
3460 Symbol s1 = diagSyms.head;
3461 Symbol s2 = diagSyms.tail.head;
3462 Name sname = s1.name;
3463 if (sname == names.init) sname = s1.owner.name;
3464 return diags.create(dkind, log.currentSource(),
3465 pos, "ref.ambiguous", sname,
3466 kindName(s1),
3467 s1,
3468 s1.location(site, types),
3469 kindName(s2),
3470 s2,
3471 s2.location(site, types));
3472 }
3474 /**
3475 * If multiple applicable methods are found during overload and none of them
3476 * is more specific than the others, attempt to merge their signatures.
3477 */
3478 Symbol mergeAbstracts(Type site) {
3479 Symbol fst = ambiguousSyms.last();
3480 Symbol res = fst;
3481 for (Symbol s : ambiguousSyms.reverse()) {
3482 Type mt1 = types.memberType(site, res);
3483 Type mt2 = types.memberType(site, s);
3484 if ((s.flags() & ABSTRACT) == 0 ||
3485 !types.overrideEquivalent(mt1, mt2) ||
3486 !types.isSameTypes(fst.erasure(types).getParameterTypes(),
3487 s.erasure(types).getParameterTypes())) {
3488 //ambiguity cannot be resolved
3489 return this;
3490 } else {
3491 Type mst = mostSpecificReturnType(mt1, mt2);
3492 if (mst == null) {
3493 // Theoretically, this can't happen, but it is possible
3494 // due to error recovery or mixing incompatible class files
3495 return this;
3496 }
3497 Symbol mostSpecific = mst == mt1 ? res : s;
3498 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
3499 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
3500 res = new MethodSymbol(
3501 mostSpecific.flags(),
3502 mostSpecific.name,
3503 newSig,
3504 mostSpecific.owner);
3505 }
3506 }
3507 return res;
3508 }
3510 @Override
3511 protected Symbol access(Name name, TypeSymbol location) {
3512 Symbol firstAmbiguity = ambiguousSyms.last();
3513 return firstAmbiguity.kind == TYP ?
3514 types.createErrorType(name, location, firstAmbiguity.type).tsym :
3515 firstAmbiguity;
3516 }
3517 }
3519 enum MethodResolutionPhase {
3520 BASIC(false, false),
3521 BOX(true, false),
3522 VARARITY(true, true) {
3523 @Override
3524 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
3525 switch (sym.kind) {
3526 case WRONG_MTH:
3527 return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
3528 bestSoFar :
3529 sym;
3530 case ABSENT_MTH:
3531 return bestSoFar;
3532 default:
3533 return sym;
3534 }
3535 }
3536 };
3538 final boolean isBoxingRequired;
3539 final boolean isVarargsRequired;
3541 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
3542 this.isBoxingRequired = isBoxingRequired;
3543 this.isVarargsRequired = isVarargsRequired;
3544 }
3546 public boolean isBoxingRequired() {
3547 return isBoxingRequired;
3548 }
3550 public boolean isVarargsRequired() {
3551 return isVarargsRequired;
3552 }
3554 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
3555 return (varargsEnabled || !isVarargsRequired) &&
3556 (boxingEnabled || !isBoxingRequired);
3557 }
3559 public Symbol mergeResults(Symbol prev, Symbol sym) {
3560 return sym;
3561 }
3562 }
3564 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
3566 /**
3567 * A resolution context is used to keep track of intermediate results of
3568 * overload resolution, such as list of method that are not applicable
3569 * (used to generate more precise diagnostics) and so on. Resolution contexts
3570 * can be nested - this means that when each overload resolution routine should
3571 * work within the resolution context it created.
3572 */
3573 class MethodResolutionContext {
3575 private List<Candidate> candidates = List.nil();
3577 MethodResolutionPhase step = null;
3579 private boolean internalResolution = false;
3580 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
3582 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
3583 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
3584 candidates = candidates.append(c);
3585 }
3587 void addApplicableCandidate(Symbol sym, Type mtype) {
3588 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
3589 candidates = candidates.append(c);
3590 }
3592 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
3593 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
3594 }
3596 /**
3597 * This class represents an overload resolution candidate. There are two
3598 * kinds of candidates: applicable methods and inapplicable methods;
3599 * applicable methods have a pointer to the instantiated method type,
3600 * while inapplicable candidates contain further details about the
3601 * reason why the method has been considered inapplicable.
3602 */
3603 class Candidate {
3605 final MethodResolutionPhase step;
3606 final Symbol sym;
3607 final JCDiagnostic details;
3608 final Type mtype;
3610 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
3611 this.step = step;
3612 this.sym = sym;
3613 this.details = details;
3614 this.mtype = mtype;
3615 }
3617 @Override
3618 public boolean equals(Object o) {
3619 if (o instanceof Candidate) {
3620 Symbol s1 = this.sym;
3621 Symbol s2 = ((Candidate)o).sym;
3622 if ((s1 != s2 &&
3623 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
3624 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
3625 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
3626 return true;
3627 }
3628 return false;
3629 }
3631 boolean isApplicable() {
3632 return mtype != null;
3633 }
3634 }
3636 DeferredAttr.AttrMode attrMode() {
3637 return attrMode;
3638 }
3640 boolean internal() {
3641 return internalResolution;
3642 }
3643 }
3645 MethodResolutionContext currentResolutionContext = null;
3646 }