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