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