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