Fri, 12 Jul 2013 13:11:12 -0700
8020278: NPE in javadoc
Reviewed-by: mcimadamore, 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 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
588 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
589 step.isBoxingRequired(), step.isVarargsRequired(), warn);
590 }
591 finally {
592 currentResolutionContext = prevContext;
593 }
594 }
596 /** Same but returns null instead throwing a NoInstanceException
597 */
598 Type instantiate(Env<AttrContext> env,
599 Type site,
600 Symbol m,
601 ResultInfo resultInfo,
602 List<Type> argtypes,
603 List<Type> typeargtypes,
604 boolean allowBoxing,
605 boolean useVarargs,
606 Warner warn) {
607 try {
608 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
609 allowBoxing, useVarargs, warn);
610 } catch (InapplicableMethodException ex) {
611 return null;
612 }
613 }
615 /**
616 * This interface defines an entry point that should be used to perform a
617 * method check. A method check usually consist in determining as to whether
618 * a set of types (actuals) is compatible with another set of types (formals).
619 * Since the notion of compatibility can vary depending on the circumstances,
620 * this interfaces allows to easily add new pluggable method check routines.
621 */
622 interface MethodCheck {
623 /**
624 * Main method check routine. A method check usually consist in determining
625 * as to whether a set of types (actuals) is compatible with another set of
626 * types (formals). If an incompatibility is found, an unchecked exception
627 * is assumed to be thrown.
628 */
629 void argumentsAcceptable(Env<AttrContext> env,
630 DeferredAttrContext deferredAttrContext,
631 List<Type> argtypes,
632 List<Type> formals,
633 Warner warn);
635 /**
636 * Retrieve the method check object that will be used during a
637 * most specific check.
638 */
639 MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
640 }
642 /**
643 * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
644 */
645 enum MethodCheckDiag {
646 /**
647 * Actuals and formals differs in length.
648 */
649 ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
650 /**
651 * An actual is incompatible with a formal.
652 */
653 ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
654 /**
655 * An actual is incompatible with the varargs element type.
656 */
657 VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
658 /**
659 * The varargs element type is inaccessible.
660 */
661 INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
663 final String basicKey;
664 final String inferKey;
666 MethodCheckDiag(String basicKey, String inferKey) {
667 this.basicKey = basicKey;
668 this.inferKey = inferKey;
669 }
671 String regex() {
672 return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
673 }
674 }
676 /**
677 * Dummy method check object. All methods are deemed applicable, regardless
678 * of their formal parameter types.
679 */
680 MethodCheck nilMethodCheck = new MethodCheck() {
681 public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
682 //do nothing - method always applicable regardless of actuals
683 }
685 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
686 return this;
687 }
688 };
690 /**
691 * Base class for 'real' method checks. The class defines the logic for
692 * iterating through formals and actuals and provides and entry point
693 * that can be used by subclasses in order to define the actual check logic.
694 */
695 abstract class AbstractMethodCheck implements MethodCheck {
696 @Override
697 public void argumentsAcceptable(final Env<AttrContext> env,
698 DeferredAttrContext deferredAttrContext,
699 List<Type> argtypes,
700 List<Type> formals,
701 Warner warn) {
702 //should we expand formals?
703 boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
704 List<JCExpression> trees = TreeInfo.args(env.tree);
706 //inference context used during this method check
707 InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
709 Type varargsFormal = useVarargs ? formals.last() : null;
711 if (varargsFormal == null &&
712 argtypes.size() != formals.size()) {
713 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
714 }
716 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
717 DiagnosticPosition pos = trees != null ? trees.head : null;
718 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
719 argtypes = argtypes.tail;
720 formals = formals.tail;
721 trees = trees != null ? trees.tail : trees;
722 }
724 if (formals.head != varargsFormal) {
725 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
726 }
728 if (useVarargs) {
729 //note: if applicability check is triggered by most specific test,
730 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
731 final Type elt = types.elemtype(varargsFormal);
732 while (argtypes.nonEmpty()) {
733 DiagnosticPosition pos = trees != null ? trees.head : null;
734 checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
735 argtypes = argtypes.tail;
736 trees = trees != null ? trees.tail : trees;
737 }
738 }
739 }
741 /**
742 * Does the actual argument conforms to the corresponding formal?
743 */
744 abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
746 protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
747 boolean inferDiag = inferenceContext != infer.emptyContext;
748 InapplicableMethodException ex = inferDiag ?
749 infer.inferenceException : inapplicableMethodException;
750 if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
751 Object[] args2 = new Object[args.length + 1];
752 System.arraycopy(args, 0, args2, 1, args.length);
753 args2[0] = inferenceContext.inferenceVars();
754 args = args2;
755 }
756 String key = inferDiag ? diag.inferKey : diag.basicKey;
757 throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
758 }
760 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
761 return nilMethodCheck;
762 }
763 }
765 /**
766 * Arity-based method check. A method is applicable if the number of actuals
767 * supplied conforms to the method signature.
768 */
769 MethodCheck arityMethodCheck = new AbstractMethodCheck() {
770 @Override
771 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
772 //do nothing - actual always compatible to formals
773 }
774 };
776 /**
777 * Main method applicability routine. Given a list of actual types A,
778 * a list of formal types F, determines whether the types in A are
779 * compatible (by method invocation conversion) with the types in F.
780 *
781 * Since this routine is shared between overload resolution and method
782 * type-inference, a (possibly empty) inference context is used to convert
783 * formal types to the corresponding 'undet' form ahead of a compatibility
784 * check so that constraints can be propagated and collected.
785 *
786 * Moreover, if one or more types in A is a deferred type, this routine uses
787 * DeferredAttr in order to perform deferred attribution. If one or more actual
788 * deferred types are stuck, they are placed in a queue and revisited later
789 * after the remainder of the arguments have been seen. If this is not sufficient
790 * to 'unstuck' the argument, a cyclic inference error is called out.
791 *
792 * A method check handler (see above) is used in order to report errors.
793 */
794 MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
796 @Override
797 void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
798 ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
799 mresult.check(pos, actual);
800 }
802 @Override
803 public void argumentsAcceptable(final Env<AttrContext> env,
804 DeferredAttrContext deferredAttrContext,
805 List<Type> argtypes,
806 List<Type> formals,
807 Warner warn) {
808 super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
809 //should we expand formals?
810 if (deferredAttrContext.phase.isVarargsRequired()) {
811 //check varargs element type accessibility
812 varargsAccessible(env, types.elemtype(formals.last()),
813 deferredAttrContext.inferenceContext);
814 }
815 }
817 private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
818 if (inferenceContext.free(t)) {
819 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
820 @Override
821 public void typesInferred(InferenceContext inferenceContext) {
822 varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
823 }
824 });
825 } else {
826 if (!isAccessible(env, t)) {
827 Symbol location = env.enclClass.sym;
828 reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
829 }
830 }
831 }
833 private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
834 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
835 CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
836 MethodCheckDiag methodDiag = varargsCheck ?
837 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
839 @Override
840 public void report(DiagnosticPosition pos, JCDiagnostic details) {
841 reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
842 }
843 };
844 return new MethodResultInfo(to, checkContext);
845 }
847 @Override
848 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
849 return new MostSpecificCheck(strict, actuals);
850 }
851 };
853 /**
854 * Check context to be used during method applicability checks. A method check
855 * context might contain inference variables.
856 */
857 abstract class MethodCheckContext implements CheckContext {
859 boolean strict;
860 DeferredAttrContext deferredAttrContext;
861 Warner rsWarner;
863 public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
864 this.strict = strict;
865 this.deferredAttrContext = deferredAttrContext;
866 this.rsWarner = rsWarner;
867 }
869 public boolean compatible(Type found, Type req, Warner warn) {
870 return strict ?
871 types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
872 types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
873 }
875 public void report(DiagnosticPosition pos, JCDiagnostic details) {
876 throw inapplicableMethodException.setMessage(details);
877 }
879 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
880 return rsWarner;
881 }
883 public InferenceContext inferenceContext() {
884 return deferredAttrContext.inferenceContext;
885 }
887 public DeferredAttrContext deferredAttrContext() {
888 return deferredAttrContext;
889 }
890 }
892 /**
893 * ResultInfo class to be used during method applicability checks. Check
894 * for deferred types goes through special path.
895 */
896 class MethodResultInfo extends ResultInfo {
898 public MethodResultInfo(Type pt, CheckContext checkContext) {
899 attr.super(VAL, pt, checkContext);
900 }
902 @Override
903 protected Type check(DiagnosticPosition pos, Type found) {
904 if (found.hasTag(DEFERRED)) {
905 DeferredType dt = (DeferredType)found;
906 return dt.check(this);
907 } else {
908 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
909 }
910 }
912 @Override
913 protected MethodResultInfo dup(Type newPt) {
914 return new MethodResultInfo(newPt, checkContext);
915 }
917 @Override
918 protected ResultInfo dup(CheckContext newContext) {
919 return new MethodResultInfo(pt, newContext);
920 }
921 }
923 /**
924 * Most specific method applicability routine. Given a list of actual types A,
925 * a list of formal types F1, and a list of formal types F2, the routine determines
926 * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
927 * argument types A.
928 */
929 class MostSpecificCheck implements MethodCheck {
931 boolean strict;
932 List<Type> actuals;
934 MostSpecificCheck(boolean strict, List<Type> actuals) {
935 this.strict = strict;
936 this.actuals = actuals;
937 }
939 @Override
940 public void argumentsAcceptable(final Env<AttrContext> env,
941 DeferredAttrContext deferredAttrContext,
942 List<Type> formals1,
943 List<Type> formals2,
944 Warner warn) {
945 formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
946 while (formals2.nonEmpty()) {
947 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
948 mresult.check(null, formals1.head);
949 formals1 = formals1.tail;
950 formals2 = formals2.tail;
951 actuals = actuals.isEmpty() ? actuals : actuals.tail;
952 }
953 }
955 /**
956 * Create a method check context to be used during the most specific applicability check
957 */
958 ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
959 Warner rsWarner, Type actual) {
960 return attr.new ResultInfo(Kinds.VAL, to,
961 new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
962 }
964 /**
965 * Subclass of method check context class that implements most specific
966 * method conversion. If the actual type under analysis is a deferred type
967 * a full blown structural analysis is carried out.
968 */
969 class MostSpecificCheckContext extends MethodCheckContext {
971 Type actual;
973 public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
974 super(strict, deferredAttrContext, rsWarner);
975 this.actual = actual;
976 }
978 public boolean compatible(Type found, Type req, Warner warn) {
979 if (!allowStructuralMostSpecific || actual == null) {
980 return super.compatible(found, req, warn);
981 } else {
982 switch (actual.getTag()) {
983 case DEFERRED:
984 DeferredType dt = (DeferredType) actual;
985 DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
986 return (e == null || e.speculativeTree == deferredAttr.stuckTree)
987 ? false : mostSpecific(found, req, e.speculativeTree, warn);
988 default:
989 return standaloneMostSpecific(found, req, actual, warn);
990 }
991 }
992 }
994 private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
995 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
996 msc.scan(tree);
997 return msc.result;
998 }
1000 boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
1001 return (!t1.isPrimitive() && t2.isPrimitive())
1002 ? true : super.compatible(t1, t2, warn);
1003 }
1005 boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
1006 return (exprType.isPrimitive() == t1.isPrimitive()
1007 && exprType.isPrimitive() != t2.isPrimitive())
1008 ? true : super.compatible(t1, t2, warn);
1009 }
1011 /**
1012 * Structural checker for most specific.
1013 */
1014 class MostSpecificChecker extends DeferredAttr.PolyScanner {
1016 final Type t;
1017 final Type s;
1018 final Warner warn;
1019 boolean result;
1021 MostSpecificChecker(Type t, Type s, Warner warn) {
1022 this.t = t;
1023 this.s = s;
1024 this.warn = warn;
1025 result = true;
1026 }
1028 @Override
1029 void skip(JCTree tree) {
1030 result &= standaloneMostSpecific(t, s, tree.type, warn);
1031 }
1033 @Override
1034 public void visitConditional(JCConditional tree) {
1035 if (tree.polyKind == PolyKind.STANDALONE) {
1036 result &= standaloneMostSpecific(t, s, tree.type, warn);
1037 } else {
1038 super.visitConditional(tree);
1039 }
1040 }
1042 @Override
1043 public void visitApply(JCMethodInvocation tree) {
1044 result &= (tree.polyKind == PolyKind.STANDALONE)
1045 ? standaloneMostSpecific(t, s, tree.type, warn)
1046 : polyMostSpecific(t, s, warn);
1047 }
1049 @Override
1050 public void visitNewClass(JCNewClass tree) {
1051 result &= (tree.polyKind == PolyKind.STANDALONE)
1052 ? standaloneMostSpecific(t, s, tree.type, warn)
1053 : polyMostSpecific(t, s, warn);
1054 }
1056 @Override
1057 public void visitReference(JCMemberReference tree) {
1058 if (types.isFunctionalInterface(t.tsym) &&
1059 types.isFunctionalInterface(s.tsym) &&
1060 types.asSuper(t, s.tsym) == null &&
1061 types.asSuper(s, t.tsym) == null) {
1062 Type desc_t = types.findDescriptorType(t);
1063 Type desc_s = types.findDescriptorType(s);
1064 if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
1065 if (!desc_s.getReturnType().hasTag(VOID)) {
1066 //perform structural comparison
1067 Type ret_t = desc_t.getReturnType();
1068 Type ret_s = desc_s.getReturnType();
1069 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
1070 ? standaloneMostSpecific(ret_t, ret_s, tree.sym.type.getReturnType(), warn)
1071 : polyMostSpecific(ret_t, ret_s, warn));
1072 } else {
1073 return;
1074 }
1075 } else {
1076 result &= false;
1077 }
1078 } else {
1079 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
1080 }
1081 }
1083 @Override
1084 public void visitLambda(JCLambda tree) {
1085 if (types.isFunctionalInterface(t.tsym) &&
1086 types.isFunctionalInterface(s.tsym) &&
1087 types.asSuper(t, s.tsym) == null &&
1088 types.asSuper(s, t.tsym) == null) {
1089 Type desc_t = types.findDescriptorType(t);
1090 Type desc_s = types.findDescriptorType(s);
1091 if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
1092 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
1093 if (!desc_s.getReturnType().hasTag(VOID)) {
1094 //perform structural comparison
1095 Type ret_t = desc_t.getReturnType();
1096 Type ret_s = desc_s.getReturnType();
1097 scanLambdaBody(tree, ret_t, ret_s);
1098 } else {
1099 return;
1100 }
1101 } else {
1102 result &= false;
1103 }
1104 } else {
1105 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
1106 }
1107 }
1108 //where
1110 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
1111 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
1112 result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
1113 } else {
1114 DeferredAttr.LambdaReturnScanner lambdaScanner =
1115 new DeferredAttr.LambdaReturnScanner() {
1116 @Override
1117 public void visitReturn(JCReturn tree) {
1118 if (tree.expr != null) {
1119 result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
1120 }
1121 }
1122 };
1123 lambdaScanner.scan(lambda.body);
1124 }
1125 }
1126 }
1127 }
1129 public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
1130 Assert.error("Cannot get here!");
1131 return null;
1132 }
1133 }
1135 public static class InapplicableMethodException extends RuntimeException {
1136 private static final long serialVersionUID = 0;
1138 JCDiagnostic diagnostic;
1139 JCDiagnostic.Factory diags;
1141 InapplicableMethodException(JCDiagnostic.Factory diags) {
1142 this.diagnostic = null;
1143 this.diags = diags;
1144 }
1145 InapplicableMethodException setMessage() {
1146 return setMessage((JCDiagnostic)null);
1147 }
1148 InapplicableMethodException setMessage(String key) {
1149 return setMessage(key != null ? diags.fragment(key) : null);
1150 }
1151 InapplicableMethodException setMessage(String key, Object... args) {
1152 return setMessage(key != null ? diags.fragment(key, args) : null);
1153 }
1154 InapplicableMethodException setMessage(JCDiagnostic diag) {
1155 this.diagnostic = diag;
1156 return this;
1157 }
1159 public JCDiagnostic getDiagnostic() {
1160 return diagnostic;
1161 }
1162 }
1163 private final InapplicableMethodException inapplicableMethodException;
1165 /* ***************************************************************************
1166 * Symbol lookup
1167 * the following naming conventions for arguments are used
1168 *
1169 * env is the environment where the symbol was mentioned
1170 * site is the type of which the symbol is a member
1171 * name is the symbol's name
1172 * if no arguments are given
1173 * argtypes are the value arguments, if we search for a method
1174 *
1175 * If no symbol was found, a ResolveError detailing the problem is returned.
1176 ****************************************************************************/
1178 /** Find field. Synthetic fields are always skipped.
1179 * @param env The current environment.
1180 * @param site The original type from where the selection takes place.
1181 * @param name The name of the field.
1182 * @param c The class to search for the field. This is always
1183 * a superclass or implemented interface of site's class.
1184 */
1185 Symbol findField(Env<AttrContext> env,
1186 Type site,
1187 Name name,
1188 TypeSymbol c) {
1189 while (c.type.hasTag(TYPEVAR))
1190 c = c.type.getUpperBound().tsym;
1191 Symbol bestSoFar = varNotFound;
1192 Symbol sym;
1193 Scope.Entry e = c.members().lookup(name);
1194 while (e.scope != null) {
1195 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
1196 return isAccessible(env, site, e.sym)
1197 ? e.sym : new AccessError(env, site, e.sym);
1198 }
1199 e = e.next();
1200 }
1201 Type st = types.supertype(c.type);
1202 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
1203 sym = findField(env, site, name, st.tsym);
1204 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1205 }
1206 for (List<Type> l = types.interfaces(c.type);
1207 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1208 l = l.tail) {
1209 sym = findField(env, site, name, l.head.tsym);
1210 if (bestSoFar.exists() && sym.exists() &&
1211 sym.owner != bestSoFar.owner)
1212 bestSoFar = new AmbiguityError(bestSoFar, sym);
1213 else if (sym.kind < bestSoFar.kind)
1214 bestSoFar = sym;
1215 }
1216 return bestSoFar;
1217 }
1219 /** Resolve a field identifier, throw a fatal error if not found.
1220 * @param pos The position to use for error reporting.
1221 * @param env The environment current at the method invocation.
1222 * @param site The type of the qualifying expression, in which
1223 * identifier is searched.
1224 * @param name The identifier's name.
1225 */
1226 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
1227 Type site, Name name) {
1228 Symbol sym = findField(env, site, name, site.tsym);
1229 if (sym.kind == VAR) return (VarSymbol)sym;
1230 else throw new FatalError(
1231 diags.fragment("fatal.err.cant.locate.field",
1232 name));
1233 }
1235 /** Find unqualified variable or field with given name.
1236 * Synthetic fields always skipped.
1237 * @param env The current environment.
1238 * @param name The name of the variable or field.
1239 */
1240 Symbol findVar(Env<AttrContext> env, Name name) {
1241 Symbol bestSoFar = varNotFound;
1242 Symbol sym;
1243 Env<AttrContext> env1 = env;
1244 boolean staticOnly = false;
1245 while (env1.outer != null) {
1246 if (isStatic(env1)) staticOnly = true;
1247 Scope.Entry e = env1.info.scope.lookup(name);
1248 while (e.scope != null &&
1249 (e.sym.kind != VAR ||
1250 (e.sym.flags_field & SYNTHETIC) != 0))
1251 e = e.next();
1252 sym = (e.scope != null)
1253 ? e.sym
1254 : findField(
1255 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
1256 if (sym.exists()) {
1257 if (staticOnly &&
1258 sym.kind == VAR &&
1259 sym.owner.kind == TYP &&
1260 (sym.flags() & STATIC) == 0)
1261 return new StaticError(sym);
1262 else
1263 return sym;
1264 } else if (sym.kind < bestSoFar.kind) {
1265 bestSoFar = sym;
1266 }
1268 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1269 env1 = env1.outer;
1270 }
1272 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1273 if (sym.exists())
1274 return sym;
1275 if (bestSoFar.exists())
1276 return bestSoFar;
1278 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1279 for (; e.scope != null; e = e.next()) {
1280 sym = e.sym;
1281 Type origin = e.getOrigin().owner.type;
1282 if (sym.kind == VAR) {
1283 if (e.sym.owner.type != origin)
1284 sym = sym.clone(e.getOrigin().owner);
1285 return isAccessible(env, origin, sym)
1286 ? sym : new AccessError(env, origin, sym);
1287 }
1288 }
1290 Symbol origin = null;
1291 e = env.toplevel.starImportScope.lookup(name);
1292 for (; e.scope != null; e = e.next()) {
1293 sym = e.sym;
1294 if (sym.kind != VAR)
1295 continue;
1296 // invariant: sym.kind == VAR
1297 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
1298 return new AmbiguityError(bestSoFar, sym);
1299 else if (bestSoFar.kind >= VAR) {
1300 origin = e.getOrigin().owner;
1301 bestSoFar = isAccessible(env, origin.type, sym)
1302 ? sym : new AccessError(env, origin.type, sym);
1303 }
1304 }
1305 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1306 return bestSoFar.clone(origin);
1307 else
1308 return bestSoFar;
1309 }
1311 Warner noteWarner = new Warner();
1313 /** Select the best method for a call site among two choices.
1314 * @param env The current environment.
1315 * @param site The original type from where the
1316 * selection takes place.
1317 * @param argtypes The invocation's value arguments,
1318 * @param typeargtypes The invocation's type arguments,
1319 * @param sym Proposed new best match.
1320 * @param bestSoFar Previously found best match.
1321 * @param allowBoxing Allow boxing conversions of arguments.
1322 * @param useVarargs Box trailing arguments into an array for varargs.
1323 */
1324 @SuppressWarnings("fallthrough")
1325 Symbol selectBest(Env<AttrContext> env,
1326 Type site,
1327 List<Type> argtypes,
1328 List<Type> typeargtypes,
1329 Symbol sym,
1330 Symbol bestSoFar,
1331 boolean allowBoxing,
1332 boolean useVarargs,
1333 boolean operator) {
1334 if (sym.kind == ERR ||
1335 !sym.isInheritedIn(site.tsym, types)) {
1336 return bestSoFar;
1337 } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
1338 return bestSoFar.kind >= ERRONEOUS ?
1339 new BadVarargsMethod((ResolveError)bestSoFar) :
1340 bestSoFar;
1341 }
1342 Assert.check(sym.kind < AMBIGUOUS);
1343 try {
1344 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1345 allowBoxing, useVarargs, types.noWarnings);
1346 if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
1347 currentResolutionContext.addApplicableCandidate(sym, mt);
1348 } catch (InapplicableMethodException ex) {
1349 if (!operator)
1350 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1351 switch (bestSoFar.kind) {
1352 case ABSENT_MTH:
1353 return new InapplicableSymbolError(currentResolutionContext);
1354 case WRONG_MTH:
1355 if (operator) return bestSoFar;
1356 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1357 default:
1358 return bestSoFar;
1359 }
1360 }
1361 if (!isAccessible(env, site, sym)) {
1362 return (bestSoFar.kind == ABSENT_MTH)
1363 ? new AccessError(env, site, sym)
1364 : bestSoFar;
1365 }
1366 return (bestSoFar.kind > AMBIGUOUS)
1367 ? sym
1368 : mostSpecific(argtypes, sym, bestSoFar, env, site,
1369 allowBoxing && operator, useVarargs);
1370 }
1372 /* Return the most specific of the two methods for a call,
1373 * given that both are accessible and applicable.
1374 * @param m1 A new candidate for most specific.
1375 * @param m2 The previous most specific candidate.
1376 * @param env The current environment.
1377 * @param site The original type from where the selection
1378 * takes place.
1379 * @param allowBoxing Allow boxing conversions of arguments.
1380 * @param useVarargs Box trailing arguments into an array for varargs.
1381 */
1382 Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1383 Symbol m2,
1384 Env<AttrContext> env,
1385 final Type site,
1386 boolean allowBoxing,
1387 boolean useVarargs) {
1388 switch (m2.kind) {
1389 case MTH:
1390 if (m1 == m2) return m1;
1391 boolean m1SignatureMoreSpecific =
1392 signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1393 boolean m2SignatureMoreSpecific =
1394 signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1395 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1396 Type mt1 = types.memberType(site, m1);
1397 Type mt2 = types.memberType(site, m2);
1398 if (!types.overrideEquivalent(mt1, mt2))
1399 return ambiguityError(m1, m2);
1401 // same signature; select (a) the non-bridge method, or
1402 // (b) the one that overrides the other, or (c) the concrete
1403 // one, or (d) merge both abstract signatures
1404 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1405 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1407 // if one overrides or hides the other, use it
1408 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1409 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1410 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1411 ((m1.owner.flags_field & INTERFACE) == 0 ||
1412 (m2.owner.flags_field & INTERFACE) != 0) &&
1413 m1.overrides(m2, m1Owner, types, false))
1414 return m1;
1415 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1416 ((m2.owner.flags_field & INTERFACE) == 0 ||
1417 (m1.owner.flags_field & INTERFACE) != 0) &&
1418 m2.overrides(m1, m2Owner, types, false))
1419 return m2;
1420 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1421 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1422 if (m1Abstract && !m2Abstract) return m2;
1423 if (m2Abstract && !m1Abstract) return m1;
1424 // both abstract or both concrete
1425 return ambiguityError(m1, m2);
1426 }
1427 if (m1SignatureMoreSpecific) return m1;
1428 if (m2SignatureMoreSpecific) return m2;
1429 return ambiguityError(m1, m2);
1430 case AMBIGUOUS:
1431 //check if m1 is more specific than all ambiguous methods in m2
1432 AmbiguityError e = (AmbiguityError)m2;
1433 for (Symbol s : e.ambiguousSyms) {
1434 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
1435 return e.addAmbiguousSymbol(m1);
1436 }
1437 }
1438 return m1;
1439 default:
1440 throw new AssertionError();
1441 }
1442 }
1443 //where
1444 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1445 noteWarner.clear();
1446 int maxLength = Math.max(
1447 Math.max(m1.type.getParameterTypes().length(), actuals.length()),
1448 m2.type.getParameterTypes().length());
1449 MethodResolutionContext prevResolutionContext = currentResolutionContext;
1450 try {
1451 currentResolutionContext = new MethodResolutionContext();
1452 currentResolutionContext.step = prevResolutionContext.step;
1453 currentResolutionContext.methodCheck =
1454 prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
1455 Type mst = instantiate(env, site, m2, null,
1456 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
1457 allowBoxing, useVarargs, noteWarner);
1458 return mst != null &&
1459 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1460 } finally {
1461 currentResolutionContext = prevResolutionContext;
1462 }
1463 }
1464 private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
1465 if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
1466 Type varargsElem = types.elemtype(args.last());
1467 if (varargsElem == null) {
1468 Assert.error("Bad varargs = " + args.last() + " " + msym);
1469 }
1470 List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
1471 while (newArgs.length() < length) {
1472 newArgs = newArgs.append(newArgs.last());
1473 }
1474 return newArgs;
1475 } else {
1476 return args;
1477 }
1478 }
1479 //where
1480 Type mostSpecificReturnType(Type mt1, Type mt2) {
1481 Type rt1 = mt1.getReturnType();
1482 Type rt2 = mt2.getReturnType();
1484 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1485 //if both are generic methods, adjust return type ahead of subtyping check
1486 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1487 }
1488 //first use subtyping, then return type substitutability
1489 if (types.isSubtype(rt1, rt2)) {
1490 return mt1;
1491 } else if (types.isSubtype(rt2, rt1)) {
1492 return mt2;
1493 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1494 return mt1;
1495 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1496 return mt2;
1497 } else {
1498 return null;
1499 }
1500 }
1501 //where
1502 Symbol ambiguityError(Symbol m1, Symbol m2) {
1503 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1504 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1505 } else {
1506 return new AmbiguityError(m1, m2);
1507 }
1508 }
1510 Symbol findMethodInScope(Env<AttrContext> env,
1511 Type site,
1512 Name name,
1513 List<Type> argtypes,
1514 List<Type> typeargtypes,
1515 Scope sc,
1516 Symbol bestSoFar,
1517 boolean allowBoxing,
1518 boolean useVarargs,
1519 boolean operator,
1520 boolean abstractok) {
1521 for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
1522 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1523 bestSoFar, allowBoxing, useVarargs, operator);
1524 }
1525 return bestSoFar;
1526 }
1527 //where
1528 class LookupFilter implements Filter<Symbol> {
1530 boolean abstractOk;
1532 LookupFilter(boolean abstractOk) {
1533 this.abstractOk = abstractOk;
1534 }
1536 public boolean accepts(Symbol s) {
1537 long flags = s.flags();
1538 return s.kind == MTH &&
1539 (flags & SYNTHETIC) == 0 &&
1540 (abstractOk ||
1541 (flags & DEFAULT) != 0 ||
1542 (flags & ABSTRACT) == 0);
1543 }
1544 };
1546 /** Find best qualified method matching given name, type and value
1547 * arguments.
1548 * @param env The current environment.
1549 * @param site The original type from where the selection
1550 * takes place.
1551 * @param name The method's name.
1552 * @param argtypes The method's value arguments.
1553 * @param typeargtypes The method's type arguments
1554 * @param allowBoxing Allow boxing conversions of arguments.
1555 * @param useVarargs Box trailing arguments into an array for varargs.
1556 */
1557 Symbol findMethod(Env<AttrContext> env,
1558 Type site,
1559 Name name,
1560 List<Type> argtypes,
1561 List<Type> typeargtypes,
1562 boolean allowBoxing,
1563 boolean useVarargs,
1564 boolean operator) {
1565 Symbol bestSoFar = methodNotFound;
1566 bestSoFar = findMethod(env,
1567 site,
1568 name,
1569 argtypes,
1570 typeargtypes,
1571 site.tsym.type,
1572 bestSoFar,
1573 allowBoxing,
1574 useVarargs,
1575 operator);
1576 return bestSoFar;
1577 }
1578 // where
1579 private Symbol findMethod(Env<AttrContext> env,
1580 Type site,
1581 Name name,
1582 List<Type> argtypes,
1583 List<Type> typeargtypes,
1584 Type intype,
1585 Symbol bestSoFar,
1586 boolean allowBoxing,
1587 boolean useVarargs,
1588 boolean operator) {
1589 @SuppressWarnings({"unchecked","rawtypes"})
1590 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1591 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1592 for (TypeSymbol s : superclasses(intype)) {
1593 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1594 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1595 if (name == names.init) return bestSoFar;
1596 iphase = (iphase == null) ? null : iphase.update(s, this);
1597 if (iphase != null) {
1598 for (Type itype : types.interfaces(s.type)) {
1599 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1600 }
1601 }
1602 }
1604 Symbol concrete = bestSoFar.kind < ERR &&
1605 (bestSoFar.flags() & ABSTRACT) == 0 ?
1606 bestSoFar : methodNotFound;
1608 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1609 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
1610 //keep searching for abstract methods
1611 for (Type itype : itypes[iphase2.ordinal()]) {
1612 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1613 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1614 (itype.tsym.flags() & DEFAULT) == 0) continue;
1615 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1616 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1617 if (concrete != bestSoFar &&
1618 concrete.kind < ERR && bestSoFar.kind < ERR &&
1619 types.isSubSignature(concrete.type, bestSoFar.type)) {
1620 //this is an hack - as javac does not do full membership checks
1621 //most specific ends up comparing abstract methods that might have
1622 //been implemented by some concrete method in a subclass and,
1623 //because of raw override, it is possible for an abstract method
1624 //to be more specific than the concrete method - so we need
1625 //to explicitly call that out (see CR 6178365)
1626 bestSoFar = concrete;
1627 }
1628 }
1629 }
1630 return bestSoFar;
1631 }
1633 enum InterfaceLookupPhase {
1634 ABSTRACT_OK() {
1635 @Override
1636 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1637 //We should not look for abstract methods if receiver is a concrete class
1638 //(as concrete classes are expected to implement all abstracts coming
1639 //from superinterfaces)
1640 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1641 return this;
1642 } else if (rs.allowDefaultMethods) {
1643 return DEFAULT_OK;
1644 } else {
1645 return null;
1646 }
1647 }
1648 },
1649 DEFAULT_OK() {
1650 @Override
1651 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1652 return this;
1653 }
1654 };
1656 abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1657 }
1659 /**
1660 * Return an Iterable object to scan the superclasses of a given type.
1661 * It's crucial that the scan is done lazily, as we don't want to accidentally
1662 * access more supertypes than strictly needed (as this could trigger completion
1663 * errors if some of the not-needed supertypes are missing/ill-formed).
1664 */
1665 Iterable<TypeSymbol> superclasses(final Type intype) {
1666 return new Iterable<TypeSymbol>() {
1667 public Iterator<TypeSymbol> iterator() {
1668 return new Iterator<TypeSymbol>() {
1670 List<TypeSymbol> seen = List.nil();
1671 TypeSymbol currentSym = symbolFor(intype);
1672 TypeSymbol prevSym = null;
1674 public boolean hasNext() {
1675 if (currentSym == syms.noSymbol) {
1676 currentSym = symbolFor(types.supertype(prevSym.type));
1677 }
1678 return currentSym != null;
1679 }
1681 public TypeSymbol next() {
1682 prevSym = currentSym;
1683 currentSym = syms.noSymbol;
1684 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1685 return prevSym;
1686 }
1688 public void remove() {
1689 throw new UnsupportedOperationException();
1690 }
1692 TypeSymbol symbolFor(Type t) {
1693 if (!t.hasTag(CLASS) &&
1694 !t.hasTag(TYPEVAR)) {
1695 return null;
1696 }
1697 while (t.hasTag(TYPEVAR))
1698 t = t.getUpperBound();
1699 if (seen.contains(t.tsym)) {
1700 //degenerate case in which we have a circular
1701 //class hierarchy - because of ill-formed classfiles
1702 return null;
1703 }
1704 seen = seen.prepend(t.tsym);
1705 return t.tsym;
1706 }
1707 };
1708 }
1709 };
1710 }
1712 /** Find unqualified method matching given name, type and value arguments.
1713 * @param env The current environment.
1714 * @param name The method's name.
1715 * @param argtypes The method's value arguments.
1716 * @param typeargtypes The method's type arguments.
1717 * @param allowBoxing Allow boxing conversions of arguments.
1718 * @param useVarargs Box trailing arguments into an array for varargs.
1719 */
1720 Symbol findFun(Env<AttrContext> env, Name name,
1721 List<Type> argtypes, List<Type> typeargtypes,
1722 boolean allowBoxing, boolean useVarargs) {
1723 Symbol bestSoFar = methodNotFound;
1724 Symbol sym;
1725 Env<AttrContext> env1 = env;
1726 boolean staticOnly = false;
1727 while (env1.outer != null) {
1728 if (isStatic(env1)) staticOnly = true;
1729 sym = findMethod(
1730 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1731 allowBoxing, useVarargs, false);
1732 if (sym.exists()) {
1733 if (staticOnly &&
1734 sym.kind == MTH &&
1735 sym.owner.kind == TYP &&
1736 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1737 else return sym;
1738 } else if (sym.kind < bestSoFar.kind) {
1739 bestSoFar = sym;
1740 }
1741 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1742 env1 = env1.outer;
1743 }
1745 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1746 typeargtypes, allowBoxing, useVarargs, false);
1747 if (sym.exists())
1748 return sym;
1750 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1751 for (; e.scope != null; e = e.next()) {
1752 sym = e.sym;
1753 Type origin = e.getOrigin().owner.type;
1754 if (sym.kind == MTH) {
1755 if (e.sym.owner.type != origin)
1756 sym = sym.clone(e.getOrigin().owner);
1757 if (!isAccessible(env, origin, sym))
1758 sym = new AccessError(env, origin, sym);
1759 bestSoFar = selectBest(env, origin,
1760 argtypes, typeargtypes,
1761 sym, bestSoFar,
1762 allowBoxing, useVarargs, false);
1763 }
1764 }
1765 if (bestSoFar.exists())
1766 return bestSoFar;
1768 e = env.toplevel.starImportScope.lookup(name);
1769 for (; e.scope != null; e = e.next()) {
1770 sym = e.sym;
1771 Type origin = e.getOrigin().owner.type;
1772 if (sym.kind == MTH) {
1773 if (e.sym.owner.type != origin)
1774 sym = sym.clone(e.getOrigin().owner);
1775 if (!isAccessible(env, origin, sym))
1776 sym = new AccessError(env, origin, sym);
1777 bestSoFar = selectBest(env, origin,
1778 argtypes, typeargtypes,
1779 sym, bestSoFar,
1780 allowBoxing, useVarargs, false);
1781 }
1782 }
1783 return bestSoFar;
1784 }
1786 /** Load toplevel or member class with given fully qualified name and
1787 * verify that it is accessible.
1788 * @param env The current environment.
1789 * @param name The fully qualified name of the class to be loaded.
1790 */
1791 Symbol loadClass(Env<AttrContext> env, Name name) {
1792 try {
1793 ClassSymbol c = reader.loadClass(name);
1794 return isAccessible(env, c) ? c : new AccessError(c);
1795 } catch (ClassReader.BadClassFile err) {
1796 throw err;
1797 } catch (CompletionFailure ex) {
1798 return typeNotFound;
1799 }
1800 }
1802 /** Find qualified member type.
1803 * @param env The current environment.
1804 * @param site The original type from where the selection takes
1805 * place.
1806 * @param name The type's name.
1807 * @param c The class to search for the member type. This is
1808 * always a superclass or implemented interface of
1809 * site's class.
1810 */
1811 Symbol findMemberType(Env<AttrContext> env,
1812 Type site,
1813 Name name,
1814 TypeSymbol c) {
1815 Symbol bestSoFar = typeNotFound;
1816 Symbol sym;
1817 Scope.Entry e = c.members().lookup(name);
1818 while (e.scope != null) {
1819 if (e.sym.kind == TYP) {
1820 return isAccessible(env, site, e.sym)
1821 ? e.sym
1822 : new AccessError(env, site, e.sym);
1823 }
1824 e = e.next();
1825 }
1826 Type st = types.supertype(c.type);
1827 if (st != null && st.hasTag(CLASS)) {
1828 sym = findMemberType(env, site, name, st.tsym);
1829 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1830 }
1831 for (List<Type> l = types.interfaces(c.type);
1832 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1833 l = l.tail) {
1834 sym = findMemberType(env, site, name, l.head.tsym);
1835 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1836 sym.owner != bestSoFar.owner)
1837 bestSoFar = new AmbiguityError(bestSoFar, sym);
1838 else if (sym.kind < bestSoFar.kind)
1839 bestSoFar = sym;
1840 }
1841 return bestSoFar;
1842 }
1844 /** Find a global type in given scope and load corresponding class.
1845 * @param env The current environment.
1846 * @param scope The scope in which to look for the type.
1847 * @param name The type's name.
1848 */
1849 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1850 Symbol bestSoFar = typeNotFound;
1851 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1852 Symbol sym = loadClass(env, e.sym.flatName());
1853 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1854 bestSoFar != sym)
1855 return new AmbiguityError(bestSoFar, sym);
1856 else if (sym.kind < bestSoFar.kind)
1857 bestSoFar = sym;
1858 }
1859 return bestSoFar;
1860 }
1862 /** Find an unqualified type symbol.
1863 * @param env The current environment.
1864 * @param name The type's name.
1865 */
1866 Symbol findType(Env<AttrContext> env, Name name) {
1867 Symbol bestSoFar = typeNotFound;
1868 Symbol sym;
1869 boolean staticOnly = false;
1870 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1871 if (isStatic(env1)) staticOnly = true;
1872 for (Scope.Entry e = env1.info.scope.lookup(name);
1873 e.scope != null;
1874 e = e.next()) {
1875 if (e.sym.kind == TYP) {
1876 if (staticOnly &&
1877 e.sym.type.hasTag(TYPEVAR) &&
1878 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1879 return e.sym;
1880 }
1881 }
1883 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1884 env1.enclClass.sym);
1885 if (staticOnly && sym.kind == TYP &&
1886 sym.type.hasTag(CLASS) &&
1887 sym.type.getEnclosingType().hasTag(CLASS) &&
1888 env1.enclClass.sym.type.isParameterized() &&
1889 sym.type.getEnclosingType().isParameterized())
1890 return new StaticError(sym);
1891 else if (sym.exists()) return sym;
1892 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1894 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1895 if ((encl.sym.flags() & STATIC) != 0)
1896 staticOnly = true;
1897 }
1899 if (!env.tree.hasTag(IMPORT)) {
1900 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1901 if (sym.exists()) return sym;
1902 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1904 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1905 if (sym.exists()) return sym;
1906 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1908 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1909 if (sym.exists()) return sym;
1910 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1911 }
1913 return bestSoFar;
1914 }
1916 /** Find an unqualified identifier which matches a specified kind set.
1917 * @param env The current environment.
1918 * @param name The identifier's name.
1919 * @param kind Indicates the possible symbol kinds
1920 * (a subset of VAL, TYP, PCK).
1921 */
1922 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1923 Symbol bestSoFar = typeNotFound;
1924 Symbol sym;
1926 if ((kind & VAR) != 0) {
1927 sym = findVar(env, name);
1928 if (sym.exists()) return sym;
1929 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1930 }
1932 if ((kind & TYP) != 0) {
1933 sym = findType(env, name);
1934 if (sym.kind==TYP) {
1935 reportDependence(env.enclClass.sym, sym);
1936 }
1937 if (sym.exists()) return sym;
1938 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1939 }
1941 if ((kind & PCK) != 0) return reader.enterPackage(name);
1942 else return bestSoFar;
1943 }
1945 /** Report dependencies.
1946 * @param from The enclosing class sym
1947 * @param to The found identifier that the class depends on.
1948 */
1949 public void reportDependence(Symbol from, Symbol to) {
1950 // Override if you want to collect the reported dependencies.
1951 }
1953 /** Find an identifier in a package which matches a specified kind set.
1954 * @param env The current environment.
1955 * @param name The identifier's name.
1956 * @param kind Indicates the possible symbol kinds
1957 * (a nonempty subset of TYP, PCK).
1958 */
1959 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1960 Name name, int kind) {
1961 Name fullname = TypeSymbol.formFullName(name, pck);
1962 Symbol bestSoFar = typeNotFound;
1963 PackageSymbol pack = null;
1964 if ((kind & PCK) != 0) {
1965 pack = reader.enterPackage(fullname);
1966 if (pack.exists()) return pack;
1967 }
1968 if ((kind & TYP) != 0) {
1969 Symbol sym = loadClass(env, fullname);
1970 if (sym.exists()) {
1971 // don't allow programs to use flatnames
1972 if (name == sym.name) return sym;
1973 }
1974 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1975 }
1976 return (pack != null) ? pack : bestSoFar;
1977 }
1979 /** Find an identifier among the members of a given type `site'.
1980 * @param env The current environment.
1981 * @param site The type containing the symbol to be found.
1982 * @param name The identifier's name.
1983 * @param kind Indicates the possible symbol kinds
1984 * (a subset of VAL, TYP).
1985 */
1986 Symbol findIdentInType(Env<AttrContext> env, Type site,
1987 Name name, int kind) {
1988 Symbol bestSoFar = typeNotFound;
1989 Symbol sym;
1990 if ((kind & VAR) != 0) {
1991 sym = findField(env, site, name, site.tsym);
1992 if (sym.exists()) return sym;
1993 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1994 }
1996 if ((kind & TYP) != 0) {
1997 sym = findMemberType(env, site, name, site.tsym);
1998 if (sym.exists()) return sym;
1999 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
2000 }
2001 return bestSoFar;
2002 }
2004 /* ***************************************************************************
2005 * Access checking
2006 * The following methods convert ResolveErrors to ErrorSymbols, issuing
2007 * an error message in the process
2008 ****************************************************************************/
2010 /** If `sym' is a bad symbol: report error and return errSymbol
2011 * else pass through unchanged,
2012 * additional arguments duplicate what has been used in trying to find the
2013 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
2014 * expect misses to happen frequently.
2015 *
2016 * @param sym The symbol that was found, or a ResolveError.
2017 * @param pos The position to use for error reporting.
2018 * @param location The symbol the served as a context for this lookup
2019 * @param site The original type from where the selection took place.
2020 * @param name The symbol's name.
2021 * @param qualified Did we get here through a qualified expression resolution?
2022 * @param argtypes The invocation's value arguments,
2023 * if we looked for a method.
2024 * @param typeargtypes The invocation's type arguments,
2025 * if we looked for a method.
2026 * @param logResolveHelper helper class used to log resolve errors
2027 */
2028 Symbol accessInternal(Symbol sym,
2029 DiagnosticPosition pos,
2030 Symbol location,
2031 Type site,
2032 Name name,
2033 boolean qualified,
2034 List<Type> argtypes,
2035 List<Type> typeargtypes,
2036 LogResolveHelper logResolveHelper) {
2037 if (sym.kind >= AMBIGUOUS) {
2038 ResolveError errSym = (ResolveError)sym;
2039 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
2040 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
2041 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
2042 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
2043 }
2044 }
2045 return sym;
2046 }
2048 /**
2049 * Variant of the generalized access routine, to be used for generating method
2050 * resolution diagnostics
2051 */
2052 Symbol accessMethod(Symbol sym,
2053 DiagnosticPosition pos,
2054 Symbol location,
2055 Type site,
2056 Name name,
2057 boolean qualified,
2058 List<Type> argtypes,
2059 List<Type> typeargtypes) {
2060 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
2061 }
2063 /** Same as original accessMethod(), but without location.
2064 */
2065 Symbol accessMethod(Symbol sym,
2066 DiagnosticPosition pos,
2067 Type site,
2068 Name name,
2069 boolean qualified,
2070 List<Type> argtypes,
2071 List<Type> typeargtypes) {
2072 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
2073 }
2075 /**
2076 * Variant of the generalized access routine, to be used for generating variable,
2077 * type resolution diagnostics
2078 */
2079 Symbol accessBase(Symbol sym,
2080 DiagnosticPosition pos,
2081 Symbol location,
2082 Type site,
2083 Name name,
2084 boolean qualified) {
2085 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
2086 }
2088 /** Same as original accessBase(), but without location.
2089 */
2090 Symbol accessBase(Symbol sym,
2091 DiagnosticPosition pos,
2092 Type site,
2093 Name name,
2094 boolean qualified) {
2095 return accessBase(sym, pos, site.tsym, site, name, qualified);
2096 }
2098 interface LogResolveHelper {
2099 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2100 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2101 }
2103 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2104 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2105 return !site.isErroneous();
2106 }
2107 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2108 return argtypes;
2109 }
2110 };
2112 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2113 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2114 return !site.isErroneous() &&
2115 !Type.isErroneous(argtypes) &&
2116 (typeargtypes == null || !Type.isErroneous(typeargtypes));
2117 }
2118 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2119 return (syms.operatorNames.contains(name)) ?
2120 argtypes :
2121 Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
2122 }
2124 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2126 public ResolveDeferredRecoveryMap(Symbol msym) {
2127 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
2128 }
2130 @Override
2131 protected Type typeOf(DeferredType dt) {
2132 Type res = super.typeOf(dt);
2133 if (!res.isErroneous()) {
2134 switch (TreeInfo.skipParens(dt.tree).getTag()) {
2135 case LAMBDA:
2136 case REFERENCE:
2137 return dt;
2138 case CONDEXPR:
2139 return res == Type.recoveryType ?
2140 dt : res;
2141 }
2142 }
2143 return res;
2144 }
2145 }
2146 };
2148 /** Check that sym is not an abstract method.
2149 */
2150 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2151 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2152 log.error(pos, "abstract.cant.be.accessed.directly",
2153 kindName(sym), sym, sym.location());
2154 }
2156 /* ***************************************************************************
2157 * Debugging
2158 ****************************************************************************/
2160 /** print all scopes starting with scope s and proceeding outwards.
2161 * used for debugging.
2162 */
2163 public void printscopes(Scope s) {
2164 while (s != null) {
2165 if (s.owner != null)
2166 System.err.print(s.owner + ": ");
2167 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
2168 if ((e.sym.flags() & ABSTRACT) != 0)
2169 System.err.print("abstract ");
2170 System.err.print(e.sym + " ");
2171 }
2172 System.err.println();
2173 s = s.next;
2174 }
2175 }
2177 void printscopes(Env<AttrContext> env) {
2178 while (env.outer != null) {
2179 System.err.println("------------------------------");
2180 printscopes(env.info.scope);
2181 env = env.outer;
2182 }
2183 }
2185 public void printscopes(Type t) {
2186 while (t.hasTag(CLASS)) {
2187 printscopes(t.tsym.members());
2188 t = types.supertype(t);
2189 }
2190 }
2192 /* ***************************************************************************
2193 * Name resolution
2194 * Naming conventions are as for symbol lookup
2195 * Unlike the find... methods these methods will report access errors
2196 ****************************************************************************/
2198 /** Resolve an unqualified (non-method) identifier.
2199 * @param pos The position to use for error reporting.
2200 * @param env The environment current at the identifier use.
2201 * @param name The identifier's name.
2202 * @param kind The set of admissible symbol kinds for the identifier.
2203 */
2204 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2205 Name name, int kind) {
2206 return accessBase(
2207 findIdent(env, name, kind),
2208 pos, env.enclClass.sym.type, name, false);
2209 }
2211 /** Resolve an unqualified method identifier.
2212 * @param pos The position to use for error reporting.
2213 * @param env The environment current at the method invocation.
2214 * @param name The identifier's name.
2215 * @param argtypes The types of the invocation's value arguments.
2216 * @param typeargtypes The types of the invocation's type arguments.
2217 */
2218 Symbol resolveMethod(DiagnosticPosition pos,
2219 Env<AttrContext> env,
2220 Name name,
2221 List<Type> argtypes,
2222 List<Type> typeargtypes) {
2223 return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
2224 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2225 @Override
2226 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2227 return findFun(env, name, argtypes, typeargtypes,
2228 phase.isBoxingRequired(),
2229 phase.isVarargsRequired());
2230 }});
2231 }
2233 /** Resolve a qualified method identifier
2234 * @param pos The position to use for error reporting.
2235 * @param env The environment current at the method invocation.
2236 * @param site The type of the qualifying expression, in which
2237 * identifier is searched.
2238 * @param name The identifier's name.
2239 * @param argtypes The types of the invocation's value arguments.
2240 * @param typeargtypes The types of the invocation's type arguments.
2241 */
2242 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2243 Type site, Name name, List<Type> argtypes,
2244 List<Type> typeargtypes) {
2245 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2246 }
2247 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2248 Symbol location, Type site, Name name, List<Type> argtypes,
2249 List<Type> typeargtypes) {
2250 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2251 }
2252 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2253 DiagnosticPosition pos, Env<AttrContext> env,
2254 Symbol location, Type site, Name name, List<Type> argtypes,
2255 List<Type> typeargtypes) {
2256 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2257 @Override
2258 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2259 return findMethod(env, site, name, argtypes, typeargtypes,
2260 phase.isBoxingRequired(),
2261 phase.isVarargsRequired(), false);
2262 }
2263 @Override
2264 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2265 if (sym.kind >= AMBIGUOUS) {
2266 sym = super.access(env, pos, location, sym);
2267 } else if (allowMethodHandles) {
2268 MethodSymbol msym = (MethodSymbol)sym;
2269 if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
2270 return findPolymorphicSignatureInstance(env, sym, argtypes);
2271 }
2272 }
2273 return sym;
2274 }
2275 });
2276 }
2278 /** Find or create an implicit method of exactly the given type (after erasure).
2279 * Searches in a side table, not the main scope of the site.
2280 * This emulates the lookup process required by JSR 292 in JVM.
2281 * @param env Attribution environment
2282 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
2283 * @param argtypes The required argument types
2284 */
2285 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2286 final Symbol spMethod,
2287 List<Type> argtypes) {
2288 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2289 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2290 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
2291 if (types.isSameType(mtype, sym.type)) {
2292 return sym;
2293 }
2294 }
2296 // create the desired method
2297 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2298 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2299 @Override
2300 public Symbol baseSymbol() {
2301 return spMethod;
2302 }
2303 };
2304 polymorphicSignatureScope.enter(msym);
2305 return msym;
2306 }
2308 /** Resolve a qualified method identifier, throw a fatal error if not
2309 * found.
2310 * @param pos The position to use for error reporting.
2311 * @param env The environment current at the method invocation.
2312 * @param site The type of the qualifying expression, in which
2313 * identifier is searched.
2314 * @param name The identifier's name.
2315 * @param argtypes The types of the invocation's value arguments.
2316 * @param typeargtypes The types of the invocation's type arguments.
2317 */
2318 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2319 Type site, Name name,
2320 List<Type> argtypes,
2321 List<Type> typeargtypes) {
2322 MethodResolutionContext resolveContext = new MethodResolutionContext();
2323 resolveContext.internalResolution = true;
2324 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2325 site, name, argtypes, typeargtypes);
2326 if (sym.kind == MTH) return (MethodSymbol)sym;
2327 else throw new FatalError(
2328 diags.fragment("fatal.err.cant.locate.meth",
2329 name));
2330 }
2332 /** Resolve constructor.
2333 * @param pos The position to use for error reporting.
2334 * @param env The environment current at the constructor invocation.
2335 * @param site The type of class for which a constructor is searched.
2336 * @param argtypes The types of the constructor invocation's value
2337 * arguments.
2338 * @param typeargtypes The types of the constructor invocation's type
2339 * arguments.
2340 */
2341 Symbol resolveConstructor(DiagnosticPosition pos,
2342 Env<AttrContext> env,
2343 Type site,
2344 List<Type> argtypes,
2345 List<Type> typeargtypes) {
2346 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2347 }
2349 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2350 final DiagnosticPosition pos,
2351 Env<AttrContext> env,
2352 Type site,
2353 List<Type> argtypes,
2354 List<Type> typeargtypes) {
2355 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2356 @Override
2357 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2358 return findConstructor(pos, env, site, argtypes, typeargtypes,
2359 phase.isBoxingRequired(),
2360 phase.isVarargsRequired());
2361 }
2362 });
2363 }
2365 /** Resolve a constructor, throw a fatal error if not 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 to be constructed.
2369 * @param argtypes The types of the invocation's value arguments.
2370 * @param typeargtypes The types of the invocation's type arguments.
2371 */
2372 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2373 Type site,
2374 List<Type> argtypes,
2375 List<Type> typeargtypes) {
2376 MethodResolutionContext resolveContext = new MethodResolutionContext();
2377 resolveContext.internalResolution = true;
2378 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2379 if (sym.kind == MTH) return (MethodSymbol)sym;
2380 else throw new FatalError(
2381 diags.fragment("fatal.err.cant.locate.ctor", site));
2382 }
2384 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2385 Type site, List<Type> argtypes,
2386 List<Type> typeargtypes,
2387 boolean allowBoxing,
2388 boolean useVarargs) {
2389 Symbol sym = findMethod(env, site,
2390 names.init, argtypes,
2391 typeargtypes, allowBoxing,
2392 useVarargs, false);
2393 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2394 return sym;
2395 }
2397 /** Resolve constructor using diamond inference.
2398 * @param pos The position to use for error reporting.
2399 * @param env The environment current at the constructor invocation.
2400 * @param site The type of class for which a constructor is searched.
2401 * The scope of this class has been touched in attribution.
2402 * @param argtypes The types of the constructor invocation's value
2403 * arguments.
2404 * @param typeargtypes The types of the constructor invocation's type
2405 * arguments.
2406 */
2407 Symbol resolveDiamond(DiagnosticPosition pos,
2408 Env<AttrContext> env,
2409 Type site,
2410 List<Type> argtypes,
2411 List<Type> typeargtypes) {
2412 return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2413 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2414 @Override
2415 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2416 return findDiamond(env, site, argtypes, typeargtypes,
2417 phase.isBoxingRequired(),
2418 phase.isVarargsRequired());
2419 }
2420 @Override
2421 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2422 if (sym.kind >= AMBIGUOUS) {
2423 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2424 ((InapplicableSymbolError)sym).errCandidate().details :
2425 null;
2426 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2427 @Override
2428 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2429 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2430 String key = details == null ?
2431 "cant.apply.diamond" :
2432 "cant.apply.diamond.1";
2433 return diags.create(dkind, log.currentSource(), pos, key,
2434 diags.fragment("diamond", site.tsym), details);
2435 }
2436 };
2437 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2438 env.info.pendingResolutionPhase = currentResolutionContext.step;
2439 }
2440 return sym;
2441 }});
2442 }
2444 /** This method scans all the constructor symbol in a given class scope -
2445 * assuming that the original scope contains a constructor of the kind:
2446 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2447 * a method check is executed against the modified constructor type:
2448 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2449 * inference. The inferred return type of the synthetic constructor IS
2450 * the inferred type for the diamond operator.
2451 */
2452 private Symbol findDiamond(Env<AttrContext> env,
2453 Type site,
2454 List<Type> argtypes,
2455 List<Type> typeargtypes,
2456 boolean allowBoxing,
2457 boolean useVarargs) {
2458 Symbol bestSoFar = methodNotFound;
2459 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2460 e.scope != null;
2461 e = e.next()) {
2462 final Symbol sym = e.sym;
2463 //- System.out.println(" e " + e.sym);
2464 if (sym.kind == MTH &&
2465 (sym.flags_field & SYNTHETIC) == 0) {
2466 List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
2467 ((ForAll)sym.type).tvars :
2468 List.<Type>nil();
2469 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2470 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2471 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2472 @Override
2473 public Symbol baseSymbol() {
2474 return sym;
2475 }
2476 };
2477 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2478 newConstr,
2479 bestSoFar,
2480 allowBoxing,
2481 useVarargs,
2482 false);
2483 }
2484 }
2485 return bestSoFar;
2486 }
2490 /** Resolve operator.
2491 * @param pos The position to use for error reporting.
2492 * @param optag The tag of the operation tree.
2493 * @param env The environment current at the operation.
2494 * @param argtypes The types of the operands.
2495 */
2496 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2497 Env<AttrContext> env, List<Type> argtypes) {
2498 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2499 try {
2500 currentResolutionContext = new MethodResolutionContext();
2501 Name name = treeinfo.operatorName(optag);
2502 return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
2503 new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
2504 @Override
2505 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2506 return findMethod(env, site, name, argtypes, typeargtypes,
2507 phase.isBoxingRequired(),
2508 phase.isVarargsRequired(), true);
2509 }
2510 @Override
2511 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2512 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2513 false, argtypes, null);
2514 }
2515 });
2516 } finally {
2517 currentResolutionContext = prevResolutionContext;
2518 }
2519 }
2521 /** Resolve operator.
2522 * @param pos The position to use for error reporting.
2523 * @param optag The tag of the operation tree.
2524 * @param env The environment current at the operation.
2525 * @param arg The type of the operand.
2526 */
2527 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2528 return resolveOperator(pos, optag, env, List.of(arg));
2529 }
2531 /** Resolve binary operator.
2532 * @param pos The position to use for error reporting.
2533 * @param optag The tag of the operation tree.
2534 * @param env The environment current at the operation.
2535 * @param left The types of the left operand.
2536 * @param right The types of the right operand.
2537 */
2538 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2539 JCTree.Tag optag,
2540 Env<AttrContext> env,
2541 Type left,
2542 Type right) {
2543 return resolveOperator(pos, optag, env, List.of(left, right));
2544 }
2546 /**
2547 * Resolution of member references is typically done as a single
2548 * overload resolution step, where the argument types A are inferred from
2549 * the target functional descriptor.
2550 *
2551 * If the member reference is a method reference with a type qualifier,
2552 * a two-step lookup process is performed. The first step uses the
2553 * expected argument list A, while the second step discards the first
2554 * type from A (which is treated as a receiver type).
2555 *
2556 * There are two cases in which inference is performed: (i) if the member
2557 * reference is a constructor reference and the qualifier type is raw - in
2558 * which case diamond inference is used to infer a parameterization for the
2559 * type qualifier; (ii) if the member reference is an unbound reference
2560 * where the type qualifier is raw - in that case, during the unbound lookup
2561 * the receiver argument type is used to infer an instantiation for the raw
2562 * qualifier type.
2563 *
2564 * When a multi-step resolution process is exploited, it is an error
2565 * if two candidates are found (ambiguity).
2566 *
2567 * This routine returns a pair (T,S), where S is the member reference symbol,
2568 * and T is the type of the class in which S is defined. This is necessary as
2569 * the type T might be dynamically inferred (i.e. if constructor reference
2570 * has a raw qualifier).
2571 */
2572 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
2573 Env<AttrContext> env,
2574 JCMemberReference referenceTree,
2575 Type site,
2576 Name name, List<Type> argtypes,
2577 List<Type> typeargtypes,
2578 boolean boxingAllowed,
2579 MethodCheck methodCheck) {
2580 MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
2582 ReferenceLookupHelper boundLookupHelper;
2583 if (!name.equals(names.init)) {
2584 //method reference
2585 boundLookupHelper =
2586 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2587 } else if (site.hasTag(ARRAY)) {
2588 //array constructor reference
2589 boundLookupHelper =
2590 new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2591 } else {
2592 //class constructor reference
2593 boundLookupHelper =
2594 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2595 }
2597 //step 1 - bound lookup
2598 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2599 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, methodCheck, boundLookupHelper);
2601 //step 2 - unbound lookup
2602 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
2603 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2604 Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, methodCheck, unboundLookupHelper);
2606 //merge results
2607 Pair<Symbol, ReferenceLookupHelper> res;
2608 if (!lookupSuccess(unboundSym)) {
2609 res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
2610 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2611 } else if (lookupSuccess(boundSym)) {
2612 res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
2613 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2614 } else {
2615 res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
2616 env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
2617 }
2619 return res;
2620 }
2621 //private
2622 boolean lookupSuccess(Symbol s) {
2623 return s.kind == MTH || s.kind == AMBIGUOUS;
2624 }
2626 /**
2627 * Helper for defining custom method-like lookup logic; a lookup helper
2628 * provides hooks for (i) the actual lookup logic and (ii) accessing the
2629 * lookup result (this step might result in compiler diagnostics to be generated)
2630 */
2631 abstract class LookupHelper {
2633 /** name of the symbol to lookup */
2634 Name name;
2636 /** location in which the lookup takes place */
2637 Type site;
2639 /** actual types used during the lookup */
2640 List<Type> argtypes;
2642 /** type arguments used during the lookup */
2643 List<Type> typeargtypes;
2645 /** Max overload resolution phase handled by this helper */
2646 MethodResolutionPhase maxPhase;
2648 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2649 this.name = name;
2650 this.site = site;
2651 this.argtypes = argtypes;
2652 this.typeargtypes = typeargtypes;
2653 this.maxPhase = maxPhase;
2654 }
2656 /**
2657 * Should lookup stop at given phase with given result
2658 */
2659 protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2660 return phase.ordinal() > maxPhase.ordinal() ||
2661 sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
2662 }
2664 /**
2665 * Search for a symbol under a given overload resolution phase - this method
2666 * is usually called several times, once per each overload resolution phase
2667 */
2668 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
2670 /**
2671 * Dump overload resolution info
2672 */
2673 void debug(DiagnosticPosition pos, Symbol sym) {
2674 //do nothing
2675 }
2677 /**
2678 * Validate the result of the lookup
2679 */
2680 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
2681 }
2683 abstract class BasicLookupHelper extends LookupHelper {
2685 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
2686 this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
2687 }
2689 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2690 super(name, site, argtypes, typeargtypes, maxPhase);
2691 }
2693 @Override
2694 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2695 Symbol sym = doLookup(env, phase);
2696 if (sym.kind == AMBIGUOUS) {
2697 AmbiguityError a_err = (AmbiguityError)sym;
2698 sym = a_err.mergeAbstracts(site);
2699 }
2700 return sym;
2701 }
2703 abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
2705 @Override
2706 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2707 if (sym.kind >= AMBIGUOUS) {
2708 //if nothing is found return the 'first' error
2709 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
2710 }
2711 return sym;
2712 }
2714 @Override
2715 void debug(DiagnosticPosition pos, Symbol sym) {
2716 reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
2717 }
2718 }
2720 /**
2721 * Helper class for member reference lookup. A reference lookup helper
2722 * defines the basic logic for member reference lookup; a method gives
2723 * access to an 'unbound' helper used to perform an unbound member
2724 * reference lookup.
2725 */
2726 abstract class ReferenceLookupHelper extends LookupHelper {
2728 /** The member reference tree */
2729 JCMemberReference referenceTree;
2731 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2732 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2733 super(name, site, argtypes, typeargtypes, maxPhase);
2734 this.referenceTree = referenceTree;
2736 }
2738 /**
2739 * Returns an unbound version of this lookup helper. By default, this
2740 * method returns an dummy lookup helper.
2741 */
2742 ReferenceLookupHelper unboundLookup() {
2743 //dummy loopkup helper that always return 'methodNotFound'
2744 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
2745 @Override
2746 ReferenceLookupHelper unboundLookup() {
2747 return this;
2748 }
2749 @Override
2750 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2751 return methodNotFound;
2752 }
2753 @Override
2754 ReferenceKind referenceKind(Symbol sym) {
2755 Assert.error();
2756 return null;
2757 }
2758 };
2759 }
2761 /**
2762 * Get the kind of the member reference
2763 */
2764 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
2766 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2767 if (sym.kind == AMBIGUOUS) {
2768 AmbiguityError a_err = (AmbiguityError)sym;
2769 sym = a_err.mergeAbstracts(site);
2770 }
2771 //skip error reporting
2772 return sym;
2773 }
2774 }
2776 /**
2777 * Helper class for method reference lookup. The lookup logic is based
2778 * upon Resolve.findMethod; in certain cases, this helper class has a
2779 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
2780 * In such cases, non-static lookup results are thrown away.
2781 */
2782 class MethodReferenceLookupHelper extends ReferenceLookupHelper {
2784 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2785 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2786 super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2787 }
2789 @Override
2790 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2791 return findMethod(env, site, name, argtypes, typeargtypes,
2792 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2793 }
2795 @Override
2796 ReferenceLookupHelper unboundLookup() {
2797 if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
2798 argtypes.nonEmpty() &&
2799 (argtypes.head.hasTag(NONE) || types.isSubtypeUnchecked(argtypes.head, site))) {
2800 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
2801 site, argtypes, typeargtypes, maxPhase);
2802 } else {
2803 return super.unboundLookup();
2804 }
2805 }
2807 @Override
2808 ReferenceKind referenceKind(Symbol sym) {
2809 if (sym.isStatic()) {
2810 return ReferenceKind.STATIC;
2811 } else {
2812 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
2813 return selName != null && selName == names._super ?
2814 ReferenceKind.SUPER :
2815 ReferenceKind.BOUND;
2816 }
2817 }
2818 }
2820 /**
2821 * Helper class for unbound method reference lookup. Essentially the same
2822 * as the basic method reference lookup helper; main difference is that static
2823 * lookup results are thrown away. If qualifier type is raw, an attempt to
2824 * infer a parameterized type is made using the first actual argument (that
2825 * would otherwise be ignored during the lookup).
2826 */
2827 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
2829 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2830 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2831 super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
2832 if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
2833 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
2834 this.site = asSuperSite;
2835 }
2836 }
2838 @Override
2839 ReferenceLookupHelper unboundLookup() {
2840 return this;
2841 }
2843 @Override
2844 ReferenceKind referenceKind(Symbol sym) {
2845 return ReferenceKind.UNBOUND;
2846 }
2847 }
2849 /**
2850 * Helper class for array constructor lookup; an array constructor lookup
2851 * is simulated by looking up a method that returns the array type specified
2852 * as qualifier, and that accepts a single int parameter (size of the array).
2853 */
2854 class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2856 ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2857 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2858 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2859 }
2861 @Override
2862 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2863 Scope sc = new Scope(syms.arrayClass);
2864 MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
2865 arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
2866 sc.enter(arrayConstr);
2867 return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
2868 }
2870 @Override
2871 ReferenceKind referenceKind(Symbol sym) {
2872 return ReferenceKind.ARRAY_CTOR;
2873 }
2874 }
2876 /**
2877 * Helper class for constructor reference lookup. The lookup logic is based
2878 * upon either Resolve.findMethod or Resolve.findDiamond - depending on
2879 * whether the constructor reference needs diamond inference (this is the case
2880 * if the qualifier type is raw). A special erroneous symbol is returned
2881 * if the lookup returns the constructor of an inner class and there's no
2882 * enclosing instance in scope.
2883 */
2884 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2886 boolean needsInference;
2888 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2889 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2890 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2891 if (site.isRaw()) {
2892 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
2893 needsInference = true;
2894 }
2895 }
2897 @Override
2898 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2899 Symbol sym = needsInference ?
2900 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
2901 findMethod(env, site, name, argtypes, typeargtypes,
2902 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2903 return sym.kind != MTH ||
2904 site.getEnclosingType().hasTag(NONE) ||
2905 hasEnclosingInstance(env, site) ?
2906 sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
2907 @Override
2908 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2909 return diags.create(dkind, log.currentSource(), pos,
2910 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
2911 }
2912 };
2913 }
2915 @Override
2916 ReferenceKind referenceKind(Symbol sym) {
2917 return site.getEnclosingType().hasTag(NONE) ?
2918 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
2919 }
2920 }
2922 /**
2923 * Main overload resolution routine. On each overload resolution step, a
2924 * lookup helper class is used to perform the method/constructor lookup;
2925 * at the end of the lookup, the helper is used to validate the results
2926 * (this last step might trigger overload resolution diagnostics).
2927 */
2928 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
2929 MethodResolutionContext resolveContext = new MethodResolutionContext();
2930 resolveContext.methodCheck = methodCheck;
2931 return lookupMethod(env, pos, location, resolveContext, lookupHelper);
2932 }
2934 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
2935 MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
2936 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2937 try {
2938 Symbol bestSoFar = methodNotFound;
2939 currentResolutionContext = resolveContext;
2940 for (MethodResolutionPhase phase : methodResolutionSteps) {
2941 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
2942 lookupHelper.shouldStop(bestSoFar, phase)) break;
2943 MethodResolutionPhase prevPhase = currentResolutionContext.step;
2944 Symbol prevBest = bestSoFar;
2945 currentResolutionContext.step = phase;
2946 Symbol sym = lookupHelper.lookup(env, phase);
2947 lookupHelper.debug(pos, sym);
2948 bestSoFar = phase.mergeResults(bestSoFar, sym);
2949 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
2950 }
2951 return lookupHelper.access(env, pos, location, bestSoFar);
2952 } finally {
2953 currentResolutionContext = prevResolutionContext;
2954 }
2955 }
2957 /**
2958 * Resolve `c.name' where name == this or name == super.
2959 * @param pos The position to use for error reporting.
2960 * @param env The environment current at the expression.
2961 * @param c The qualifier.
2962 * @param name The identifier's name.
2963 */
2964 Symbol resolveSelf(DiagnosticPosition pos,
2965 Env<AttrContext> env,
2966 TypeSymbol c,
2967 Name name) {
2968 Env<AttrContext> env1 = env;
2969 boolean staticOnly = false;
2970 while (env1.outer != null) {
2971 if (isStatic(env1)) staticOnly = true;
2972 if (env1.enclClass.sym == c) {
2973 Symbol sym = env1.info.scope.lookup(name).sym;
2974 if (sym != null) {
2975 if (staticOnly) sym = new StaticError(sym);
2976 return accessBase(sym, pos, env.enclClass.sym.type,
2977 name, true);
2978 }
2979 }
2980 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2981 env1 = env1.outer;
2982 }
2983 if (allowDefaultMethods && c.isInterface() &&
2984 name == names._super && !isStatic(env) &&
2985 types.isDirectSuperInterface(c, env.enclClass.sym)) {
2986 //this might be a default super call if one of the superinterfaces is 'c'
2987 for (Type t : pruneInterfaces(env.enclClass.type)) {
2988 if (t.tsym == c) {
2989 env.info.defaultSuperCallSite = t;
2990 return new VarSymbol(0, names._super,
2991 types.asSuper(env.enclClass.type, c), env.enclClass.sym);
2992 }
2993 }
2994 //find a direct superinterface that is a subtype of 'c'
2995 for (Type i : types.interfaces(env.enclClass.type)) {
2996 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
2997 log.error(pos, "illegal.default.super.call", c,
2998 diags.fragment("redundant.supertype", c, i));
2999 return syms.errSymbol;
3000 }
3001 }
3002 Assert.error();
3003 }
3004 log.error(pos, "not.encl.class", c);
3005 return syms.errSymbol;
3006 }
3007 //where
3008 private List<Type> pruneInterfaces(Type t) {
3009 ListBuffer<Type> result = ListBuffer.lb();
3010 for (Type t1 : types.interfaces(t)) {
3011 boolean shouldAdd = true;
3012 for (Type t2 : types.interfaces(t)) {
3013 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
3014 shouldAdd = false;
3015 }
3016 }
3017 if (shouldAdd) {
3018 result.append(t1);
3019 }
3020 }
3021 return result.toList();
3022 }
3025 /**
3026 * Resolve `c.this' for an enclosing class c that contains the
3027 * named member.
3028 * @param pos The position to use for error reporting.
3029 * @param env The environment current at the expression.
3030 * @param member The member that must be contained in the result.
3031 */
3032 Symbol resolveSelfContaining(DiagnosticPosition pos,
3033 Env<AttrContext> env,
3034 Symbol member,
3035 boolean isSuperCall) {
3036 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
3037 if (sym == null) {
3038 log.error(pos, "encl.class.required", member);
3039 return syms.errSymbol;
3040 } else {
3041 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
3042 }
3043 }
3045 boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
3046 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
3047 return encl != null && encl.kind < ERRONEOUS;
3048 }
3050 private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
3051 Symbol member,
3052 boolean isSuperCall) {
3053 Name name = names._this;
3054 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
3055 boolean staticOnly = false;
3056 if (env1 != null) {
3057 while (env1 != null && env1.outer != null) {
3058 if (isStatic(env1)) staticOnly = true;
3059 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
3060 Symbol sym = env1.info.scope.lookup(name).sym;
3061 if (sym != null) {
3062 if (staticOnly) sym = new StaticError(sym);
3063 return sym;
3064 }
3065 }
3066 if ((env1.enclClass.sym.flags() & STATIC) != 0)
3067 staticOnly = true;
3068 env1 = env1.outer;
3069 }
3070 }
3071 return null;
3072 }
3074 /**
3075 * Resolve an appropriate implicit this instance for t's container.
3076 * JLS 8.8.5.1 and 15.9.2
3077 */
3078 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
3079 return resolveImplicitThis(pos, env, t, false);
3080 }
3082 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
3083 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
3084 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
3085 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
3086 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
3087 log.error(pos, "cant.ref.before.ctor.called", "this");
3088 return thisType;
3089 }
3091 /* ***************************************************************************
3092 * ResolveError classes, indicating error situations when accessing symbols
3093 ****************************************************************************/
3095 //used by TransTypes when checking target type of synthetic cast
3096 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
3097 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
3098 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
3099 }
3100 //where
3101 private void logResolveError(ResolveError error,
3102 DiagnosticPosition pos,
3103 Symbol location,
3104 Type site,
3105 Name name,
3106 List<Type> argtypes,
3107 List<Type> typeargtypes) {
3108 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3109 pos, location, site, name, argtypes, typeargtypes);
3110 if (d != null) {
3111 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
3112 log.report(d);
3113 }
3114 }
3116 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
3118 public Object methodArguments(List<Type> argtypes) {
3119 if (argtypes == null || argtypes.isEmpty()) {
3120 return noArgs;
3121 } else {
3122 ListBuffer<Object> diagArgs = ListBuffer.lb();
3123 for (Type t : argtypes) {
3124 if (t.hasTag(DEFERRED)) {
3125 diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3126 } else {
3127 diagArgs.append(t);
3128 }
3129 }
3130 return diagArgs;
3131 }
3132 }
3134 /**
3135 * Root class for resolution errors. Subclass of ResolveError
3136 * represent a different kinds of resolution error - as such they must
3137 * specify how they map into concrete compiler diagnostics.
3138 */
3139 abstract class ResolveError extends Symbol {
3141 /** The name of the kind of error, for debugging only. */
3142 final String debugName;
3144 ResolveError(int kind, String debugName) {
3145 super(kind, 0, null, null, null);
3146 this.debugName = debugName;
3147 }
3149 @Override
3150 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3151 throw new AssertionError();
3152 }
3154 @Override
3155 public String toString() {
3156 return debugName;
3157 }
3159 @Override
3160 public boolean exists() {
3161 return false;
3162 }
3164 /**
3165 * Create an external representation for this erroneous symbol to be
3166 * used during attribution - by default this returns the symbol of a
3167 * brand new error type which stores the original type found
3168 * during resolution.
3169 *
3170 * @param name the name used during resolution
3171 * @param location the location from which the symbol is accessed
3172 */
3173 protected Symbol access(Name name, TypeSymbol location) {
3174 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3175 }
3177 /**
3178 * Create a diagnostic representing this resolution error.
3179 *
3180 * @param dkind The kind of the diagnostic to be created (e.g error).
3181 * @param pos The position to be used for error reporting.
3182 * @param site The original type from where the selection took place.
3183 * @param name The name of the symbol to be resolved.
3184 * @param argtypes The invocation's value arguments,
3185 * if we looked for a method.
3186 * @param typeargtypes The invocation's type arguments,
3187 * if we looked for a method.
3188 */
3189 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3190 DiagnosticPosition pos,
3191 Symbol location,
3192 Type site,
3193 Name name,
3194 List<Type> argtypes,
3195 List<Type> typeargtypes);
3196 }
3198 /**
3199 * This class is the root class of all resolution errors caused by
3200 * an invalid symbol being found during resolution.
3201 */
3202 abstract class InvalidSymbolError extends ResolveError {
3204 /** The invalid symbol found during resolution */
3205 Symbol sym;
3207 InvalidSymbolError(int kind, Symbol sym, String debugName) {
3208 super(kind, debugName);
3209 this.sym = sym;
3210 }
3212 @Override
3213 public boolean exists() {
3214 return true;
3215 }
3217 @Override
3218 public String toString() {
3219 return super.toString() + " wrongSym=" + sym;
3220 }
3222 @Override
3223 public Symbol access(Name name, TypeSymbol location) {
3224 if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
3225 return types.createErrorType(name, location, sym.type).tsym;
3226 else
3227 return sym;
3228 }
3229 }
3231 /**
3232 * InvalidSymbolError error class indicating that a symbol matching a
3233 * given name does not exists in a given site.
3234 */
3235 class SymbolNotFoundError extends ResolveError {
3237 SymbolNotFoundError(int kind) {
3238 super(kind, "symbol not found error");
3239 }
3241 @Override
3242 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3243 DiagnosticPosition pos,
3244 Symbol location,
3245 Type site,
3246 Name name,
3247 List<Type> argtypes,
3248 List<Type> typeargtypes) {
3249 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3250 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3251 if (name == names.error)
3252 return null;
3254 if (syms.operatorNames.contains(name)) {
3255 boolean isUnaryOp = argtypes.size() == 1;
3256 String key = argtypes.size() == 1 ?
3257 "operator.cant.be.applied" :
3258 "operator.cant.be.applied.1";
3259 Type first = argtypes.head;
3260 Type second = !isUnaryOp ? argtypes.tail.head : null;
3261 return diags.create(dkind, log.currentSource(), pos,
3262 key, name, first, second);
3263 }
3264 boolean hasLocation = false;
3265 if (location == null) {
3266 location = site.tsym;
3267 }
3268 if (!location.name.isEmpty()) {
3269 if (location.kind == PCK && !site.tsym.exists()) {
3270 return diags.create(dkind, log.currentSource(), pos,
3271 "doesnt.exist", location);
3272 }
3273 hasLocation = !location.name.equals(names._this) &&
3274 !location.name.equals(names._super);
3275 }
3276 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
3277 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
3278 Name idname = isConstructor ? site.tsym.name : name;
3279 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3280 if (hasLocation) {
3281 return diags.create(dkind, log.currentSource(), pos,
3282 errKey, kindname, idname, //symbol kindname, name
3283 typeargtypes, args(argtypes), //type parameters and arguments (if any)
3284 getLocationDiag(location, site)); //location kindname, type
3285 }
3286 else {
3287 return diags.create(dkind, log.currentSource(), pos,
3288 errKey, kindname, idname, //symbol kindname, name
3289 typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3290 }
3291 }
3292 //where
3293 private Object args(List<Type> args) {
3294 return args.isEmpty() ? args : methodArguments(args);
3295 }
3297 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3298 String key = "cant.resolve";
3299 String suffix = hasLocation ? ".location" : "";
3300 switch (kindname) {
3301 case METHOD:
3302 case CONSTRUCTOR: {
3303 suffix += ".args";
3304 suffix += hasTypeArgs ? ".params" : "";
3305 }
3306 }
3307 return key + suffix;
3308 }
3309 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3310 if (location.kind == VAR) {
3311 return diags.fragment("location.1",
3312 kindName(location),
3313 location,
3314 location.type);
3315 } else {
3316 return diags.fragment("location",
3317 typeKindName(site),
3318 site,
3319 null);
3320 }
3321 }
3322 }
3324 /**
3325 * InvalidSymbolError error class indicating that a given symbol
3326 * (either a method, a constructor or an operand) is not applicable
3327 * given an actual arguments/type argument list.
3328 */
3329 class InapplicableSymbolError extends ResolveError {
3331 protected MethodResolutionContext resolveContext;
3333 InapplicableSymbolError(MethodResolutionContext context) {
3334 this(WRONG_MTH, "inapplicable symbol error", context);
3335 }
3337 protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
3338 super(kind, debugName);
3339 this.resolveContext = context;
3340 }
3342 @Override
3343 public String toString() {
3344 return super.toString();
3345 }
3347 @Override
3348 public boolean exists() {
3349 return true;
3350 }
3352 @Override
3353 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3354 DiagnosticPosition pos,
3355 Symbol location,
3356 Type site,
3357 Name name,
3358 List<Type> argtypes,
3359 List<Type> typeargtypes) {
3360 if (name == names.error)
3361 return null;
3363 if (syms.operatorNames.contains(name)) {
3364 boolean isUnaryOp = argtypes.size() == 1;
3365 String key = argtypes.size() == 1 ?
3366 "operator.cant.be.applied" :
3367 "operator.cant.be.applied.1";
3368 Type first = argtypes.head;
3369 Type second = !isUnaryOp ? argtypes.tail.head : null;
3370 return diags.create(dkind, log.currentSource(), pos,
3371 key, name, first, second);
3372 }
3373 else {
3374 Candidate c = errCandidate();
3375 if (compactMethodDiags) {
3376 for (Map.Entry<Template, DiagnosticRewriter> _entry :
3377 MethodResolutionDiagHelper.rewriters.entrySet()) {
3378 if (_entry.getKey().matches(c.details)) {
3379 JCDiagnostic simpleDiag =
3380 _entry.getValue().rewriteDiagnostic(diags, pos,
3381 log.currentSource(), dkind, c.details);
3382 simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
3383 return simpleDiag;
3384 }
3385 }
3386 }
3387 Symbol ws = c.sym.asMemberOf(site, types);
3388 return diags.create(dkind, log.currentSource(), pos,
3389 "cant.apply.symbol",
3390 kindName(ws),
3391 ws.name == names.init ? ws.owner.name : ws.name,
3392 methodArguments(ws.type.getParameterTypes()),
3393 methodArguments(argtypes),
3394 kindName(ws.owner),
3395 ws.owner.type,
3396 c.details);
3397 }
3398 }
3400 @Override
3401 public Symbol access(Name name, TypeSymbol location) {
3402 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3403 }
3405 private Candidate errCandidate() {
3406 Candidate bestSoFar = null;
3407 for (Candidate c : resolveContext.candidates) {
3408 if (c.isApplicable()) continue;
3409 bestSoFar = c;
3410 }
3411 Assert.checkNonNull(bestSoFar);
3412 return bestSoFar;
3413 }
3414 }
3416 /**
3417 * ResolveError error class indicating that a set of symbols
3418 * (either methods, constructors or operands) is not applicable
3419 * given an actual arguments/type argument list.
3420 */
3421 class InapplicableSymbolsError extends InapplicableSymbolError {
3423 InapplicableSymbolsError(MethodResolutionContext context) {
3424 super(WRONG_MTHS, "inapplicable symbols", context);
3425 }
3427 @Override
3428 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3429 DiagnosticPosition pos,
3430 Symbol location,
3431 Type site,
3432 Name name,
3433 List<Type> argtypes,
3434 List<Type> typeargtypes) {
3435 Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
3436 Map<Symbol, JCDiagnostic> filteredCandidates = filterCandidates(candidatesMap);
3437 if (filteredCandidates.isEmpty()) {
3438 filteredCandidates = candidatesMap;
3439 }
3440 boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
3441 if (filteredCandidates.size() > 1) {
3442 JCDiagnostic err = diags.create(dkind,
3443 null,
3444 truncatedDiag ?
3445 EnumSet.of(DiagnosticFlag.COMPRESSED) :
3446 EnumSet.noneOf(DiagnosticFlag.class),
3447 log.currentSource(),
3448 pos,
3449 "cant.apply.symbols",
3450 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
3451 name == names.init ? site.tsym.name : name,
3452 methodArguments(argtypes));
3453 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
3454 } else if (filteredCandidates.size() == 1) {
3455 JCDiagnostic d = new InapplicableSymbolError(resolveContext).getDiagnostic(dkind, pos,
3456 location, site, name, argtypes, typeargtypes);
3457 if (truncatedDiag) {
3458 d.setFlag(DiagnosticFlag.COMPRESSED);
3459 }
3460 return d;
3461 } else {
3462 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3463 location, site, name, argtypes, typeargtypes);
3464 }
3465 }
3466 //where
3467 private Map<Symbol, JCDiagnostic> mapCandidates() {
3468 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
3469 for (Candidate c : resolveContext.candidates) {
3470 if (c.isApplicable()) continue;
3471 candidates.put(c.sym, c.details);
3472 }
3473 return candidates;
3474 }
3476 Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
3477 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
3478 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3479 JCDiagnostic d = _entry.getValue();
3480 if (!compactMethodDiags ||
3481 !new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
3482 candidates.put(_entry.getKey(), d);
3483 }
3484 }
3485 return candidates;
3486 }
3488 private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
3489 List<JCDiagnostic> details = List.nil();
3490 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3491 Symbol sym = _entry.getKey();
3492 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3493 Kinds.kindName(sym),
3494 sym.location(site, types),
3495 sym.asMemberOf(site, types),
3496 _entry.getValue());
3497 details = details.prepend(detailDiag);
3498 }
3499 //typically members are visited in reverse order (see Scope)
3500 //so we need to reverse the candidate list so that candidates
3501 //conform to source order
3502 return details;
3503 }
3504 }
3506 /**
3507 * An InvalidSymbolError error class indicating that a symbol is not
3508 * accessible from a given site
3509 */
3510 class AccessError extends InvalidSymbolError {
3512 private Env<AttrContext> env;
3513 private Type site;
3515 AccessError(Symbol sym) {
3516 this(null, null, sym);
3517 }
3519 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3520 super(HIDDEN, sym, "access error");
3521 this.env = env;
3522 this.site = site;
3523 if (debugResolve)
3524 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3525 }
3527 @Override
3528 public boolean exists() {
3529 return false;
3530 }
3532 @Override
3533 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3534 DiagnosticPosition pos,
3535 Symbol location,
3536 Type site,
3537 Name name,
3538 List<Type> argtypes,
3539 List<Type> typeargtypes) {
3540 if (sym.owner.type.hasTag(ERROR))
3541 return null;
3543 if (sym.name == names.init && sym.owner != site.tsym) {
3544 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3545 pos, location, site, name, argtypes, typeargtypes);
3546 }
3547 else if ((sym.flags() & PUBLIC) != 0
3548 || (env != null && this.site != null
3549 && !isAccessible(env, this.site))) {
3550 return diags.create(dkind, log.currentSource(),
3551 pos, "not.def.access.class.intf.cant.access",
3552 sym, sym.location());
3553 }
3554 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3555 return diags.create(dkind, log.currentSource(),
3556 pos, "report.access", sym,
3557 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3558 sym.location());
3559 }
3560 else {
3561 return diags.create(dkind, log.currentSource(),
3562 pos, "not.def.public.cant.access", sym, sym.location());
3563 }
3564 }
3565 }
3567 /**
3568 * InvalidSymbolError error class indicating that an instance member
3569 * has erroneously been accessed from a static context.
3570 */
3571 class StaticError extends InvalidSymbolError {
3573 StaticError(Symbol sym) {
3574 super(STATICERR, sym, "static error");
3575 }
3577 @Override
3578 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3579 DiagnosticPosition pos,
3580 Symbol location,
3581 Type site,
3582 Name name,
3583 List<Type> argtypes,
3584 List<Type> typeargtypes) {
3585 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3586 ? types.erasure(sym.type).tsym
3587 : sym);
3588 return diags.create(dkind, log.currentSource(), pos,
3589 "non-static.cant.be.ref", kindName(sym), errSym);
3590 }
3591 }
3593 /**
3594 * InvalidSymbolError error class indicating that a pair of symbols
3595 * (either methods, constructors or operands) are ambiguous
3596 * given an actual arguments/type argument list.
3597 */
3598 class AmbiguityError extends ResolveError {
3600 /** The other maximally specific symbol */
3601 List<Symbol> ambiguousSyms = List.nil();
3603 @Override
3604 public boolean exists() {
3605 return true;
3606 }
3608 AmbiguityError(Symbol sym1, Symbol sym2) {
3609 super(AMBIGUOUS, "ambiguity error");
3610 ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3611 }
3613 private List<Symbol> flatten(Symbol sym) {
3614 if (sym.kind == AMBIGUOUS) {
3615 return ((AmbiguityError)sym).ambiguousSyms;
3616 } else {
3617 return List.of(sym);
3618 }
3619 }
3621 AmbiguityError addAmbiguousSymbol(Symbol s) {
3622 ambiguousSyms = ambiguousSyms.prepend(s);
3623 return this;
3624 }
3626 @Override
3627 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3628 DiagnosticPosition pos,
3629 Symbol location,
3630 Type site,
3631 Name name,
3632 List<Type> argtypes,
3633 List<Type> typeargtypes) {
3634 List<Symbol> diagSyms = ambiguousSyms.reverse();
3635 Symbol s1 = diagSyms.head;
3636 Symbol s2 = diagSyms.tail.head;
3637 Name sname = s1.name;
3638 if (sname == names.init) sname = s1.owner.name;
3639 return diags.create(dkind, log.currentSource(),
3640 pos, "ref.ambiguous", sname,
3641 kindName(s1),
3642 s1,
3643 s1.location(site, types),
3644 kindName(s2),
3645 s2,
3646 s2.location(site, types));
3647 }
3649 /**
3650 * If multiple applicable methods are found during overload and none of them
3651 * is more specific than the others, attempt to merge their signatures.
3652 */
3653 Symbol mergeAbstracts(Type site) {
3654 List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
3655 for (Symbol s : ambiguousInOrder) {
3656 Type mt = types.memberType(site, s);
3657 boolean found = true;
3658 List<Type> allThrown = mt.getThrownTypes();
3659 for (Symbol s2 : ambiguousInOrder) {
3660 Type mt2 = types.memberType(site, s2);
3661 if ((s2.flags() & ABSTRACT) == 0 ||
3662 !types.overrideEquivalent(mt, mt2) ||
3663 !types.isSameTypes(s.erasure(types).getParameterTypes(),
3664 s2.erasure(types).getParameterTypes())) {
3665 //ambiguity cannot be resolved
3666 return this;
3667 }
3668 Type mst = mostSpecificReturnType(mt, mt2);
3669 if (mst == null || mst != mt) {
3670 found = false;
3671 break;
3672 }
3673 allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
3674 }
3675 if (found) {
3676 //all ambiguous methods were abstract and one method had
3677 //most specific return type then others
3678 return (allThrown == mt.getThrownTypes()) ?
3679 s : new MethodSymbol(
3680 s.flags(),
3681 s.name,
3682 types.createMethodTypeWithThrown(mt, allThrown),
3683 s.owner);
3684 }
3685 }
3686 return this;
3687 }
3689 @Override
3690 protected Symbol access(Name name, TypeSymbol location) {
3691 Symbol firstAmbiguity = ambiguousSyms.last();
3692 return firstAmbiguity.kind == TYP ?
3693 types.createErrorType(name, location, firstAmbiguity.type).tsym :
3694 firstAmbiguity;
3695 }
3696 }
3698 class BadVarargsMethod extends ResolveError {
3700 ResolveError delegatedError;
3702 BadVarargsMethod(ResolveError delegatedError) {
3703 super(delegatedError.kind, "badVarargs");
3704 this.delegatedError = delegatedError;
3705 }
3707 @Override
3708 public Symbol baseSymbol() {
3709 return delegatedError.baseSymbol();
3710 }
3712 @Override
3713 protected Symbol access(Name name, TypeSymbol location) {
3714 return delegatedError.access(name, location);
3715 }
3717 @Override
3718 public boolean exists() {
3719 return true;
3720 }
3722 @Override
3723 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
3724 return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
3725 }
3726 }
3728 /**
3729 * Helper class for method resolution diagnostic simplification.
3730 * Certain resolution diagnostic are rewritten as simpler diagnostic
3731 * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
3732 * is stripped away, as it doesn't carry additional info. The logic
3733 * for matching a given diagnostic is given in terms of a template
3734 * hierarchy: a diagnostic template can be specified programmatically,
3735 * so that only certain diagnostics are matched. Each templete is then
3736 * associated with a rewriter object that carries out the task of rewtiting
3737 * the diagnostic to a simpler one.
3738 */
3739 static class MethodResolutionDiagHelper {
3741 /**
3742 * A diagnostic rewriter transforms a method resolution diagnostic
3743 * into a simpler one
3744 */
3745 interface DiagnosticRewriter {
3746 JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3747 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3748 DiagnosticType preferredKind, JCDiagnostic d);
3749 }
3751 /**
3752 * A diagnostic template is made up of two ingredients: (i) a regular
3753 * expression for matching a diagnostic key and (ii) a list of sub-templates
3754 * for matching diagnostic arguments.
3755 */
3756 static class Template {
3758 /** regex used to match diag key */
3759 String regex;
3761 /** templates used to match diagnostic args */
3762 Template[] subTemplates;
3764 Template(String key, Template... subTemplates) {
3765 this.regex = key;
3766 this.subTemplates = subTemplates;
3767 }
3769 /**
3770 * Returns true if the regex matches the diagnostic key and if
3771 * all diagnostic arguments are matches by corresponding sub-templates.
3772 */
3773 boolean matches(Object o) {
3774 JCDiagnostic d = (JCDiagnostic)o;
3775 Object[] args = d.getArgs();
3776 if (!d.getCode().matches(regex) ||
3777 subTemplates.length != d.getArgs().length) {
3778 return false;
3779 }
3780 for (int i = 0; i < args.length ; i++) {
3781 if (!subTemplates[i].matches(args[i])) {
3782 return false;
3783 }
3784 }
3785 return true;
3786 }
3787 }
3789 /** a dummy template that match any diagnostic argument */
3790 static final Template skip = new Template("") {
3791 @Override
3792 boolean matches(Object d) {
3793 return true;
3794 }
3795 };
3797 /** rewriter map used for method resolution simplification */
3798 static final Map<Template, DiagnosticRewriter> rewriters =
3799 new LinkedHashMap<Template, DiagnosticRewriter>();
3801 static {
3802 String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
3803 rewriters.put(new Template(argMismatchRegex, new Template("(.*)(bad.arg.types.in.lambda)", skip, skip)),
3804 new DiagnosticRewriter() {
3805 @Override
3806 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3807 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3808 DiagnosticType preferredKind, JCDiagnostic d) {
3809 return (JCDiagnostic)((JCDiagnostic)d.getArgs()[0]).getArgs()[1];
3810 }
3811 });
3813 rewriters.put(new Template(argMismatchRegex, skip),
3814 new DiagnosticRewriter() {
3815 @Override
3816 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
3817 DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
3818 DiagnosticType preferredKind, JCDiagnostic d) {
3819 JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
3820 return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
3821 "prob.found.req", cause);
3822 }
3823 });
3824 }
3825 }
3827 enum MethodResolutionPhase {
3828 BASIC(false, false),
3829 BOX(true, false),
3830 VARARITY(true, true) {
3831 @Override
3832 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
3833 switch (sym.kind) {
3834 case WRONG_MTH:
3835 return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
3836 bestSoFar :
3837 sym;
3838 case ABSENT_MTH:
3839 return bestSoFar;
3840 default:
3841 return sym;
3842 }
3843 }
3844 };
3846 final boolean isBoxingRequired;
3847 final boolean isVarargsRequired;
3849 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
3850 this.isBoxingRequired = isBoxingRequired;
3851 this.isVarargsRequired = isVarargsRequired;
3852 }
3854 public boolean isBoxingRequired() {
3855 return isBoxingRequired;
3856 }
3858 public boolean isVarargsRequired() {
3859 return isVarargsRequired;
3860 }
3862 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
3863 return (varargsEnabled || !isVarargsRequired) &&
3864 (boxingEnabled || !isBoxingRequired);
3865 }
3867 public Symbol mergeResults(Symbol prev, Symbol sym) {
3868 return sym;
3869 }
3870 }
3872 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
3874 /**
3875 * A resolution context is used to keep track of intermediate results of
3876 * overload resolution, such as list of method that are not applicable
3877 * (used to generate more precise diagnostics) and so on. Resolution contexts
3878 * can be nested - this means that when each overload resolution routine should
3879 * work within the resolution context it created.
3880 */
3881 class MethodResolutionContext {
3883 private List<Candidate> candidates = List.nil();
3885 MethodResolutionPhase step = null;
3887 MethodCheck methodCheck = resolveMethodCheck;
3889 private boolean internalResolution = false;
3890 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
3892 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
3893 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
3894 candidates = candidates.append(c);
3895 }
3897 void addApplicableCandidate(Symbol sym, Type mtype) {
3898 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
3899 candidates = candidates.append(c);
3900 }
3902 DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
3903 return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
3904 }
3906 /**
3907 * This class represents an overload resolution candidate. There are two
3908 * kinds of candidates: applicable methods and inapplicable methods;
3909 * applicable methods have a pointer to the instantiated method type,
3910 * while inapplicable candidates contain further details about the
3911 * reason why the method has been considered inapplicable.
3912 */
3913 @SuppressWarnings("overrides")
3914 class Candidate {
3916 final MethodResolutionPhase step;
3917 final Symbol sym;
3918 final JCDiagnostic details;
3919 final Type mtype;
3921 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
3922 this.step = step;
3923 this.sym = sym;
3924 this.details = details;
3925 this.mtype = mtype;
3926 }
3928 @Override
3929 public boolean equals(Object o) {
3930 if (o instanceof Candidate) {
3931 Symbol s1 = this.sym;
3932 Symbol s2 = ((Candidate)o).sym;
3933 if ((s1 != s2 &&
3934 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
3935 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
3936 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
3937 return true;
3938 }
3939 return false;
3940 }
3942 boolean isApplicable() {
3943 return mtype != null;
3944 }
3945 }
3947 DeferredAttr.AttrMode attrMode() {
3948 return attrMode;
3949 }
3951 boolean internal() {
3952 return internalResolution;
3953 }
3954 }
3956 MethodResolutionContext currentResolutionContext = null;
3957 }