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