Mon, 17 Dec 2012 07:47:05 -0800
8004832: Add new doclint package
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2012, 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.InferenceContext.FreeTypeListener;
39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
40 import com.sun.tools.javac.jvm.*;
41 import com.sun.tools.javac.tree.*;
42 import com.sun.tools.javac.tree.JCTree.*;
43 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
44 import com.sun.tools.javac.util.*;
45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
49 import java.util.Arrays;
50 import java.util.Collection;
51 import java.util.EnumMap;
52 import java.util.EnumSet;
53 import java.util.Iterator;
54 import java.util.LinkedHashMap;
55 import java.util.LinkedHashSet;
56 import java.util.Map;
57 import java.util.Set;
59 import javax.lang.model.element.ElementVisitor;
61 import static com.sun.tools.javac.code.Flags.*;
62 import static com.sun.tools.javac.code.Flags.BLOCK;
63 import static com.sun.tools.javac.code.Kinds.*;
64 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
65 import static com.sun.tools.javac.code.TypeTag.*;
66 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
67 import static com.sun.tools.javac.tree.JCTree.Tag.*;
69 /** Helper class for name resolution, used mostly by the attribution phase.
70 *
71 * <p><b>This is NOT part of any supported API.
72 * If you write code that depends on this, you do so at your own risk.
73 * This code and its internal interfaces are subject to change or
74 * deletion without notice.</b>
75 */
76 public class Resolve {
77 protected static final Context.Key<Resolve> resolveKey =
78 new Context.Key<Resolve>();
80 Names names;
81 Log log;
82 Symtab syms;
83 Attr attr;
84 DeferredAttr deferredAttr;
85 Check chk;
86 Infer infer;
87 ClassReader reader;
88 TreeInfo treeinfo;
89 Types types;
90 JCDiagnostic.Factory diags;
91 public final boolean boxingEnabled; // = source.allowBoxing();
92 public final boolean varargsEnabled; // = source.allowVarargs();
93 public final boolean allowMethodHandles;
94 public final boolean allowDefaultMethods;
95 private final boolean debugResolve;
96 final EnumSet<VerboseResolutionMode> verboseResolutionMode;
98 Scope polymorphicSignatureScope;
100 protected Resolve(Context context) {
101 context.put(resolveKey, this);
102 syms = Symtab.instance(context);
104 varNotFound = new
105 SymbolNotFoundError(ABSENT_VAR);
106 methodNotFound = new
107 SymbolNotFoundError(ABSENT_MTH);
108 typeNotFound = new
109 SymbolNotFoundError(ABSENT_TYP);
111 names = Names.instance(context);
112 log = Log.instance(context);
113 attr = Attr.instance(context);
114 deferredAttr = DeferredAttr.instance(context);
115 chk = Check.instance(context);
116 infer = Infer.instance(context);
117 reader = ClassReader.instance(context);
118 treeinfo = TreeInfo.instance(context);
119 types = Types.instance(context);
120 diags = JCDiagnostic.Factory.instance(context);
121 Source source = Source.instance(context);
122 boxingEnabled = source.allowBoxing();
123 varargsEnabled = source.allowVarargs();
124 Options options = Options.instance(context);
125 debugResolve = options.isSet("debugresolve");
126 verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
127 Target target = Target.instance(context);
128 allowMethodHandles = target.hasMethodHandles();
129 allowDefaultMethods = source.allowDefaultMethods();
130 polymorphicSignatureScope = new Scope(syms.noSymbol);
132 inapplicableMethodException = new InapplicableMethodException(diags);
133 }
135 /** error symbols, which are returned when resolution fails
136 */
137 private final SymbolNotFoundError varNotFound;
138 private final SymbolNotFoundError methodNotFound;
139 private final SymbolNotFoundError typeNotFound;
141 public static Resolve instance(Context context) {
142 Resolve instance = context.get(resolveKey);
143 if (instance == null)
144 instance = new Resolve(context);
145 return instance;
146 }
148 // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
149 enum VerboseResolutionMode {
150 SUCCESS("success"),
151 FAILURE("failure"),
152 APPLICABLE("applicable"),
153 INAPPLICABLE("inapplicable"),
154 DEFERRED_INST("deferred-inference"),
155 PREDEF("predef"),
156 OBJECT_INIT("object-init"),
157 INTERNAL("internal");
159 final String opt;
161 private VerboseResolutionMode(String opt) {
162 this.opt = opt;
163 }
165 static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
166 String s = opts.get("verboseResolution");
167 EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
168 if (s == null) return res;
169 if (s.contains("all")) {
170 res = EnumSet.allOf(VerboseResolutionMode.class);
171 }
172 Collection<String> args = Arrays.asList(s.split(","));
173 for (VerboseResolutionMode mode : values()) {
174 if (args.contains(mode.opt)) {
175 res.add(mode);
176 } else if (args.contains("-" + mode.opt)) {
177 res.remove(mode);
178 }
179 }
180 return res;
181 }
182 }
184 void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
185 List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
186 boolean success = bestSoFar.kind < ERRONEOUS;
188 if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
189 return;
190 } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
191 return;
192 }
194 if (bestSoFar.name == names.init &&
195 bestSoFar.owner == syms.objectType.tsym &&
196 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
197 return; //skip diags for Object constructor resolution
198 } else if (site == syms.predefClass.type &&
199 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
200 return; //skip spurious diags for predef symbols (i.e. operators)
201 } else if (currentResolutionContext.internalResolution &&
202 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
203 return;
204 }
206 int pos = 0;
207 int mostSpecificPos = -1;
208 ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
209 for (Candidate c : currentResolutionContext.candidates) {
210 if (currentResolutionContext.step != c.step ||
211 (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
212 (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
213 continue;
214 } else {
215 subDiags.append(c.isApplicable() ?
216 getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
217 getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
218 if (c.sym == bestSoFar)
219 mostSpecificPos = pos;
220 pos++;
221 }
222 }
223 String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
224 List<Type> argtypes2 = Type.map(argtypes,
225 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
226 JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
227 site.tsym, mostSpecificPos, currentResolutionContext.step,
228 methodArguments(argtypes2),
229 methodArguments(typeargtypes));
230 JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
231 log.report(d);
232 }
234 JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
235 JCDiagnostic subDiag = null;
236 if (sym.type.hasTag(FORALL)) {
237 subDiag = diags.fragment("partial.inst.sig", inst);
238 }
240 String key = subDiag == null ?
241 "applicable.method.found" :
242 "applicable.method.found.1";
244 return diags.fragment(key, pos, sym, subDiag);
245 }
247 JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
248 return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
249 }
250 // </editor-fold>
252 /* ************************************************************************
253 * Identifier resolution
254 *************************************************************************/
256 /** An environment is "static" if its static level is greater than
257 * the one of its outer environment
258 */
259 protected static boolean isStatic(Env<AttrContext> env) {
260 return env.info.staticLevel > env.outer.info.staticLevel;
261 }
263 /** An environment is an "initializer" if it is a constructor or
264 * an instance initializer.
265 */
266 static boolean isInitializer(Env<AttrContext> env) {
267 Symbol owner = env.info.scope.owner;
268 return owner.isConstructor() ||
269 owner.owner.kind == TYP &&
270 (owner.kind == VAR ||
271 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
272 (owner.flags() & STATIC) == 0;
273 }
275 /** Is class accessible in given evironment?
276 * @param env The current environment.
277 * @param c The class whose accessibility is checked.
278 */
279 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
280 return isAccessible(env, c, false);
281 }
283 public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
284 boolean isAccessible = false;
285 switch ((short)(c.flags() & AccessFlags)) {
286 case PRIVATE:
287 isAccessible =
288 env.enclClass.sym.outermostClass() ==
289 c.owner.outermostClass();
290 break;
291 case 0:
292 isAccessible =
293 env.toplevel.packge == c.owner // fast special case
294 ||
295 env.toplevel.packge == c.packge()
296 ||
297 // Hack: this case is added since synthesized default constructors
298 // of anonymous classes should be allowed to access
299 // classes which would be inaccessible otherwise.
300 env.enclMethod != null &&
301 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
302 break;
303 default: // error recovery
304 case PUBLIC:
305 isAccessible = true;
306 break;
307 case PROTECTED:
308 isAccessible =
309 env.toplevel.packge == c.owner // fast special case
310 ||
311 env.toplevel.packge == c.packge()
312 ||
313 isInnerSubClass(env.enclClass.sym, c.owner);
314 break;
315 }
316 return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
317 isAccessible :
318 isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
319 }
320 //where
321 /** Is given class a subclass of given base class, or an inner class
322 * of a subclass?
323 * Return null if no such class exists.
324 * @param c The class which is the subclass or is contained in it.
325 * @param base The base class
326 */
327 private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
328 while (c != null && !c.isSubClass(base, types)) {
329 c = c.owner.enclClass();
330 }
331 return c != null;
332 }
334 boolean isAccessible(Env<AttrContext> env, Type t) {
335 return isAccessible(env, t, false);
336 }
338 boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
339 return (t.hasTag(ARRAY))
340 ? isAccessible(env, types.elemtype(t))
341 : isAccessible(env, t.tsym, checkInner);
342 }
344 /** Is symbol accessible as a member of given type in given evironment?
345 * @param env The current environment.
346 * @param site The type of which the tested symbol is regarded
347 * as a member.
348 * @param sym The symbol.
349 */
350 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
351 return isAccessible(env, site, sym, false);
352 }
353 public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
354 if (sym.name == names.init && sym.owner != site.tsym) return false;
355 switch ((short)(sym.flags() & AccessFlags)) {
356 case PRIVATE:
357 return
358 (env.enclClass.sym == sym.owner // fast special case
359 ||
360 env.enclClass.sym.outermostClass() ==
361 sym.owner.outermostClass())
362 &&
363 sym.isInheritedIn(site.tsym, types);
364 case 0:
365 return
366 (env.toplevel.packge == sym.owner.owner // fast special case
367 ||
368 env.toplevel.packge == sym.packge())
369 &&
370 isAccessible(env, site, checkInner)
371 &&
372 sym.isInheritedIn(site.tsym, types)
373 &&
374 notOverriddenIn(site, sym);
375 case PROTECTED:
376 return
377 (env.toplevel.packge == sym.owner.owner // fast special case
378 ||
379 env.toplevel.packge == sym.packge()
380 ||
381 isProtectedAccessible(sym, env.enclClass.sym, site)
382 ||
383 // OK to select instance method or field from 'super' or type name
384 // (but type names should be disallowed elsewhere!)
385 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
386 &&
387 isAccessible(env, site, checkInner)
388 &&
389 notOverriddenIn(site, sym);
390 default: // this case includes erroneous combinations as well
391 return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
392 }
393 }
394 //where
395 /* `sym' is accessible only if not overridden by
396 * another symbol which is a member of `site'
397 * (because, if it is overridden, `sym' is not strictly
398 * speaking a member of `site'). A polymorphic signature method
399 * cannot be overridden (e.g. MH.invokeExact(Object[])).
400 */
401 private boolean notOverriddenIn(Type site, Symbol sym) {
402 if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
403 return true;
404 else {
405 Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
406 return (s2 == null || s2 == sym || sym.owner == s2.owner ||
407 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
408 }
409 }
410 //where
411 /** Is given protected symbol accessible if it is selected from given site
412 * and the selection takes place in given class?
413 * @param sym The symbol with protected access
414 * @param c The class where the access takes place
415 * @site The type of the qualifier
416 */
417 private
418 boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
419 while (c != null &&
420 !(c.isSubClass(sym.owner, types) &&
421 (c.flags() & INTERFACE) == 0 &&
422 // In JLS 2e 6.6.2.1, the subclass restriction applies
423 // only to instance fields and methods -- types are excluded
424 // regardless of whether they are declared 'static' or not.
425 ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
426 c = c.owner.enclClass();
427 return c != null;
428 }
430 /**
431 * Performs a recursive scan of a type looking for accessibility problems
432 * from current attribution environment
433 */
434 void checkAccessibleType(Env<AttrContext> env, Type t) {
435 accessibilityChecker.visit(t, env);
436 }
438 /**
439 * Accessibility type-visitor
440 */
441 Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
442 new Types.SimpleVisitor<Void, Env<AttrContext>>() {
444 void visit(List<Type> ts, Env<AttrContext> env) {
445 for (Type t : ts) {
446 visit(t, env);
447 }
448 }
450 public Void visitType(Type t, Env<AttrContext> env) {
451 return null;
452 }
454 @Override
455 public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
456 visit(t.elemtype, env);
457 return null;
458 }
460 @Override
461 public Void visitClassType(ClassType t, Env<AttrContext> env) {
462 visit(t.getTypeArguments(), env);
463 if (!isAccessible(env, t, true)) {
464 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
465 }
466 return null;
467 }
469 @Override
470 public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
471 visit(t.type, env);
472 return null;
473 }
475 @Override
476 public Void visitMethodType(MethodType t, Env<AttrContext> env) {
477 visit(t.getParameterTypes(), env);
478 visit(t.getReturnType(), env);
479 visit(t.getThrownTypes(), env);
480 return null;
481 }
482 };
484 /** Try to instantiate the type of a method so that it fits
485 * given type arguments and argument types. If succesful, return
486 * the method's instantiated type, else return null.
487 * The instantiation will take into account an additional leading
488 * formal parameter if the method is an instance method seen as a member
489 * of un underdetermined site In this case, we treat site as an additional
490 * parameter and the parameters of the class containing the method as
491 * additional type variables that get instantiated.
492 *
493 * @param env The current environment
494 * @param site The type of which the method is a member.
495 * @param m The method symbol.
496 * @param argtypes The invocation's given value arguments.
497 * @param typeargtypes The invocation's given type arguments.
498 * @param allowBoxing Allow boxing conversions of arguments.
499 * @param useVarargs Box trailing arguments into an array for varargs.
500 */
501 Type rawInstantiate(Env<AttrContext> env,
502 Type site,
503 Symbol m,
504 ResultInfo resultInfo,
505 List<Type> argtypes,
506 List<Type> typeargtypes,
507 boolean allowBoxing,
508 boolean useVarargs,
509 Warner warn) throws Infer.InferenceException {
511 Type mt = types.memberType(site, m);
512 // tvars is the list of formal type variables for which type arguments
513 // need to inferred.
514 List<Type> tvars = List.nil();
515 if (typeargtypes == null) typeargtypes = List.nil();
516 if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
517 // This is not a polymorphic method, but typeargs are supplied
518 // which is fine, see JLS 15.12.2.1
519 } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
520 ForAll pmt = (ForAll) mt;
521 if (typeargtypes.length() != pmt.tvars.length())
522 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
523 // Check type arguments are within bounds
524 List<Type> formals = pmt.tvars;
525 List<Type> actuals = typeargtypes;
526 while (formals.nonEmpty() && actuals.nonEmpty()) {
527 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
528 pmt.tvars, typeargtypes);
529 for (; bounds.nonEmpty(); bounds = bounds.tail)
530 if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
531 throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
532 formals = formals.tail;
533 actuals = actuals.tail;
534 }
535 mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
536 } else if (mt.hasTag(FORALL)) {
537 ForAll pmt = (ForAll) mt;
538 List<Type> tvars1 = types.newInstances(pmt.tvars);
539 tvars = tvars.appendList(tvars1);
540 mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
541 }
543 // find out whether we need to go the slow route via infer
544 boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
545 for (List<Type> l = argtypes;
546 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
547 l = l.tail) {
548 if (l.head.hasTag(FORALL)) instNeeded = true;
549 }
551 if (instNeeded)
552 return infer.instantiateMethod(env,
553 tvars,
554 (MethodType)mt,
555 resultInfo,
556 m,
557 argtypes,
558 allowBoxing,
559 useVarargs,
560 currentResolutionContext,
561 warn);
563 checkRawArgumentsAcceptable(env, m, argtypes, mt.getParameterTypes(),
564 allowBoxing, useVarargs, warn);
565 return mt;
566 }
568 Type checkMethod(Env<AttrContext> env,
569 Type site,
570 Symbol m,
571 ResultInfo resultInfo,
572 List<Type> argtypes,
573 List<Type> typeargtypes,
574 Warner warn) {
575 MethodResolutionContext prevContext = currentResolutionContext;
576 try {
577 currentResolutionContext = new MethodResolutionContext();
578 currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
579 MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
580 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
581 step.isBoxingRequired(), step.isVarargsRequired(), warn);
582 }
583 finally {
584 currentResolutionContext = prevContext;
585 }
586 }
588 /** Same but returns null instead throwing a NoInstanceException
589 */
590 Type instantiate(Env<AttrContext> env,
591 Type site,
592 Symbol m,
593 ResultInfo resultInfo,
594 List<Type> argtypes,
595 List<Type> typeargtypes,
596 boolean allowBoxing,
597 boolean useVarargs,
598 Warner warn) {
599 try {
600 return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
601 allowBoxing, useVarargs, warn);
602 } catch (InapplicableMethodException ex) {
603 return null;
604 }
605 }
607 /** Check if a parameter list accepts a list of args.
608 */
609 boolean argumentsAcceptable(Env<AttrContext> env,
610 Symbol msym,
611 List<Type> argtypes,
612 List<Type> formals,
613 boolean allowBoxing,
614 boolean useVarargs,
615 Warner warn) {
616 try {
617 checkRawArgumentsAcceptable(env, msym, argtypes, formals, allowBoxing, useVarargs, warn);
618 return true;
619 } catch (InapplicableMethodException ex) {
620 return false;
621 }
622 }
623 /**
624 * A check handler is used by the main method applicability routine in order
625 * to handle specific method applicability failures. It is assumed that a class
626 * implementing this interface should throw exceptions that are a subtype of
627 * InapplicableMethodException (see below). Such exception will terminate the
628 * method applicability check and propagate important info outwards (for the
629 * purpose of generating better diagnostics).
630 */
631 interface MethodCheckHandler {
632 /* The number of actuals and formals differ */
633 InapplicableMethodException arityMismatch();
634 /* An actual argument type does not conform to the corresponding formal type */
635 InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
636 /* The element type of a varargs is not accessible in the current context */
637 InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
638 }
640 /**
641 * Basic method check handler used within Resolve - all methods end up
642 * throwing InapplicableMethodException; a diagnostic fragment that describes
643 * the cause as to why the method is not applicable is set on the exception
644 * before it is thrown.
645 */
646 MethodCheckHandler resolveHandler = new MethodCheckHandler() {
647 public InapplicableMethodException arityMismatch() {
648 return inapplicableMethodException.setMessage("arg.length.mismatch");
649 }
650 public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
651 String key = varargs ?
652 "varargs.argument.mismatch" :
653 "no.conforming.assignment.exists";
654 return inapplicableMethodException.setMessage(key,
655 details);
656 }
657 public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
658 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
659 expected, Kinds.kindName(location), location);
660 }
661 };
663 void checkRawArgumentsAcceptable(Env<AttrContext> env,
664 Symbol msym,
665 List<Type> argtypes,
666 List<Type> formals,
667 boolean allowBoxing,
668 boolean useVarargs,
669 Warner warn) {
670 checkRawArgumentsAcceptable(env, msym, currentResolutionContext.attrMode(), infer.emptyContext, argtypes, formals,
671 allowBoxing, useVarargs, warn, resolveHandler);
672 }
674 /**
675 * Main method applicability routine. Given a list of actual types A,
676 * a list of formal types F, determines whether the types in A are
677 * compatible (by method invocation conversion) with the types in F.
678 *
679 * Since this routine is shared between overload resolution and method
680 * type-inference, a (possibly empty) inference context is used to convert
681 * formal types to the corresponding 'undet' form ahead of a compatibility
682 * check so that constraints can be propagated and collected.
683 *
684 * Moreover, if one or more types in A is a deferred type, this routine uses
685 * DeferredAttr in order to perform deferred attribution. If one or more actual
686 * deferred types are stuck, they are placed in a queue and revisited later
687 * after the remainder of the arguments have been seen. If this is not sufficient
688 * to 'unstuck' the argument, a cyclic inference error is called out.
689 *
690 * A method check handler (see above) is used in order to report errors.
691 */
692 void checkRawArgumentsAcceptable(final Env<AttrContext> env,
693 Symbol msym,
694 DeferredAttr.AttrMode mode,
695 final Infer.InferenceContext inferenceContext,
696 List<Type> argtypes,
697 List<Type> formals,
698 boolean allowBoxing,
699 boolean useVarargs,
700 Warner warn,
701 final MethodCheckHandler handler) {
702 Type varargsFormal = useVarargs ? formals.last() : null;
704 if (varargsFormal == null &&
705 argtypes.size() != formals.size()) {
706 throw handler.arityMismatch(); // not enough args
707 }
709 DeferredAttr.DeferredAttrContext deferredAttrContext =
710 deferredAttr.new DeferredAttrContext(mode, msym, currentResolutionContext.step, inferenceContext);
712 while (argtypes.nonEmpty() && formals.head != varargsFormal) {
713 ResultInfo mresult = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, deferredAttrContext, handler, warn);
714 mresult.check(null, argtypes.head);
715 argtypes = argtypes.tail;
716 formals = formals.tail;
717 }
719 if (formals.head != varargsFormal) {
720 throw handler.arityMismatch(); // not enough args
721 }
723 if (useVarargs) {
724 //note: if applicability check is triggered by most specific test,
725 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
726 final Type elt = types.elemtype(varargsFormal);
727 ResultInfo mresult = methodCheckResult(elt, allowBoxing, true, inferenceContext, deferredAttrContext, handler, warn);
728 while (argtypes.nonEmpty()) {
729 mresult.check(null, argtypes.head);
730 argtypes = argtypes.tail;
731 }
732 //check varargs element type accessibility
733 varargsAccessible(env, elt, handler, inferenceContext);
734 }
736 deferredAttrContext.complete();
737 }
739 void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
740 if (inferenceContext.free(t)) {
741 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
742 @Override
743 public void typesInferred(InferenceContext inferenceContext) {
744 varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
745 }
746 });
747 } else {
748 if (!isAccessible(env, t)) {
749 Symbol location = env.enclClass.sym;
750 throw handler.inaccessibleVarargs(location, t);
751 }
752 }
753 }
755 /**
756 * Check context to be used during method applicability checks. A method check
757 * context might contain inference variables.
758 */
759 abstract class MethodCheckContext implements CheckContext {
761 MethodCheckHandler handler;
762 boolean useVarargs;
763 Infer.InferenceContext inferenceContext;
764 DeferredAttrContext deferredAttrContext;
765 Warner rsWarner;
767 public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs,
768 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
769 this.handler = handler;
770 this.useVarargs = useVarargs;
771 this.inferenceContext = inferenceContext;
772 this.deferredAttrContext = deferredAttrContext;
773 this.rsWarner = rsWarner;
774 }
776 public void report(DiagnosticPosition pos, JCDiagnostic details) {
777 throw handler.argumentMismatch(useVarargs, details);
778 }
780 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
781 return rsWarner;
782 }
784 public InferenceContext inferenceContext() {
785 return inferenceContext;
786 }
788 public DeferredAttrContext deferredAttrContext() {
789 return deferredAttrContext;
790 }
791 }
793 /**
794 * Subclass of method check context class that implements strict method conversion.
795 * Strict method conversion checks compatibility between types using subtyping tests.
796 */
797 class StrictMethodContext extends MethodCheckContext {
799 public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs,
800 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
801 super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
802 }
804 public boolean compatible(Type found, Type req, Warner warn) {
805 return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
806 }
807 }
809 /**
810 * Subclass of method check context class that implements loose method conversion.
811 * Loose method conversion checks compatibility between types using method conversion tests.
812 */
813 class LooseMethodContext extends MethodCheckContext {
815 public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs,
816 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
817 super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
818 }
820 public boolean compatible(Type found, Type req, Warner warn) {
821 return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
822 }
823 }
825 /**
826 * Create a method check context to be used during method applicability check
827 */
828 ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
829 Infer.InferenceContext inferenceContext, DeferredAttr.DeferredAttrContext deferredAttrContext,
830 MethodCheckHandler methodHandler, Warner rsWarner) {
831 MethodCheckContext checkContext = allowBoxing ?
832 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner) :
833 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
834 return new MethodResultInfo(to, checkContext, deferredAttrContext);
835 }
837 class MethodResultInfo extends ResultInfo {
839 DeferredAttr.DeferredAttrContext deferredAttrContext;
841 public MethodResultInfo(Type pt, CheckContext checkContext, DeferredAttr.DeferredAttrContext deferredAttrContext) {
842 attr.super(VAL, pt, checkContext);
843 this.deferredAttrContext = deferredAttrContext;
844 }
846 @Override
847 protected Type check(DiagnosticPosition pos, Type found) {
848 if (found.hasTag(DEFERRED)) {
849 DeferredType dt = (DeferredType)found;
850 return dt.check(this);
851 } else {
852 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
853 }
854 }
856 @Override
857 protected MethodResultInfo dup(Type newPt) {
858 return new MethodResultInfo(newPt, checkContext, deferredAttrContext);
859 }
861 @Override
862 protected ResultInfo dup(CheckContext newContext) {
863 return new MethodResultInfo(pt, newContext, deferredAttrContext);
864 }
865 }
867 public static class InapplicableMethodException extends RuntimeException {
868 private static final long serialVersionUID = 0;
870 JCDiagnostic diagnostic;
871 JCDiagnostic.Factory diags;
873 InapplicableMethodException(JCDiagnostic.Factory diags) {
874 this.diagnostic = null;
875 this.diags = diags;
876 }
877 InapplicableMethodException setMessage() {
878 return setMessage((JCDiagnostic)null);
879 }
880 InapplicableMethodException setMessage(String key) {
881 return setMessage(key != null ? diags.fragment(key) : null);
882 }
883 InapplicableMethodException setMessage(String key, Object... args) {
884 return setMessage(key != null ? diags.fragment(key, args) : null);
885 }
886 InapplicableMethodException setMessage(JCDiagnostic diag) {
887 this.diagnostic = diag;
888 return this;
889 }
891 public JCDiagnostic getDiagnostic() {
892 return diagnostic;
893 }
894 }
895 private final InapplicableMethodException inapplicableMethodException;
897 /* ***************************************************************************
898 * Symbol lookup
899 * the following naming conventions for arguments are used
900 *
901 * env is the environment where the symbol was mentioned
902 * site is the type of which the symbol is a member
903 * name is the symbol's name
904 * if no arguments are given
905 * argtypes are the value arguments, if we search for a method
906 *
907 * If no symbol was found, a ResolveError detailing the problem is returned.
908 ****************************************************************************/
910 /** Find field. Synthetic fields are always skipped.
911 * @param env The current environment.
912 * @param site The original type from where the selection takes place.
913 * @param name The name of the field.
914 * @param c The class to search for the field. This is always
915 * a superclass or implemented interface of site's class.
916 */
917 Symbol findField(Env<AttrContext> env,
918 Type site,
919 Name name,
920 TypeSymbol c) {
921 while (c.type.hasTag(TYPEVAR))
922 c = c.type.getUpperBound().tsym;
923 Symbol bestSoFar = varNotFound;
924 Symbol sym;
925 Scope.Entry e = c.members().lookup(name);
926 while (e.scope != null) {
927 if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
928 return isAccessible(env, site, e.sym)
929 ? e.sym : new AccessError(env, site, e.sym);
930 }
931 e = e.next();
932 }
933 Type st = types.supertype(c.type);
934 if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
935 sym = findField(env, site, name, st.tsym);
936 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
937 }
938 for (List<Type> l = types.interfaces(c.type);
939 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
940 l = l.tail) {
941 sym = findField(env, site, name, l.head.tsym);
942 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
943 sym.owner != bestSoFar.owner)
944 bestSoFar = new AmbiguityError(bestSoFar, sym);
945 else if (sym.kind < bestSoFar.kind)
946 bestSoFar = sym;
947 }
948 return bestSoFar;
949 }
951 /** Resolve a field identifier, throw a fatal error if not found.
952 * @param pos The position to use for error reporting.
953 * @param env The environment current at the method invocation.
954 * @param site The type of the qualifying expression, in which
955 * identifier is searched.
956 * @param name The identifier's name.
957 */
958 public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
959 Type site, Name name) {
960 Symbol sym = findField(env, site, name, site.tsym);
961 if (sym.kind == VAR) return (VarSymbol)sym;
962 else throw new FatalError(
963 diags.fragment("fatal.err.cant.locate.field",
964 name));
965 }
967 /** Find unqualified variable or field with given name.
968 * Synthetic fields always skipped.
969 * @param env The current environment.
970 * @param name The name of the variable or field.
971 */
972 Symbol findVar(Env<AttrContext> env, Name name) {
973 Symbol bestSoFar = varNotFound;
974 Symbol sym;
975 Env<AttrContext> env1 = env;
976 boolean staticOnly = false;
977 while (env1.outer != null) {
978 if (isStatic(env1)) staticOnly = true;
979 Scope.Entry e = env1.info.scope.lookup(name);
980 while (e.scope != null &&
981 (e.sym.kind != VAR ||
982 (e.sym.flags_field & SYNTHETIC) != 0))
983 e = e.next();
984 sym = (e.scope != null)
985 ? e.sym
986 : findField(
987 env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
988 if (sym.exists()) {
989 if (staticOnly &&
990 sym.kind == VAR &&
991 sym.owner.kind == TYP &&
992 (sym.flags() & STATIC) == 0)
993 return new StaticError(sym);
994 else
995 return sym;
996 } else if (sym.kind < bestSoFar.kind) {
997 bestSoFar = sym;
998 }
1000 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1001 env1 = env1.outer;
1002 }
1004 sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1005 if (sym.exists())
1006 return sym;
1007 if (bestSoFar.exists())
1008 return bestSoFar;
1010 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1011 for (; e.scope != null; e = e.next()) {
1012 sym = e.sym;
1013 Type origin = e.getOrigin().owner.type;
1014 if (sym.kind == VAR) {
1015 if (e.sym.owner.type != origin)
1016 sym = sym.clone(e.getOrigin().owner);
1017 return isAccessible(env, origin, sym)
1018 ? sym : new AccessError(env, origin, sym);
1019 }
1020 }
1022 Symbol origin = null;
1023 e = env.toplevel.starImportScope.lookup(name);
1024 for (; e.scope != null; e = e.next()) {
1025 sym = e.sym;
1026 if (sym.kind != VAR)
1027 continue;
1028 // invariant: sym.kind == VAR
1029 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
1030 return new AmbiguityError(bestSoFar, sym);
1031 else if (bestSoFar.kind >= VAR) {
1032 origin = e.getOrigin().owner;
1033 bestSoFar = isAccessible(env, origin.type, sym)
1034 ? sym : new AccessError(env, origin.type, sym);
1035 }
1036 }
1037 if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1038 return bestSoFar.clone(origin);
1039 else
1040 return bestSoFar;
1041 }
1043 Warner noteWarner = new Warner();
1045 /** Select the best method for a call site among two choices.
1046 * @param env The current environment.
1047 * @param site The original type from where the
1048 * selection takes place.
1049 * @param argtypes The invocation's value arguments,
1050 * @param typeargtypes The invocation's type arguments,
1051 * @param sym Proposed new best match.
1052 * @param bestSoFar Previously found best match.
1053 * @param allowBoxing Allow boxing conversions of arguments.
1054 * @param useVarargs Box trailing arguments into an array for varargs.
1055 */
1056 @SuppressWarnings("fallthrough")
1057 Symbol selectBest(Env<AttrContext> env,
1058 Type site,
1059 List<Type> argtypes,
1060 List<Type> typeargtypes,
1061 Symbol sym,
1062 Symbol bestSoFar,
1063 boolean allowBoxing,
1064 boolean useVarargs,
1065 boolean operator) {
1066 if (sym.kind == ERR ||
1067 !sym.isInheritedIn(site.tsym, types) ||
1068 (useVarargs && (sym.flags() & VARARGS) == 0)) {
1069 return bestSoFar;
1070 }
1071 Assert.check(sym.kind < AMBIGUOUS);
1072 try {
1073 Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1074 allowBoxing, useVarargs, types.noWarnings);
1075 if (!operator)
1076 currentResolutionContext.addApplicableCandidate(sym, mt);
1077 } catch (InapplicableMethodException ex) {
1078 if (!operator)
1079 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1080 switch (bestSoFar.kind) {
1081 case ABSENT_MTH:
1082 return new InapplicableSymbolError(currentResolutionContext);
1083 case WRONG_MTH:
1084 if (operator) return bestSoFar;
1085 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1086 default:
1087 return bestSoFar;
1088 }
1089 }
1090 if (!isAccessible(env, site, sym)) {
1091 return (bestSoFar.kind == ABSENT_MTH)
1092 ? new AccessError(env, site, sym)
1093 : bestSoFar;
1094 }
1095 return (bestSoFar.kind > AMBIGUOUS)
1096 ? sym
1097 : mostSpecific(argtypes, sym, bestSoFar, env, site,
1098 allowBoxing && operator, useVarargs);
1099 }
1101 /* Return the most specific of the two methods for a call,
1102 * given that both are accessible and applicable.
1103 * @param m1 A new candidate for most specific.
1104 * @param m2 The previous most specific candidate.
1105 * @param env The current environment.
1106 * @param site The original type from where the selection
1107 * takes place.
1108 * @param allowBoxing Allow boxing conversions of arguments.
1109 * @param useVarargs Box trailing arguments into an array for varargs.
1110 */
1111 Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1112 Symbol m2,
1113 Env<AttrContext> env,
1114 final Type site,
1115 boolean allowBoxing,
1116 boolean useVarargs) {
1117 switch (m2.kind) {
1118 case MTH:
1119 if (m1 == m2) return m1;
1120 boolean m1SignatureMoreSpecific =
1121 signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1122 boolean m2SignatureMoreSpecific =
1123 signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1124 if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1125 Type mt1 = types.memberType(site, m1);
1126 Type mt2 = types.memberType(site, m2);
1127 if (!types.overrideEquivalent(mt1, mt2))
1128 return ambiguityError(m1, m2);
1130 // same signature; select (a) the non-bridge method, or
1131 // (b) the one that overrides the other, or (c) the concrete
1132 // one, or (d) merge both abstract signatures
1133 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1134 return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1136 // if one overrides or hides the other, use it
1137 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1138 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1139 if (types.asSuper(m1Owner.type, m2Owner) != null &&
1140 ((m1.owner.flags_field & INTERFACE) == 0 ||
1141 (m2.owner.flags_field & INTERFACE) != 0) &&
1142 m1.overrides(m2, m1Owner, types, false))
1143 return m1;
1144 if (types.asSuper(m2Owner.type, m1Owner) != null &&
1145 ((m2.owner.flags_field & INTERFACE) == 0 ||
1146 (m1.owner.flags_field & INTERFACE) != 0) &&
1147 m2.overrides(m1, m2Owner, types, false))
1148 return m2;
1149 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1150 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1151 if (m1Abstract && !m2Abstract) return m2;
1152 if (m2Abstract && !m1Abstract) return m1;
1153 // both abstract or both concrete
1154 if (!m1Abstract && !m2Abstract)
1155 return ambiguityError(m1, m2);
1156 // check that both signatures have the same erasure
1157 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
1158 m2.erasure(types).getParameterTypes()))
1159 return ambiguityError(m1, m2);
1160 // both abstract, neither overridden; merge throws clause and result type
1161 Type mst = mostSpecificReturnType(mt1, mt2);
1162 if (mst == null) {
1163 // Theoretically, this can't happen, but it is possible
1164 // due to error recovery or mixing incompatible class files
1165 return ambiguityError(m1, m2);
1166 }
1167 Symbol mostSpecific = mst == mt1 ? m1 : m2;
1168 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
1169 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
1170 MethodSymbol result = new MethodSymbol(
1171 mostSpecific.flags(),
1172 mostSpecific.name,
1173 newSig,
1174 mostSpecific.owner) {
1175 @Override
1176 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1177 if (origin == site.tsym)
1178 return this;
1179 else
1180 return super.implementation(origin, types, checkResult);
1181 }
1182 };
1183 return result;
1184 }
1185 if (m1SignatureMoreSpecific) return m1;
1186 if (m2SignatureMoreSpecific) return m2;
1187 return ambiguityError(m1, m2);
1188 case AMBIGUOUS:
1189 AmbiguityError e = (AmbiguityError)m2;
1190 Symbol err1 = mostSpecific(argtypes, m1, e.sym, env, site, allowBoxing, useVarargs);
1191 Symbol err2 = mostSpecific(argtypes, m1, e.sym2, env, site, allowBoxing, useVarargs);
1192 if (err1 == err2) return err1;
1193 if (err1 == e.sym && err2 == e.sym2) return m2;
1194 if (err1 instanceof AmbiguityError &&
1195 err2 instanceof AmbiguityError &&
1196 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
1197 return ambiguityError(m1, m2);
1198 else
1199 return ambiguityError(err1, err2);
1200 default:
1201 throw new AssertionError();
1202 }
1203 }
1204 //where
1205 private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1206 Symbol m12 = adjustVarargs(m1, m2, useVarargs);
1207 Symbol m22 = adjustVarargs(m2, m1, useVarargs);
1208 Type mtype1 = types.memberType(site, m12);
1209 Type mtype2 = types.memberType(site, m22);
1211 //check if invocation is more specific
1212 if (invocationMoreSpecific(env, site, m22, mtype1.getParameterTypes(), allowBoxing, useVarargs)) {
1213 return true;
1214 }
1216 //perform structural check
1218 List<Type> formals1 = mtype1.getParameterTypes();
1219 Type lastFormal1 = formals1.last();
1220 List<Type> formals2 = mtype2.getParameterTypes();
1221 Type lastFormal2 = formals2.last();
1222 ListBuffer<Type> newFormals = ListBuffer.lb();
1224 boolean hasStructuralPoly = false;
1225 for (Type actual : actuals) {
1226 //perform formal argument adaptation in case actuals > formals (varargs)
1227 Type f1 = formals1.isEmpty() ?
1228 lastFormal1 : formals1.head;
1229 Type f2 = formals2.isEmpty() ?
1230 lastFormal2 : formals2.head;
1232 //is this a structural actual argument?
1233 boolean isStructuralPoly = actual.hasTag(DEFERRED) &&
1234 (((DeferredType)actual).tree.hasTag(LAMBDA) ||
1235 ((DeferredType)actual).tree.hasTag(REFERENCE));
1237 Type newFormal = f1;
1239 if (isStructuralPoly) {
1240 //for structural arguments only - check that corresponding formals
1241 //are related - if so replace formal with <null>
1242 hasStructuralPoly = true;
1243 DeferredType dt = (DeferredType)actual;
1244 Type t1 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m1, currentResolutionContext.step).apply(dt);
1245 Type t2 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m2, currentResolutionContext.step).apply(dt);
1246 if (t1.isErroneous() || t2.isErroneous() || !isStructuralSubtype(t1, t2)) {
1247 //not structural subtypes - simply fail
1248 return false;
1249 } else {
1250 newFormal = syms.botType;
1251 }
1252 }
1254 newFormals.append(newFormal);
1255 if (newFormals.length() > mtype2.getParameterTypes().length()) {
1256 //expand m2's type so as to fit the new formal arity (varargs)
1257 m22.type = types.createMethodTypeWithParameters(m22.type, m22.type.getParameterTypes().append(f2));
1258 }
1260 formals1 = formals1.isEmpty() ? formals1 : formals1.tail;
1261 formals2 = formals2.isEmpty() ? formals2 : formals2.tail;
1262 }
1264 if (!hasStructuralPoly) {
1265 //if no structural actual was found, we're done
1266 return false;
1267 }
1268 //perform additional adaptation if actuals < formals (varargs)
1269 for (Type t : formals1) {
1270 newFormals.append(t);
1271 }
1272 //check if invocation (with tweaked args) is more specific
1273 return invocationMoreSpecific(env, site, m22, newFormals.toList(), allowBoxing, useVarargs);
1274 }
1275 //where
1276 private boolean invocationMoreSpecific(Env<AttrContext> env, Type site, Symbol m2, List<Type> argtypes1, boolean allowBoxing, boolean useVarargs) {
1277 noteWarner.clear();
1278 Type mst = instantiate(env, site, m2, null,
1279 types.lowerBounds(argtypes1), null,
1280 allowBoxing, false, noteWarner);
1281 return mst != null &&
1282 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1283 }
1284 //where
1285 private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
1286 List<Type> fromArgs = from.type.getParameterTypes();
1287 List<Type> toArgs = to.type.getParameterTypes();
1288 if (useVarargs &&
1289 (from.flags() & VARARGS) != 0 &&
1290 (to.flags() & VARARGS) != 0) {
1291 Type varargsTypeFrom = fromArgs.last();
1292 Type varargsTypeTo = toArgs.last();
1293 ListBuffer<Type> args = ListBuffer.lb();
1294 if (toArgs.length() < fromArgs.length()) {
1295 //if we are checking a varargs method 'from' against another varargs
1296 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
1297 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
1298 //until 'to' signature has the same arity as 'from')
1299 while (fromArgs.head != varargsTypeFrom) {
1300 args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
1301 fromArgs = fromArgs.tail;
1302 toArgs = toArgs.head == varargsTypeTo ?
1303 toArgs :
1304 toArgs.tail;
1305 }
1306 } else {
1307 //formal argument list is same as original list where last
1308 //argument (array type) is removed
1309 args.appendList(toArgs.reverse().tail.reverse());
1310 }
1311 //append varargs element type as last synthetic formal
1312 args.append(types.elemtype(varargsTypeTo));
1313 Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
1314 return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
1315 } else {
1316 return to;
1317 }
1318 }
1319 //where
1320 boolean isStructuralSubtype(Type s, Type t) {
1322 Type ret_s = types.findDescriptorType(s).getReturnType();
1323 Type ret_t = types.findDescriptorType(t).getReturnType();
1325 //covariant most specific check for function descriptor return type
1326 if (!types.isSubtype(ret_s, ret_t)) {
1327 return false;
1328 }
1330 List<Type> args_s = types.findDescriptorType(s).getParameterTypes();
1331 List<Type> args_t = types.findDescriptorType(t).getParameterTypes();
1333 //arity must be identical
1334 if (args_s.length() != args_t.length()) {
1335 return false;
1336 }
1338 //invariant most specific check for function descriptor parameter types
1339 if (!types.isSameTypes(args_t, args_s)) {
1340 return false;
1341 }
1343 return true;
1344 }
1345 //where
1346 Type mostSpecificReturnType(Type mt1, Type mt2) {
1347 Type rt1 = mt1.getReturnType();
1348 Type rt2 = mt2.getReturnType();
1350 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1351 //if both are generic methods, adjust return type ahead of subtyping check
1352 rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1353 }
1354 //first use subtyping, then return type substitutability
1355 if (types.isSubtype(rt1, rt2)) {
1356 return mt1;
1357 } else if (types.isSubtype(rt2, rt1)) {
1358 return mt2;
1359 } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1360 return mt1;
1361 } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1362 return mt2;
1363 } else {
1364 return null;
1365 }
1366 }
1367 //where
1368 Symbol ambiguityError(Symbol m1, Symbol m2) {
1369 if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1370 return (m1.flags() & CLASH) == 0 ? m1 : m2;
1371 } else {
1372 return new AmbiguityError(m1, m2);
1373 }
1374 }
1376 Symbol findMethodInScope(Env<AttrContext> env,
1377 Type site,
1378 Name name,
1379 List<Type> argtypes,
1380 List<Type> typeargtypes,
1381 Scope sc,
1382 Symbol bestSoFar,
1383 boolean allowBoxing,
1384 boolean useVarargs,
1385 boolean operator,
1386 boolean abstractok) {
1387 for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
1388 bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1389 bestSoFar, allowBoxing, useVarargs, operator);
1390 }
1391 return bestSoFar;
1392 }
1393 //where
1394 class LookupFilter implements Filter<Symbol> {
1396 boolean abstractOk;
1398 LookupFilter(boolean abstractOk) {
1399 this.abstractOk = abstractOk;
1400 }
1402 public boolean accepts(Symbol s) {
1403 long flags = s.flags();
1404 return s.kind == MTH &&
1405 (flags & SYNTHETIC) == 0 &&
1406 (abstractOk ||
1407 (flags & DEFAULT) != 0 ||
1408 (flags & ABSTRACT) == 0);
1409 }
1410 };
1412 /** Find best qualified method matching given name, type and value
1413 * arguments.
1414 * @param env The current environment.
1415 * @param site The original type from where the selection
1416 * takes place.
1417 * @param name The method's name.
1418 * @param argtypes The method's value arguments.
1419 * @param typeargtypes The method's type arguments
1420 * @param allowBoxing Allow boxing conversions of arguments.
1421 * @param useVarargs Box trailing arguments into an array for varargs.
1422 */
1423 Symbol findMethod(Env<AttrContext> env,
1424 Type site,
1425 Name name,
1426 List<Type> argtypes,
1427 List<Type> typeargtypes,
1428 boolean allowBoxing,
1429 boolean useVarargs,
1430 boolean operator) {
1431 Symbol bestSoFar = methodNotFound;
1432 bestSoFar = findMethod(env,
1433 site,
1434 name,
1435 argtypes,
1436 typeargtypes,
1437 site.tsym.type,
1438 bestSoFar,
1439 allowBoxing,
1440 useVarargs,
1441 operator);
1442 reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
1443 return bestSoFar;
1444 }
1445 // where
1446 private Symbol findMethod(Env<AttrContext> env,
1447 Type site,
1448 Name name,
1449 List<Type> argtypes,
1450 List<Type> typeargtypes,
1451 Type intype,
1452 Symbol bestSoFar,
1453 boolean allowBoxing,
1454 boolean useVarargs,
1455 boolean operator) {
1456 @SuppressWarnings({"unchecked","rawtypes"})
1457 List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1458 InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1459 for (TypeSymbol s : superclasses(intype)) {
1460 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1461 s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1462 if (name == names.init) return bestSoFar;
1463 iphase = (iphase == null) ? null : iphase.update(s, this);
1464 if (iphase != null) {
1465 for (Type itype : types.interfaces(s.type)) {
1466 itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1467 }
1468 }
1469 }
1471 Symbol concrete = bestSoFar.kind < ERR &&
1472 (bestSoFar.flags() & ABSTRACT) == 0 ?
1473 bestSoFar : methodNotFound;
1475 for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1476 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
1477 //keep searching for abstract methods
1478 for (Type itype : itypes[iphase2.ordinal()]) {
1479 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1480 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1481 (itype.tsym.flags() & DEFAULT) == 0) continue;
1482 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1483 itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1484 if (concrete != bestSoFar &&
1485 concrete.kind < ERR && bestSoFar.kind < ERR &&
1486 types.isSubSignature(concrete.type, bestSoFar.type)) {
1487 //this is an hack - as javac does not do full membership checks
1488 //most specific ends up comparing abstract methods that might have
1489 //been implemented by some concrete method in a subclass and,
1490 //because of raw override, it is possible for an abstract method
1491 //to be more specific than the concrete method - so we need
1492 //to explicitly call that out (see CR 6178365)
1493 bestSoFar = concrete;
1494 }
1495 }
1496 }
1497 return bestSoFar;
1498 }
1500 enum InterfaceLookupPhase {
1501 ABSTRACT_OK() {
1502 @Override
1503 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1504 //We should not look for abstract methods if receiver is a concrete class
1505 //(as concrete classes are expected to implement all abstracts coming
1506 //from superinterfaces)
1507 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1508 return this;
1509 } else if (rs.allowDefaultMethods) {
1510 return DEFAULT_OK;
1511 } else {
1512 return null;
1513 }
1514 }
1515 },
1516 DEFAULT_OK() {
1517 @Override
1518 InterfaceLookupPhase update(Symbol s, Resolve rs) {
1519 return this;
1520 }
1521 };
1523 abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1524 }
1526 /**
1527 * Return an Iterable object to scan the superclasses of a given type.
1528 * It's crucial that the scan is done lazily, as we don't want to accidentally
1529 * access more supertypes than strictly needed (as this could trigger completion
1530 * errors if some of the not-needed supertypes are missing/ill-formed).
1531 */
1532 Iterable<TypeSymbol> superclasses(final Type intype) {
1533 return new Iterable<TypeSymbol>() {
1534 public Iterator<TypeSymbol> iterator() {
1535 return new Iterator<TypeSymbol>() {
1537 List<TypeSymbol> seen = List.nil();
1538 TypeSymbol currentSym = symbolFor(intype);
1539 TypeSymbol prevSym = null;
1541 public boolean hasNext() {
1542 if (currentSym == syms.noSymbol) {
1543 currentSym = symbolFor(types.supertype(prevSym.type));
1544 }
1545 return currentSym != null;
1546 }
1548 public TypeSymbol next() {
1549 prevSym = currentSym;
1550 currentSym = syms.noSymbol;
1551 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1552 return prevSym;
1553 }
1555 public void remove() {
1556 throw new UnsupportedOperationException();
1557 }
1559 TypeSymbol symbolFor(Type t) {
1560 if (!t.hasTag(CLASS) &&
1561 !t.hasTag(TYPEVAR)) {
1562 return null;
1563 }
1564 while (t.hasTag(TYPEVAR))
1565 t = t.getUpperBound();
1566 if (seen.contains(t.tsym)) {
1567 //degenerate case in which we have a circular
1568 //class hierarchy - because of ill-formed classfiles
1569 return null;
1570 }
1571 seen = seen.prepend(t.tsym);
1572 return t.tsym;
1573 }
1574 };
1575 }
1576 };
1577 }
1579 /** Find unqualified method matching given name, type and value arguments.
1580 * @param env The current environment.
1581 * @param name The method's name.
1582 * @param argtypes The method's value arguments.
1583 * @param typeargtypes The method's type arguments.
1584 * @param allowBoxing Allow boxing conversions of arguments.
1585 * @param useVarargs Box trailing arguments into an array for varargs.
1586 */
1587 Symbol findFun(Env<AttrContext> env, Name name,
1588 List<Type> argtypes, List<Type> typeargtypes,
1589 boolean allowBoxing, boolean useVarargs) {
1590 Symbol bestSoFar = methodNotFound;
1591 Symbol sym;
1592 Env<AttrContext> env1 = env;
1593 boolean staticOnly = false;
1594 while (env1.outer != null) {
1595 if (isStatic(env1)) staticOnly = true;
1596 sym = findMethod(
1597 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1598 allowBoxing, useVarargs, false);
1599 if (sym.exists()) {
1600 if (staticOnly &&
1601 sym.kind == MTH &&
1602 sym.owner.kind == TYP &&
1603 (sym.flags() & STATIC) == 0) return new StaticError(sym);
1604 else return sym;
1605 } else if (sym.kind < bestSoFar.kind) {
1606 bestSoFar = sym;
1607 }
1608 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1609 env1 = env1.outer;
1610 }
1612 sym = findMethod(env, syms.predefClass.type, name, argtypes,
1613 typeargtypes, allowBoxing, useVarargs, false);
1614 if (sym.exists())
1615 return sym;
1617 Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
1618 for (; e.scope != null; e = e.next()) {
1619 sym = e.sym;
1620 Type origin = e.getOrigin().owner.type;
1621 if (sym.kind == MTH) {
1622 if (e.sym.owner.type != origin)
1623 sym = sym.clone(e.getOrigin().owner);
1624 if (!isAccessible(env, origin, sym))
1625 sym = new AccessError(env, origin, sym);
1626 bestSoFar = selectBest(env, origin,
1627 argtypes, typeargtypes,
1628 sym, bestSoFar,
1629 allowBoxing, useVarargs, false);
1630 }
1631 }
1632 if (bestSoFar.exists())
1633 return bestSoFar;
1635 e = env.toplevel.starImportScope.lookup(name);
1636 for (; e.scope != null; e = e.next()) {
1637 sym = e.sym;
1638 Type origin = e.getOrigin().owner.type;
1639 if (sym.kind == MTH) {
1640 if (e.sym.owner.type != origin)
1641 sym = sym.clone(e.getOrigin().owner);
1642 if (!isAccessible(env, origin, sym))
1643 sym = new AccessError(env, origin, sym);
1644 bestSoFar = selectBest(env, origin,
1645 argtypes, typeargtypes,
1646 sym, bestSoFar,
1647 allowBoxing, useVarargs, false);
1648 }
1649 }
1650 return bestSoFar;
1651 }
1653 /** Load toplevel or member class with given fully qualified name and
1654 * verify that it is accessible.
1655 * @param env The current environment.
1656 * @param name The fully qualified name of the class to be loaded.
1657 */
1658 Symbol loadClass(Env<AttrContext> env, Name name) {
1659 try {
1660 ClassSymbol c = reader.loadClass(name);
1661 return isAccessible(env, c) ? c : new AccessError(c);
1662 } catch (ClassReader.BadClassFile err) {
1663 throw err;
1664 } catch (CompletionFailure ex) {
1665 return typeNotFound;
1666 }
1667 }
1669 /** Find qualified member type.
1670 * @param env The current environment.
1671 * @param site The original type from where the selection takes
1672 * place.
1673 * @param name The type's name.
1674 * @param c The class to search for the member type. This is
1675 * always a superclass or implemented interface of
1676 * site's class.
1677 */
1678 Symbol findMemberType(Env<AttrContext> env,
1679 Type site,
1680 Name name,
1681 TypeSymbol c) {
1682 Symbol bestSoFar = typeNotFound;
1683 Symbol sym;
1684 Scope.Entry e = c.members().lookup(name);
1685 while (e.scope != null) {
1686 if (e.sym.kind == TYP) {
1687 return isAccessible(env, site, e.sym)
1688 ? e.sym
1689 : new AccessError(env, site, e.sym);
1690 }
1691 e = e.next();
1692 }
1693 Type st = types.supertype(c.type);
1694 if (st != null && st.hasTag(CLASS)) {
1695 sym = findMemberType(env, site, name, st.tsym);
1696 if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1697 }
1698 for (List<Type> l = types.interfaces(c.type);
1699 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1700 l = l.tail) {
1701 sym = findMemberType(env, site, name, l.head.tsym);
1702 if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
1703 sym.owner != bestSoFar.owner)
1704 bestSoFar = new AmbiguityError(bestSoFar, sym);
1705 else if (sym.kind < bestSoFar.kind)
1706 bestSoFar = sym;
1707 }
1708 return bestSoFar;
1709 }
1711 /** Find a global type in given scope and load corresponding class.
1712 * @param env The current environment.
1713 * @param scope The scope in which to look for the type.
1714 * @param name The type's name.
1715 */
1716 Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1717 Symbol bestSoFar = typeNotFound;
1718 for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
1719 Symbol sym = loadClass(env, e.sym.flatName());
1720 if (bestSoFar.kind == TYP && sym.kind == TYP &&
1721 bestSoFar != sym)
1722 return new AmbiguityError(bestSoFar, sym);
1723 else if (sym.kind < bestSoFar.kind)
1724 bestSoFar = sym;
1725 }
1726 return bestSoFar;
1727 }
1729 /** Find an unqualified type symbol.
1730 * @param env The current environment.
1731 * @param name The type's name.
1732 */
1733 Symbol findType(Env<AttrContext> env, Name name) {
1734 Symbol bestSoFar = typeNotFound;
1735 Symbol sym;
1736 boolean staticOnly = false;
1737 for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
1738 if (isStatic(env1)) staticOnly = true;
1739 for (Scope.Entry e = env1.info.scope.lookup(name);
1740 e.scope != null;
1741 e = e.next()) {
1742 if (e.sym.kind == TYP) {
1743 if (staticOnly &&
1744 e.sym.type.hasTag(TYPEVAR) &&
1745 e.sym.owner.kind == TYP) return new StaticError(e.sym);
1746 return e.sym;
1747 }
1748 }
1750 sym = findMemberType(env1, env1.enclClass.sym.type, name,
1751 env1.enclClass.sym);
1752 if (staticOnly && sym.kind == TYP &&
1753 sym.type.hasTag(CLASS) &&
1754 sym.type.getEnclosingType().hasTag(CLASS) &&
1755 env1.enclClass.sym.type.isParameterized() &&
1756 sym.type.getEnclosingType().isParameterized())
1757 return new StaticError(sym);
1758 else if (sym.exists()) return sym;
1759 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1761 JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
1762 if ((encl.sym.flags() & STATIC) != 0)
1763 staticOnly = true;
1764 }
1766 if (!env.tree.hasTag(IMPORT)) {
1767 sym = findGlobalType(env, env.toplevel.namedImportScope, name);
1768 if (sym.exists()) return sym;
1769 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1771 sym = findGlobalType(env, env.toplevel.packge.members(), name);
1772 if (sym.exists()) return sym;
1773 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1775 sym = findGlobalType(env, env.toplevel.starImportScope, name);
1776 if (sym.exists()) return sym;
1777 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1778 }
1780 return bestSoFar;
1781 }
1783 /** Find an unqualified identifier which matches a specified kind set.
1784 * @param env The current environment.
1785 * @param name The identifier's name.
1786 * @param kind Indicates the possible symbol kinds
1787 * (a subset of VAL, TYP, PCK).
1788 */
1789 Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
1790 Symbol bestSoFar = typeNotFound;
1791 Symbol sym;
1793 if ((kind & VAR) != 0) {
1794 sym = findVar(env, name);
1795 if (sym.exists()) return sym;
1796 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1797 }
1799 if ((kind & TYP) != 0) {
1800 sym = findType(env, name);
1801 if (sym.exists()) return sym;
1802 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1803 }
1805 if ((kind & PCK) != 0) return reader.enterPackage(name);
1806 else return bestSoFar;
1807 }
1809 /** Find an identifier in a package which matches a specified kind set.
1810 * @param env The current environment.
1811 * @param name The identifier's name.
1812 * @param kind Indicates the possible symbol kinds
1813 * (a nonempty subset of TYP, PCK).
1814 */
1815 Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1816 Name name, int kind) {
1817 Name fullname = TypeSymbol.formFullName(name, pck);
1818 Symbol bestSoFar = typeNotFound;
1819 PackageSymbol pack = null;
1820 if ((kind & PCK) != 0) {
1821 pack = reader.enterPackage(fullname);
1822 if (pack.exists()) return pack;
1823 }
1824 if ((kind & TYP) != 0) {
1825 Symbol sym = loadClass(env, fullname);
1826 if (sym.exists()) {
1827 // don't allow programs to use flatnames
1828 if (name == sym.name) return sym;
1829 }
1830 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1831 }
1832 return (pack != null) ? pack : bestSoFar;
1833 }
1835 /** Find an identifier among the members of a given type `site'.
1836 * @param env The current environment.
1837 * @param site The type containing the symbol to be found.
1838 * @param name The identifier's name.
1839 * @param kind Indicates the possible symbol kinds
1840 * (a subset of VAL, TYP).
1841 */
1842 Symbol findIdentInType(Env<AttrContext> env, Type site,
1843 Name name, int kind) {
1844 Symbol bestSoFar = typeNotFound;
1845 Symbol sym;
1846 if ((kind & VAR) != 0) {
1847 sym = findField(env, site, name, site.tsym);
1848 if (sym.exists()) return sym;
1849 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1850 }
1852 if ((kind & TYP) != 0) {
1853 sym = findMemberType(env, site, name, site.tsym);
1854 if (sym.exists()) return sym;
1855 else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1856 }
1857 return bestSoFar;
1858 }
1860 /* ***************************************************************************
1861 * Access checking
1862 * The following methods convert ResolveErrors to ErrorSymbols, issuing
1863 * an error message in the process
1864 ****************************************************************************/
1866 /** If `sym' is a bad symbol: report error and return errSymbol
1867 * else pass through unchanged,
1868 * additional arguments duplicate what has been used in trying to find the
1869 * symbol {@literal (--> flyweight pattern)}. This improves performance since we
1870 * expect misses to happen frequently.
1871 *
1872 * @param sym The symbol that was found, or a ResolveError.
1873 * @param pos The position to use for error reporting.
1874 * @param location The symbol the served as a context for this lookup
1875 * @param site The original type from where the selection took place.
1876 * @param name The symbol's name.
1877 * @param qualified Did we get here through a qualified expression resolution?
1878 * @param argtypes The invocation's value arguments,
1879 * if we looked for a method.
1880 * @param typeargtypes The invocation's type arguments,
1881 * if we looked for a method.
1882 * @param logResolveHelper helper class used to log resolve errors
1883 */
1884 Symbol accessInternal(Symbol sym,
1885 DiagnosticPosition pos,
1886 Symbol location,
1887 Type site,
1888 Name name,
1889 boolean qualified,
1890 List<Type> argtypes,
1891 List<Type> typeargtypes,
1892 LogResolveHelper logResolveHelper) {
1893 if (sym.kind >= AMBIGUOUS) {
1894 ResolveError errSym = (ResolveError)sym;
1895 sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
1896 argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
1897 if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
1898 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
1899 }
1900 }
1901 return sym;
1902 }
1904 /**
1905 * Variant of the generalized access routine, to be used for generating method
1906 * resolution diagnostics
1907 */
1908 Symbol accessMethod(Symbol sym,
1909 DiagnosticPosition pos,
1910 Symbol location,
1911 Type site,
1912 Name name,
1913 boolean qualified,
1914 List<Type> argtypes,
1915 List<Type> typeargtypes) {
1916 return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
1917 }
1919 /** Same as original accessMethod(), but without location.
1920 */
1921 Symbol accessMethod(Symbol sym,
1922 DiagnosticPosition pos,
1923 Type site,
1924 Name name,
1925 boolean qualified,
1926 List<Type> argtypes,
1927 List<Type> typeargtypes) {
1928 return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
1929 }
1931 /**
1932 * Variant of the generalized access routine, to be used for generating variable,
1933 * type resolution diagnostics
1934 */
1935 Symbol accessBase(Symbol sym,
1936 DiagnosticPosition pos,
1937 Symbol location,
1938 Type site,
1939 Name name,
1940 boolean qualified) {
1941 return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
1942 }
1944 /** Same as original accessBase(), but without location.
1945 */
1946 Symbol accessBase(Symbol sym,
1947 DiagnosticPosition pos,
1948 Type site,
1949 Name name,
1950 boolean qualified) {
1951 return accessBase(sym, pos, site.tsym, site, name, qualified);
1952 }
1954 interface LogResolveHelper {
1955 boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
1956 List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
1957 }
1959 LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
1960 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1961 return !site.isErroneous();
1962 }
1963 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1964 return argtypes;
1965 }
1966 };
1968 LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
1969 public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
1970 return !site.isErroneous() &&
1971 !Type.isErroneous(argtypes) &&
1972 (typeargtypes == null || !Type.isErroneous(typeargtypes));
1973 }
1974 public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
1975 return (syms.operatorNames.contains(name)) ?
1976 argtypes :
1977 Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
1978 }
1980 class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
1982 public ResolveDeferredRecoveryMap(Symbol msym) {
1983 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
1984 }
1986 @Override
1987 protected Type typeOf(DeferredType dt) {
1988 Type res = super.typeOf(dt);
1989 if (!res.isErroneous()) {
1990 switch (TreeInfo.skipParens(dt.tree).getTag()) {
1991 case LAMBDA:
1992 case REFERENCE:
1993 return dt;
1994 case CONDEXPR:
1995 return res == Type.recoveryType ?
1996 dt : res;
1997 }
1998 }
1999 return res;
2000 }
2001 }
2002 };
2004 /** Check that sym is not an abstract method.
2005 */
2006 void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2007 if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2008 log.error(pos, "abstract.cant.be.accessed.directly",
2009 kindName(sym), sym, sym.location());
2010 }
2012 /* ***************************************************************************
2013 * Debugging
2014 ****************************************************************************/
2016 /** print all scopes starting with scope s and proceeding outwards.
2017 * used for debugging.
2018 */
2019 public void printscopes(Scope s) {
2020 while (s != null) {
2021 if (s.owner != null)
2022 System.err.print(s.owner + ": ");
2023 for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
2024 if ((e.sym.flags() & ABSTRACT) != 0)
2025 System.err.print("abstract ");
2026 System.err.print(e.sym + " ");
2027 }
2028 System.err.println();
2029 s = s.next;
2030 }
2031 }
2033 void printscopes(Env<AttrContext> env) {
2034 while (env.outer != null) {
2035 System.err.println("------------------------------");
2036 printscopes(env.info.scope);
2037 env = env.outer;
2038 }
2039 }
2041 public void printscopes(Type t) {
2042 while (t.hasTag(CLASS)) {
2043 printscopes(t.tsym.members());
2044 t = types.supertype(t);
2045 }
2046 }
2048 /* ***************************************************************************
2049 * Name resolution
2050 * Naming conventions are as for symbol lookup
2051 * Unlike the find... methods these methods will report access errors
2052 ****************************************************************************/
2054 /** Resolve an unqualified (non-method) identifier.
2055 * @param pos The position to use for error reporting.
2056 * @param env The environment current at the identifier use.
2057 * @param name The identifier's name.
2058 * @param kind The set of admissible symbol kinds for the identifier.
2059 */
2060 Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2061 Name name, int kind) {
2062 return accessBase(
2063 findIdent(env, name, kind),
2064 pos, env.enclClass.sym.type, name, false);
2065 }
2067 /** Resolve an unqualified method identifier.
2068 * @param pos The position to use for error reporting.
2069 * @param env The environment current at the method invocation.
2070 * @param name The identifier's name.
2071 * @param argtypes The types of the invocation's value arguments.
2072 * @param typeargtypes The types of the invocation's type arguments.
2073 */
2074 Symbol resolveMethod(DiagnosticPosition pos,
2075 Env<AttrContext> env,
2076 Name name,
2077 List<Type> argtypes,
2078 List<Type> typeargtypes) {
2079 return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2080 @Override
2081 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2082 return findFun(env, name, argtypes, typeargtypes,
2083 phase.isBoxingRequired(),
2084 phase.isVarargsRequired());
2085 }
2086 });
2087 }
2089 /** Resolve a qualified method identifier
2090 * @param pos The position to use for error reporting.
2091 * @param env The environment current at the method invocation.
2092 * @param site The type of the qualifying expression, in which
2093 * identifier is searched.
2094 * @param name The identifier's name.
2095 * @param argtypes The types of the invocation's value arguments.
2096 * @param typeargtypes The types of the invocation's type arguments.
2097 */
2098 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2099 Type site, Name name, List<Type> argtypes,
2100 List<Type> typeargtypes) {
2101 return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2102 }
2103 Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2104 Symbol location, Type site, Name name, List<Type> argtypes,
2105 List<Type> typeargtypes) {
2106 return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2107 }
2108 private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2109 DiagnosticPosition pos, Env<AttrContext> env,
2110 Symbol location, Type site, Name name, List<Type> argtypes,
2111 List<Type> typeargtypes) {
2112 return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2113 @Override
2114 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2115 return findMethod(env, site, name, argtypes, typeargtypes,
2116 phase.isBoxingRequired(),
2117 phase.isVarargsRequired(), false);
2118 }
2119 @Override
2120 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2121 if (sym.kind >= AMBIGUOUS) {
2122 sym = super.access(env, pos, location, sym);
2123 } else if (allowMethodHandles) {
2124 MethodSymbol msym = (MethodSymbol)sym;
2125 if (msym.isSignaturePolymorphic(types)) {
2126 return findPolymorphicSignatureInstance(env, sym, argtypes);
2127 }
2128 }
2129 return sym;
2130 }
2131 });
2132 }
2134 /** Find or create an implicit method of exactly the given type (after erasure).
2135 * Searches in a side table, not the main scope of the site.
2136 * This emulates the lookup process required by JSR 292 in JVM.
2137 * @param env Attribution environment
2138 * @param spMethod signature polymorphic method - i.e. MH.invokeExact
2139 * @param argtypes The required argument types
2140 */
2141 Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2142 final Symbol spMethod,
2143 List<Type> argtypes) {
2144 Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2145 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2146 for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
2147 if (types.isSameType(mtype, sym.type)) {
2148 return sym;
2149 }
2150 }
2152 // create the desired method
2153 long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2154 Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2155 @Override
2156 public Symbol baseSymbol() {
2157 return spMethod;
2158 }
2159 };
2160 polymorphicSignatureScope.enter(msym);
2161 return msym;
2162 }
2164 /** Resolve a qualified method identifier, throw a fatal error if not
2165 * found.
2166 * @param pos The position to use for error reporting.
2167 * @param env The environment current at the method invocation.
2168 * @param site The type of the qualifying expression, in which
2169 * identifier is searched.
2170 * @param name The identifier's name.
2171 * @param argtypes The types of the invocation's value arguments.
2172 * @param typeargtypes The types of the invocation's type arguments.
2173 */
2174 public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2175 Type site, Name name,
2176 List<Type> argtypes,
2177 List<Type> typeargtypes) {
2178 MethodResolutionContext resolveContext = new MethodResolutionContext();
2179 resolveContext.internalResolution = true;
2180 Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2181 site, name, argtypes, typeargtypes);
2182 if (sym.kind == MTH) return (MethodSymbol)sym;
2183 else throw new FatalError(
2184 diags.fragment("fatal.err.cant.locate.meth",
2185 name));
2186 }
2188 /** Resolve constructor.
2189 * @param pos The position to use for error reporting.
2190 * @param env The environment current at the constructor invocation.
2191 * @param site The type of class for which a constructor is searched.
2192 * @param argtypes The types of the constructor invocation's value
2193 * arguments.
2194 * @param typeargtypes The types of the constructor invocation's type
2195 * arguments.
2196 */
2197 Symbol resolveConstructor(DiagnosticPosition pos,
2198 Env<AttrContext> env,
2199 Type site,
2200 List<Type> argtypes,
2201 List<Type> typeargtypes) {
2202 return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2203 }
2205 private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2206 final DiagnosticPosition pos,
2207 Env<AttrContext> env,
2208 Type site,
2209 List<Type> argtypes,
2210 List<Type> typeargtypes) {
2211 return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2212 @Override
2213 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2214 return findConstructor(pos, env, site, argtypes, typeargtypes,
2215 phase.isBoxingRequired(),
2216 phase.isVarargsRequired());
2217 }
2218 });
2219 }
2221 /** Resolve a constructor, throw a fatal error if not found.
2222 * @param pos The position to use for error reporting.
2223 * @param env The environment current at the method invocation.
2224 * @param site The type to be constructed.
2225 * @param argtypes The types of the invocation's value arguments.
2226 * @param typeargtypes The types of the invocation's type arguments.
2227 */
2228 public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2229 Type site,
2230 List<Type> argtypes,
2231 List<Type> typeargtypes) {
2232 MethodResolutionContext resolveContext = new MethodResolutionContext();
2233 resolveContext.internalResolution = true;
2234 Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2235 if (sym.kind == MTH) return (MethodSymbol)sym;
2236 else throw new FatalError(
2237 diags.fragment("fatal.err.cant.locate.ctor", site));
2238 }
2240 Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2241 Type site, List<Type> argtypes,
2242 List<Type> typeargtypes,
2243 boolean allowBoxing,
2244 boolean useVarargs) {
2245 Symbol sym = findMethod(env, site,
2246 names.init, argtypes,
2247 typeargtypes, allowBoxing,
2248 useVarargs, false);
2249 chk.checkDeprecated(pos, env.info.scope.owner, sym);
2250 return sym;
2251 }
2253 /** Resolve constructor using diamond inference.
2254 * @param pos The position to use for error reporting.
2255 * @param env The environment current at the constructor invocation.
2256 * @param site The type of class for which a constructor is searched.
2257 * The scope of this class has been touched in attribution.
2258 * @param argtypes The types of the constructor invocation's value
2259 * arguments.
2260 * @param typeargtypes The types of the constructor invocation's type
2261 * arguments.
2262 */
2263 Symbol resolveDiamond(DiagnosticPosition pos,
2264 Env<AttrContext> env,
2265 Type site,
2266 List<Type> argtypes,
2267 List<Type> typeargtypes) {
2268 return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2269 @Override
2270 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2271 return findDiamond(env, site, argtypes, typeargtypes,
2272 phase.isBoxingRequired(),
2273 phase.isVarargsRequired());
2274 }
2275 @Override
2276 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2277 if (sym.kind >= AMBIGUOUS) {
2278 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2279 ((InapplicableSymbolError)sym).errCandidate().details :
2280 null;
2281 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2282 @Override
2283 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2284 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2285 String key = details == null ?
2286 "cant.apply.diamond" :
2287 "cant.apply.diamond.1";
2288 return diags.create(dkind, log.currentSource(), pos, key,
2289 diags.fragment("diamond", site.tsym), details);
2290 }
2291 };
2292 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2293 env.info.pendingResolutionPhase = currentResolutionContext.step;
2294 }
2295 return sym;
2296 }
2297 });
2298 }
2300 /** This method scans all the constructor symbol in a given class scope -
2301 * assuming that the original scope contains a constructor of the kind:
2302 * {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2303 * a method check is executed against the modified constructor type:
2304 * {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2305 * inference. The inferred return type of the synthetic constructor IS
2306 * the inferred type for the diamond operator.
2307 */
2308 private Symbol findDiamond(Env<AttrContext> env,
2309 Type site,
2310 List<Type> argtypes,
2311 List<Type> typeargtypes,
2312 boolean allowBoxing,
2313 boolean useVarargs) {
2314 Symbol bestSoFar = methodNotFound;
2315 for (Scope.Entry e = site.tsym.members().lookup(names.init);
2316 e.scope != null;
2317 e = e.next()) {
2318 final Symbol sym = e.sym;
2319 //- System.out.println(" e " + e.sym);
2320 if (sym.kind == MTH &&
2321 (sym.flags_field & SYNTHETIC) == 0) {
2322 List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
2323 ((ForAll)sym.type).tvars :
2324 List.<Type>nil();
2325 Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2326 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2327 MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2328 @Override
2329 public Symbol baseSymbol() {
2330 return sym;
2331 }
2332 };
2333 bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2334 newConstr,
2335 bestSoFar,
2336 allowBoxing,
2337 useVarargs,
2338 false);
2339 }
2340 }
2341 return bestSoFar;
2342 }
2346 /** Resolve operator.
2347 * @param pos The position to use for error reporting.
2348 * @param optag The tag of the operation tree.
2349 * @param env The environment current at the operation.
2350 * @param argtypes The types of the operands.
2351 */
2352 Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2353 Env<AttrContext> env, List<Type> argtypes) {
2354 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2355 try {
2356 currentResolutionContext = new MethodResolutionContext();
2357 Name name = treeinfo.operatorName(optag);
2358 Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2359 null, false, false, true);
2360 if (boxingEnabled && sym.kind >= WRONG_MTHS)
2361 sym = findMethod(env, syms.predefClass.type, name, argtypes,
2362 null, true, false, true);
2363 return accessMethod(sym, pos, env.enclClass.sym.type, name,
2364 false, argtypes, null);
2365 }
2366 finally {
2367 currentResolutionContext = prevResolutionContext;
2368 }
2369 }
2371 /** Resolve operator.
2372 * @param pos The position to use for error reporting.
2373 * @param optag The tag of the operation tree.
2374 * @param env The environment current at the operation.
2375 * @param arg The type of the operand.
2376 */
2377 Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2378 return resolveOperator(pos, optag, env, List.of(arg));
2379 }
2381 /** Resolve binary operator.
2382 * @param pos The position to use for error reporting.
2383 * @param optag The tag of the operation tree.
2384 * @param env The environment current at the operation.
2385 * @param left The types of the left operand.
2386 * @param right The types of the right operand.
2387 */
2388 Symbol resolveBinaryOperator(DiagnosticPosition pos,
2389 JCTree.Tag optag,
2390 Env<AttrContext> env,
2391 Type left,
2392 Type right) {
2393 return resolveOperator(pos, optag, env, List.of(left, right));
2394 }
2396 /**
2397 * Resolution of member references is typically done as a single
2398 * overload resolution step, where the argument types A are inferred from
2399 * the target functional descriptor.
2400 *
2401 * If the member reference is a method reference with a type qualifier,
2402 * a two-step lookup process is performed. The first step uses the
2403 * expected argument list A, while the second step discards the first
2404 * type from A (which is treated as a receiver type).
2405 *
2406 * There are two cases in which inference is performed: (i) if the member
2407 * reference is a constructor reference and the qualifier type is raw - in
2408 * which case diamond inference is used to infer a parameterization for the
2409 * type qualifier; (ii) if the member reference is an unbound reference
2410 * where the type qualifier is raw - in that case, during the unbound lookup
2411 * the receiver argument type is used to infer an instantiation for the raw
2412 * qualifier type.
2413 *
2414 * When a multi-step resolution process is exploited, it is an error
2415 * if two candidates are found (ambiguity).
2416 *
2417 * This routine returns a pair (T,S), where S is the member reference symbol,
2418 * and T is the type of the class in which S is defined. This is necessary as
2419 * the type T might be dynamically inferred (i.e. if constructor reference
2420 * has a raw qualifier).
2421 */
2422 Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
2423 Env<AttrContext> env,
2424 JCMemberReference referenceTree,
2425 Type site,
2426 Name name, List<Type> argtypes,
2427 List<Type> typeargtypes,
2428 boolean boxingAllowed) {
2429 MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
2430 //step 1 - bound lookup
2431 ReferenceLookupHelper boundLookupHelper = name.equals(names.init) ?
2432 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase) :
2433 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2434 Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2435 Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
2437 //step 2 - unbound lookup
2438 ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
2439 Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2440 Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
2442 //merge results
2443 Pair<Symbol, ReferenceLookupHelper> res;
2444 if (unboundSym.kind != MTH) {
2445 res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
2446 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2447 } else if (boundSym.kind == MTH) {
2448 res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
2449 env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
2450 } else {
2451 res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
2452 env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
2453 }
2455 return res;
2456 }
2458 /**
2459 * Helper for defining custom method-like lookup logic; a lookup helper
2460 * provides hooks for (i) the actual lookup logic and (ii) accessing the
2461 * lookup result (this step might result in compiler diagnostics to be generated)
2462 */
2463 abstract class LookupHelper {
2465 /** name of the symbol to lookup */
2466 Name name;
2468 /** location in which the lookup takes place */
2469 Type site;
2471 /** actual types used during the lookup */
2472 List<Type> argtypes;
2474 /** type arguments used during the lookup */
2475 List<Type> typeargtypes;
2477 /** Max overload resolution phase handled by this helper */
2478 MethodResolutionPhase maxPhase;
2480 LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2481 this.name = name;
2482 this.site = site;
2483 this.argtypes = argtypes;
2484 this.typeargtypes = typeargtypes;
2485 this.maxPhase = maxPhase;
2486 }
2488 /**
2489 * Should lookup stop at given phase with given result
2490 */
2491 protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2492 return phase.ordinal() > maxPhase.ordinal() ||
2493 sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
2494 }
2496 /**
2497 * Search for a symbol under a given overload resolution phase - this method
2498 * is usually called several times, once per each overload resolution phase
2499 */
2500 abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
2502 /**
2503 * Validate the result of the lookup
2504 */
2505 abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
2506 }
2508 abstract class BasicLookupHelper extends LookupHelper {
2510 BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
2511 super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
2512 }
2514 @Override
2515 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2516 if (sym.kind >= AMBIGUOUS) {
2517 //if nothing is found return the 'first' error
2518 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
2519 }
2520 return sym;
2521 }
2522 }
2524 /**
2525 * Helper class for member reference lookup. A reference lookup helper
2526 * defines the basic logic for member reference lookup; a method gives
2527 * access to an 'unbound' helper used to perform an unbound member
2528 * reference lookup.
2529 */
2530 abstract class ReferenceLookupHelper extends LookupHelper {
2532 /** The member reference tree */
2533 JCMemberReference referenceTree;
2535 ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2536 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2537 super(name, site, argtypes, typeargtypes, maxPhase);
2538 this.referenceTree = referenceTree;
2540 }
2542 /**
2543 * Returns an unbound version of this lookup helper. By default, this
2544 * method returns an dummy lookup helper.
2545 */
2546 ReferenceLookupHelper unboundLookup() {
2547 //dummy loopkup helper that always return 'methodNotFound'
2548 return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
2549 @Override
2550 ReferenceLookupHelper unboundLookup() {
2551 return this;
2552 }
2553 @Override
2554 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2555 return methodNotFound;
2556 }
2557 @Override
2558 ReferenceKind referenceKind(Symbol sym) {
2559 Assert.error();
2560 return null;
2561 }
2562 };
2563 }
2565 /**
2566 * Get the kind of the member reference
2567 */
2568 abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
2570 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2571 //skip error reporting
2572 return sym;
2573 }
2574 }
2576 /**
2577 * Helper class for method reference lookup. The lookup logic is based
2578 * upon Resolve.findMethod; in certain cases, this helper class has a
2579 * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
2580 * In such cases, non-static lookup results are thrown away.
2581 */
2582 class MethodReferenceLookupHelper extends ReferenceLookupHelper {
2584 MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2585 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2586 super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2587 }
2589 protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
2590 return findMethod(env, site, name, argtypes, typeargtypes,
2591 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2592 }
2594 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2595 return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
2596 sym.kind != MTH ||
2597 sym.isStatic() ? sym : new StaticError(sym);
2598 }
2600 @Override
2601 final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2602 return adjustLookupResult(env, lookupReferenceInternal(env, phase));
2603 }
2605 @Override
2606 ReferenceLookupHelper unboundLookup() {
2607 if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
2608 argtypes.nonEmpty() &&
2609 types.isSubtypeUnchecked(argtypes.head, site)) {
2610 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
2611 site, argtypes, typeargtypes, maxPhase);
2612 } else {
2613 return super.unboundLookup();
2614 }
2615 }
2617 @Override
2618 ReferenceKind referenceKind(Symbol sym) {
2619 if (sym.isStatic()) {
2620 return ReferenceKind.STATIC;
2621 } else {
2622 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
2623 return selName != null && selName == names._super ?
2624 ReferenceKind.SUPER :
2625 ReferenceKind.BOUND;
2626 }
2627 }
2628 }
2630 /**
2631 * Helper class for unbound method reference lookup. Essentially the same
2632 * as the basic method reference lookup helper; main difference is that static
2633 * lookup results are thrown away. If qualifier type is raw, an attempt to
2634 * infer a parameterized type is made using the first actual argument (that
2635 * would otherwise be ignored during the lookup).
2636 */
2637 class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
2639 UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
2640 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2641 super(referenceTree, name,
2642 site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
2643 argtypes.tail, typeargtypes, maxPhase);
2644 }
2646 @Override
2647 protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
2648 return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
2649 }
2651 @Override
2652 ReferenceLookupHelper unboundLookup() {
2653 return this;
2654 }
2656 @Override
2657 ReferenceKind referenceKind(Symbol sym) {
2658 return ReferenceKind.UNBOUND;
2659 }
2660 }
2662 /**
2663 * Helper class for constructor reference lookup. The lookup logic is based
2664 * upon either Resolve.findMethod or Resolve.findDiamond - depending on
2665 * whether the constructor reference needs diamond inference (this is the case
2666 * if the qualifier type is raw). A special erroneous symbol is returned
2667 * if the lookup returns the constructor of an inner class and there's no
2668 * enclosing instance in scope.
2669 */
2670 class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
2672 boolean needsInference;
2674 ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
2675 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2676 super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
2677 if (site.isRaw()) {
2678 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
2679 needsInference = true;
2680 }
2681 }
2683 @Override
2684 protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2685 Symbol sym = needsInference ?
2686 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
2687 findMethod(env, site, name, argtypes, typeargtypes,
2688 phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
2689 return sym.kind != MTH ||
2690 site.getEnclosingType().hasTag(NONE) ||
2691 hasEnclosingInstance(env, site) ?
2692 sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
2693 @Override
2694 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2695 return diags.create(dkind, log.currentSource(), pos,
2696 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
2697 }
2698 };
2699 }
2701 @Override
2702 ReferenceKind referenceKind(Symbol sym) {
2703 return site.getEnclosingType().hasTag(NONE) ?
2704 ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
2705 }
2706 }
2708 /**
2709 * Main overload resolution routine. On each overload resolution step, a
2710 * lookup helper class is used to perform the method/constructor lookup;
2711 * at the end of the lookup, the helper is used to validate the results
2712 * (this last step might trigger overload resolution diagnostics).
2713 */
2714 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
2715 return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
2716 }
2718 Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
2719 MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
2720 MethodResolutionContext prevResolutionContext = currentResolutionContext;
2721 try {
2722 Symbol bestSoFar = methodNotFound;
2723 currentResolutionContext = resolveContext;
2724 for (MethodResolutionPhase phase : methodResolutionSteps) {
2725 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
2726 lookupHelper.shouldStop(bestSoFar, phase)) break;
2727 MethodResolutionPhase prevPhase = currentResolutionContext.step;
2728 Symbol prevBest = bestSoFar;
2729 currentResolutionContext.step = phase;
2730 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
2731 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
2732 }
2733 return lookupHelper.access(env, pos, location, bestSoFar);
2734 } finally {
2735 currentResolutionContext = prevResolutionContext;
2736 }
2737 }
2739 /**
2740 * Resolve `c.name' where name == this or name == super.
2741 * @param pos The position to use for error reporting.
2742 * @param env The environment current at the expression.
2743 * @param c The qualifier.
2744 * @param name The identifier's name.
2745 */
2746 Symbol resolveSelf(DiagnosticPosition pos,
2747 Env<AttrContext> env,
2748 TypeSymbol c,
2749 Name name) {
2750 Env<AttrContext> env1 = env;
2751 boolean staticOnly = false;
2752 while (env1.outer != null) {
2753 if (isStatic(env1)) staticOnly = true;
2754 if (env1.enclClass.sym == c) {
2755 Symbol sym = env1.info.scope.lookup(name).sym;
2756 if (sym != null) {
2757 if (staticOnly) sym = new StaticError(sym);
2758 return accessBase(sym, pos, env.enclClass.sym.type,
2759 name, true);
2760 }
2761 }
2762 if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2763 env1 = env1.outer;
2764 }
2765 if (allowDefaultMethods && c.isInterface() &&
2766 name == names._super && !isStatic(env) &&
2767 types.isDirectSuperInterface(c, env.enclClass.sym)) {
2768 //this might be a default super call if one of the superinterfaces is 'c'
2769 for (Type t : pruneInterfaces(env.enclClass.type)) {
2770 if (t.tsym == c) {
2771 env.info.defaultSuperCallSite = t;
2772 return new VarSymbol(0, names._super,
2773 types.asSuper(env.enclClass.type, c), env.enclClass.sym);
2774 }
2775 }
2776 //find a direct superinterface that is a subtype of 'c'
2777 for (Type i : types.interfaces(env.enclClass.type)) {
2778 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
2779 log.error(pos, "illegal.default.super.call", c,
2780 diags.fragment("redundant.supertype", c, i));
2781 return syms.errSymbol;
2782 }
2783 }
2784 Assert.error();
2785 }
2786 log.error(pos, "not.encl.class", c);
2787 return syms.errSymbol;
2788 }
2789 //where
2790 private List<Type> pruneInterfaces(Type t) {
2791 ListBuffer<Type> result = ListBuffer.lb();
2792 for (Type t1 : types.interfaces(t)) {
2793 boolean shouldAdd = true;
2794 for (Type t2 : types.interfaces(t)) {
2795 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
2796 shouldAdd = false;
2797 }
2798 }
2799 if (shouldAdd) {
2800 result.append(t1);
2801 }
2802 }
2803 return result.toList();
2804 }
2807 /**
2808 * Resolve `c.this' for an enclosing class c that contains the
2809 * named member.
2810 * @param pos The position to use for error reporting.
2811 * @param env The environment current at the expression.
2812 * @param member The member that must be contained in the result.
2813 */
2814 Symbol resolveSelfContaining(DiagnosticPosition pos,
2815 Env<AttrContext> env,
2816 Symbol member,
2817 boolean isSuperCall) {
2818 Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
2819 if (sym == null) {
2820 log.error(pos, "encl.class.required", member);
2821 return syms.errSymbol;
2822 } else {
2823 return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
2824 }
2825 }
2827 boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
2828 Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
2829 return encl != null && encl.kind < ERRONEOUS;
2830 }
2832 private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
2833 Symbol member,
2834 boolean isSuperCall) {
2835 Name name = names._this;
2836 Env<AttrContext> env1 = isSuperCall ? env.outer : env;
2837 boolean staticOnly = false;
2838 if (env1 != null) {
2839 while (env1 != null && env1.outer != null) {
2840 if (isStatic(env1)) staticOnly = true;
2841 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
2842 Symbol sym = env1.info.scope.lookup(name).sym;
2843 if (sym != null) {
2844 if (staticOnly) sym = new StaticError(sym);
2845 return sym;
2846 }
2847 }
2848 if ((env1.enclClass.sym.flags() & STATIC) != 0)
2849 staticOnly = true;
2850 env1 = env1.outer;
2851 }
2852 }
2853 return null;
2854 }
2856 /**
2857 * Resolve an appropriate implicit this instance for t's container.
2858 * JLS 8.8.5.1 and 15.9.2
2859 */
2860 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
2861 return resolveImplicitThis(pos, env, t, false);
2862 }
2864 Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
2865 Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
2866 ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
2867 : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
2868 if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
2869 log.error(pos, "cant.ref.before.ctor.called", "this");
2870 return thisType;
2871 }
2873 /* ***************************************************************************
2874 * ResolveError classes, indicating error situations when accessing symbols
2875 ****************************************************************************/
2877 //used by TransTypes when checking target type of synthetic cast
2878 public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
2879 AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
2880 logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
2881 }
2882 //where
2883 private void logResolveError(ResolveError error,
2884 DiagnosticPosition pos,
2885 Symbol location,
2886 Type site,
2887 Name name,
2888 List<Type> argtypes,
2889 List<Type> typeargtypes) {
2890 JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
2891 pos, location, site, name, argtypes, typeargtypes);
2892 if (d != null) {
2893 d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
2894 log.report(d);
2895 }
2896 }
2898 private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
2900 public Object methodArguments(List<Type> argtypes) {
2901 if (argtypes == null || argtypes.isEmpty()) {
2902 return noArgs;
2903 } else {
2904 ListBuffer<Object> diagArgs = ListBuffer.lb();
2905 for (Type t : argtypes) {
2906 if (t.hasTag(DEFERRED)) {
2907 diagArgs.append(((DeferredAttr.DeferredType)t).tree);
2908 } else {
2909 diagArgs.append(t);
2910 }
2911 }
2912 return diagArgs;
2913 }
2914 }
2916 /**
2917 * Root class for resolution errors. Subclass of ResolveError
2918 * represent a different kinds of resolution error - as such they must
2919 * specify how they map into concrete compiler diagnostics.
2920 */
2921 abstract class ResolveError extends Symbol {
2923 /** The name of the kind of error, for debugging only. */
2924 final String debugName;
2926 ResolveError(int kind, String debugName) {
2927 super(kind, 0, null, null, null);
2928 this.debugName = debugName;
2929 }
2931 @Override
2932 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2933 throw new AssertionError();
2934 }
2936 @Override
2937 public String toString() {
2938 return debugName;
2939 }
2941 @Override
2942 public boolean exists() {
2943 return false;
2944 }
2946 /**
2947 * Create an external representation for this erroneous symbol to be
2948 * used during attribution - by default this returns the symbol of a
2949 * brand new error type which stores the original type found
2950 * during resolution.
2951 *
2952 * @param name the name used during resolution
2953 * @param location the location from which the symbol is accessed
2954 */
2955 protected Symbol access(Name name, TypeSymbol location) {
2956 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
2957 }
2959 /**
2960 * Create a diagnostic representing this resolution error.
2961 *
2962 * @param dkind The kind of the diagnostic to be created (e.g error).
2963 * @param pos The position to be used for error reporting.
2964 * @param site The original type from where the selection took place.
2965 * @param name The name of the symbol to be resolved.
2966 * @param argtypes The invocation's value arguments,
2967 * if we looked for a method.
2968 * @param typeargtypes The invocation's type arguments,
2969 * if we looked for a method.
2970 */
2971 abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
2972 DiagnosticPosition pos,
2973 Symbol location,
2974 Type site,
2975 Name name,
2976 List<Type> argtypes,
2977 List<Type> typeargtypes);
2978 }
2980 /**
2981 * This class is the root class of all resolution errors caused by
2982 * an invalid symbol being found during resolution.
2983 */
2984 abstract class InvalidSymbolError extends ResolveError {
2986 /** The invalid symbol found during resolution */
2987 Symbol sym;
2989 InvalidSymbolError(int kind, Symbol sym, String debugName) {
2990 super(kind, debugName);
2991 this.sym = sym;
2992 }
2994 @Override
2995 public boolean exists() {
2996 return true;
2997 }
2999 @Override
3000 public String toString() {
3001 return super.toString() + " wrongSym=" + sym;
3002 }
3004 @Override
3005 public Symbol access(Name name, TypeSymbol location) {
3006 if (sym.kind >= AMBIGUOUS)
3007 return ((ResolveError)sym).access(name, location);
3008 else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
3009 return types.createErrorType(name, location, sym.type).tsym;
3010 else
3011 return sym;
3012 }
3013 }
3015 /**
3016 * InvalidSymbolError error class indicating that a symbol matching a
3017 * given name does not exists in a given site.
3018 */
3019 class SymbolNotFoundError extends ResolveError {
3021 SymbolNotFoundError(int kind) {
3022 super(kind, "symbol not found error");
3023 }
3025 @Override
3026 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3027 DiagnosticPosition pos,
3028 Symbol location,
3029 Type site,
3030 Name name,
3031 List<Type> argtypes,
3032 List<Type> typeargtypes) {
3033 argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3034 typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3035 if (name == names.error)
3036 return null;
3038 if (syms.operatorNames.contains(name)) {
3039 boolean isUnaryOp = argtypes.size() == 1;
3040 String key = argtypes.size() == 1 ?
3041 "operator.cant.be.applied" :
3042 "operator.cant.be.applied.1";
3043 Type first = argtypes.head;
3044 Type second = !isUnaryOp ? argtypes.tail.head : null;
3045 return diags.create(dkind, log.currentSource(), pos,
3046 key, name, first, second);
3047 }
3048 boolean hasLocation = false;
3049 if (location == null) {
3050 location = site.tsym;
3051 }
3052 if (!location.name.isEmpty()) {
3053 if (location.kind == PCK && !site.tsym.exists()) {
3054 return diags.create(dkind, log.currentSource(), pos,
3055 "doesnt.exist", location);
3056 }
3057 hasLocation = !location.name.equals(names._this) &&
3058 !location.name.equals(names._super);
3059 }
3060 boolean isConstructor = kind == ABSENT_MTH && name == names.init;
3061 KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
3062 Name idname = isConstructor ? site.tsym.name : name;
3063 String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3064 if (hasLocation) {
3065 return diags.create(dkind, log.currentSource(), pos,
3066 errKey, kindname, idname, //symbol kindname, name
3067 typeargtypes, argtypes, //type parameters and arguments (if any)
3068 getLocationDiag(location, site)); //location kindname, type
3069 }
3070 else {
3071 return diags.create(dkind, log.currentSource(), pos,
3072 errKey, kindname, idname, //symbol kindname, name
3073 typeargtypes, argtypes); //type parameters and arguments (if any)
3074 }
3075 }
3076 //where
3077 private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3078 String key = "cant.resolve";
3079 String suffix = hasLocation ? ".location" : "";
3080 switch (kindname) {
3081 case METHOD:
3082 case CONSTRUCTOR: {
3083 suffix += ".args";
3084 suffix += hasTypeArgs ? ".params" : "";
3085 }
3086 }
3087 return key + suffix;
3088 }
3089 private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3090 if (location.kind == VAR) {
3091 return diags.fragment("location.1",
3092 kindName(location),
3093 location,
3094 location.type);
3095 } else {
3096 return diags.fragment("location",
3097 typeKindName(site),
3098 site,
3099 null);
3100 }
3101 }
3102 }
3104 /**
3105 * InvalidSymbolError error class indicating that a given symbol
3106 * (either a method, a constructor or an operand) is not applicable
3107 * given an actual arguments/type argument list.
3108 */
3109 class InapplicableSymbolError extends ResolveError {
3111 protected MethodResolutionContext resolveContext;
3113 InapplicableSymbolError(MethodResolutionContext context) {
3114 this(WRONG_MTH, "inapplicable symbol error", context);
3115 }
3117 protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
3118 super(kind, debugName);
3119 this.resolveContext = context;
3120 }
3122 @Override
3123 public String toString() {
3124 return super.toString();
3125 }
3127 @Override
3128 public boolean exists() {
3129 return true;
3130 }
3132 @Override
3133 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3134 DiagnosticPosition pos,
3135 Symbol location,
3136 Type site,
3137 Name name,
3138 List<Type> argtypes,
3139 List<Type> typeargtypes) {
3140 if (name == names.error)
3141 return null;
3143 if (syms.operatorNames.contains(name)) {
3144 boolean isUnaryOp = argtypes.size() == 1;
3145 String key = argtypes.size() == 1 ?
3146 "operator.cant.be.applied" :
3147 "operator.cant.be.applied.1";
3148 Type first = argtypes.head;
3149 Type second = !isUnaryOp ? argtypes.tail.head : null;
3150 return diags.create(dkind, log.currentSource(), pos,
3151 key, name, first, second);
3152 }
3153 else {
3154 Candidate c = errCandidate();
3155 Symbol ws = c.sym.asMemberOf(site, types);
3156 return diags.create(dkind, log.currentSource(), pos,
3157 "cant.apply.symbol",
3158 kindName(ws),
3159 ws.name == names.init ? ws.owner.name : ws.name,
3160 methodArguments(ws.type.getParameterTypes()),
3161 methodArguments(argtypes),
3162 kindName(ws.owner),
3163 ws.owner.type,
3164 c.details);
3165 }
3166 }
3168 @Override
3169 public Symbol access(Name name, TypeSymbol location) {
3170 return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3171 }
3173 private Candidate errCandidate() {
3174 Candidate bestSoFar = null;
3175 for (Candidate c : resolveContext.candidates) {
3176 if (c.isApplicable()) continue;
3177 bestSoFar = c;
3178 }
3179 Assert.checkNonNull(bestSoFar);
3180 return bestSoFar;
3181 }
3182 }
3184 /**
3185 * ResolveError error class indicating that a set of symbols
3186 * (either methods, constructors or operands) is not applicable
3187 * given an actual arguments/type argument list.
3188 */
3189 class InapplicableSymbolsError extends InapplicableSymbolError {
3191 InapplicableSymbolsError(MethodResolutionContext context) {
3192 super(WRONG_MTHS, "inapplicable symbols", context);
3193 }
3195 @Override
3196 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3197 DiagnosticPosition pos,
3198 Symbol location,
3199 Type site,
3200 Name name,
3201 List<Type> argtypes,
3202 List<Type> typeargtypes) {
3203 if (!resolveContext.candidates.isEmpty()) {
3204 JCDiagnostic err = diags.create(dkind,
3205 log.currentSource(),
3206 pos,
3207 "cant.apply.symbols",
3208 name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
3209 name == names.init ? site.tsym.name : name,
3210 methodArguments(argtypes));
3211 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
3212 } else {
3213 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3214 location, site, name, argtypes, typeargtypes);
3215 }
3216 }
3218 //where
3219 List<JCDiagnostic> candidateDetails(Type site) {
3220 Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
3221 for (Candidate c : resolveContext.candidates) {
3222 if (c.isApplicable()) continue;
3223 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3224 Kinds.kindName(c.sym),
3225 c.sym.location(site, types),
3226 c.sym.asMemberOf(site, types),
3227 c.details);
3228 details.put(c.sym, detailDiag);
3229 }
3230 return List.from(details.values());
3231 }
3232 }
3234 /**
3235 * An InvalidSymbolError error class indicating that a symbol is not
3236 * accessible from a given site
3237 */
3238 class AccessError extends InvalidSymbolError {
3240 private Env<AttrContext> env;
3241 private Type site;
3243 AccessError(Symbol sym) {
3244 this(null, null, sym);
3245 }
3247 AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3248 super(HIDDEN, sym, "access error");
3249 this.env = env;
3250 this.site = site;
3251 if (debugResolve)
3252 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3253 }
3255 @Override
3256 public boolean exists() {
3257 return false;
3258 }
3260 @Override
3261 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3262 DiagnosticPosition pos,
3263 Symbol location,
3264 Type site,
3265 Name name,
3266 List<Type> argtypes,
3267 List<Type> typeargtypes) {
3268 if (sym.owner.type.hasTag(ERROR))
3269 return null;
3271 if (sym.name == names.init && sym.owner != site.tsym) {
3272 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3273 pos, location, site, name, argtypes, typeargtypes);
3274 }
3275 else if ((sym.flags() & PUBLIC) != 0
3276 || (env != null && this.site != null
3277 && !isAccessible(env, this.site))) {
3278 return diags.create(dkind, log.currentSource(),
3279 pos, "not.def.access.class.intf.cant.access",
3280 sym, sym.location());
3281 }
3282 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3283 return diags.create(dkind, log.currentSource(),
3284 pos, "report.access", sym,
3285 asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3286 sym.location());
3287 }
3288 else {
3289 return diags.create(dkind, log.currentSource(),
3290 pos, "not.def.public.cant.access", sym, sym.location());
3291 }
3292 }
3293 }
3295 /**
3296 * InvalidSymbolError error class indicating that an instance member
3297 * has erroneously been accessed from a static context.
3298 */
3299 class StaticError extends InvalidSymbolError {
3301 StaticError(Symbol sym) {
3302 super(STATICERR, sym, "static error");
3303 }
3305 @Override
3306 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3307 DiagnosticPosition pos,
3308 Symbol location,
3309 Type site,
3310 Name name,
3311 List<Type> argtypes,
3312 List<Type> typeargtypes) {
3313 Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3314 ? types.erasure(sym.type).tsym
3315 : sym);
3316 return diags.create(dkind, log.currentSource(), pos,
3317 "non-static.cant.be.ref", kindName(sym), errSym);
3318 }
3319 }
3321 /**
3322 * InvalidSymbolError error class indicating that a pair of symbols
3323 * (either methods, constructors or operands) are ambiguous
3324 * given an actual arguments/type argument list.
3325 */
3326 class AmbiguityError extends InvalidSymbolError {
3328 /** The other maximally specific symbol */
3329 Symbol sym2;
3331 AmbiguityError(Symbol sym1, Symbol sym2) {
3332 super(AMBIGUOUS, sym1, "ambiguity error");
3333 this.sym2 = sym2;
3334 }
3336 @Override
3337 JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3338 DiagnosticPosition pos,
3339 Symbol location,
3340 Type site,
3341 Name name,
3342 List<Type> argtypes,
3343 List<Type> typeargtypes) {
3344 AmbiguityError pair = this;
3345 while (true) {
3346 if (pair.sym.kind == AMBIGUOUS)
3347 pair = (AmbiguityError)pair.sym;
3348 else if (pair.sym2.kind == AMBIGUOUS)
3349 pair = (AmbiguityError)pair.sym2;
3350 else break;
3351 }
3352 Name sname = pair.sym.name;
3353 if (sname == names.init) sname = pair.sym.owner.name;
3354 return diags.create(dkind, log.currentSource(),
3355 pos, "ref.ambiguous", sname,
3356 kindName(pair.sym),
3357 pair.sym,
3358 pair.sym.location(site, types),
3359 kindName(pair.sym2),
3360 pair.sym2,
3361 pair.sym2.location(site, types));
3362 }
3363 }
3365 enum MethodResolutionPhase {
3366 BASIC(false, false),
3367 BOX(true, false),
3368 VARARITY(true, true) {
3369 @Override
3370 public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
3371 switch (sym.kind) {
3372 case WRONG_MTH:
3373 return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
3374 bestSoFar :
3375 sym;
3376 case ABSENT_MTH:
3377 return bestSoFar;
3378 default:
3379 return sym;
3380 }
3381 }
3382 };
3384 final boolean isBoxingRequired;
3385 final boolean isVarargsRequired;
3387 MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
3388 this.isBoxingRequired = isBoxingRequired;
3389 this.isVarargsRequired = isVarargsRequired;
3390 }
3392 public boolean isBoxingRequired() {
3393 return isBoxingRequired;
3394 }
3396 public boolean isVarargsRequired() {
3397 return isVarargsRequired;
3398 }
3400 public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
3401 return (varargsEnabled || !isVarargsRequired) &&
3402 (boxingEnabled || !isBoxingRequired);
3403 }
3405 public Symbol mergeResults(Symbol prev, Symbol sym) {
3406 return sym;
3407 }
3408 }
3410 final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
3412 /**
3413 * A resolution context is used to keep track of intermediate results of
3414 * overload resolution, such as list of method that are not applicable
3415 * (used to generate more precise diagnostics) and so on. Resolution contexts
3416 * can be nested - this means that when each overload resolution routine should
3417 * work within the resolution context it created.
3418 */
3419 class MethodResolutionContext {
3421 private List<Candidate> candidates = List.nil();
3423 MethodResolutionPhase step = null;
3425 private boolean internalResolution = false;
3426 private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
3428 void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
3429 Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
3430 candidates = candidates.append(c);
3431 }
3433 void addApplicableCandidate(Symbol sym, Type mtype) {
3434 Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
3435 candidates = candidates.append(c);
3436 }
3438 /**
3439 * This class represents an overload resolution candidate. There are two
3440 * kinds of candidates: applicable methods and inapplicable methods;
3441 * applicable methods have a pointer to the instantiated method type,
3442 * while inapplicable candidates contain further details about the
3443 * reason why the method has been considered inapplicable.
3444 */
3445 class Candidate {
3447 final MethodResolutionPhase step;
3448 final Symbol sym;
3449 final JCDiagnostic details;
3450 final Type mtype;
3452 private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
3453 this.step = step;
3454 this.sym = sym;
3455 this.details = details;
3456 this.mtype = mtype;
3457 }
3459 @Override
3460 public boolean equals(Object o) {
3461 if (o instanceof Candidate) {
3462 Symbol s1 = this.sym;
3463 Symbol s2 = ((Candidate)o).sym;
3464 if ((s1 != s2 &&
3465 (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
3466 (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
3467 ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
3468 return true;
3469 }
3470 return false;
3471 }
3473 boolean isApplicable() {
3474 return mtype != null;
3475 }
3476 }
3478 DeferredAttr.AttrMode attrMode() {
3479 return attrMode;
3480 }
3482 boolean internal() {
3483 return internalResolution;
3484 }
3485 }
3487 MethodResolutionContext currentResolutionContext = null;
3488 }