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