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