001    /*
002     * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
003     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004     *
005     * This code is free software; you can redistribute it and/or modify it
006     * under the terms of the GNU General Public License version 2 only, as
007     * published by the Free Software Foundation.  Sun designates this
008     * particular file as subject to the "Classpath" exception as provided
009     * by Sun in the LICENSE file that accompanied this code.
010     *
011     * This code is distributed in the hope that it will be useful, but WITHOUT
012     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013     * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014     * version 2 for more details (a copy is included in the LICENSE file that
015     * accompanied this code).
016     *
017     * You should have received a copy of the GNU General Public License version
018     * 2 along with this work; if not, write to the Free Software Foundation,
019     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020     *
021     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022     * CA 95054 USA or visit www.sun.com if you need additional information or
023     * have any questions.
024     */
025    
026    package com.sun.tools.javac.comp;
027    
028    import com.sun.tools.javac.util.*;
029    import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
030    import com.sun.tools.javac.code.*;
031    import com.sun.tools.javac.jvm.*;
032    import com.sun.tools.javac.tree.*;
033    import com.sun.tools.javac.api.Formattable.LocalizedString;
034    import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
035    
036    import com.sun.tools.javac.code.Type.*;
037    import com.sun.tools.javac.code.Symbol.*;
038    import com.sun.tools.javac.tree.JCTree.*;
039    
040    import static com.sun.tools.javac.code.Flags.*;
041    import static com.sun.tools.javac.code.Kinds.*;
042    import static com.sun.tools.javac.code.TypeTags.*;
043    import javax.lang.model.element.ElementVisitor;
044    
045    import java.util.Map;
046    import java.util.HashMap;
047    
048    /** Helper class for name resolution, used mostly by the attribution phase.
049     *
050     *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
051     *  you write code that depends on this, you do so at your own risk.
052     *  This code and its internal interfaces are subject to change or
053     *  deletion without notice.</b>
054     */
055    public class Resolve {
056        protected static final Context.Key<Resolve> resolveKey =
057            new Context.Key<Resolve>();
058    
059        Names names;
060        Log log;
061        Symtab syms;
062        Check chk;
063        Infer infer;
064        ClassReader reader;
065        TreeInfo treeinfo;
066        Types types;
067        JCDiagnostic.Factory diags;
068        public final boolean boxingEnabled; // = source.allowBoxing();
069        public final boolean varargsEnabled; // = source.allowVarargs();
070        private final boolean debugResolve;
071    
072        public static Resolve instance(Context context) {
073            Resolve instance = context.get(resolveKey);
074            if (instance == null)
075                instance = new Resolve(context);
076            return instance;
077        }
078    
079        protected Resolve(Context context) {
080            context.put(resolveKey, this);
081            syms = Symtab.instance(context);
082    
083            varNotFound = new
084                ResolveError(ABSENT_VAR, syms.errSymbol, "variable not found");
085            wrongMethod = new
086                ResolveError(WRONG_MTH, syms.errSymbol, "method not found");
087            wrongMethods = new
088                ResolveError(WRONG_MTHS, syms.errSymbol, "wrong methods");
089            methodNotFound = new
090                ResolveError(ABSENT_MTH, syms.errSymbol, "method not found");
091            typeNotFound = new
092                ResolveError(ABSENT_TYP, syms.errSymbol, "type not found");
093    
094            names = Names.instance(context);
095            log = Log.instance(context);
096            chk = Check.instance(context);
097            infer = Infer.instance(context);
098            reader = ClassReader.instance(context);
099            treeinfo = TreeInfo.instance(context);
100            types = Types.instance(context);
101            diags = JCDiagnostic.Factory.instance(context);
102            Source source = Source.instance(context);
103            boxingEnabled = source.allowBoxing();
104            varargsEnabled = source.allowVarargs();
105            Options options = Options.instance(context);
106            debugResolve = options.get("debugresolve") != null;
107        }
108    
109        /** error symbols, which are returned when resolution fails
110         */
111        final ResolveError varNotFound;
112        final ResolveError wrongMethod;
113        final ResolveError wrongMethods;
114        final ResolveError methodNotFound;
115        final ResolveError typeNotFound;
116    
117    /* ************************************************************************
118     * Identifier resolution
119     *************************************************************************/
120    
121        /** An environment is "static" if its static level is greater than
122         *  the one of its outer environment
123         */
124        static boolean isStatic(Env<AttrContext> env) {
125            return env.info.staticLevel > env.outer.info.staticLevel;
126        }
127    
128        /** An environment is an "initializer" if it is a constructor or
129         *  an instance initializer.
130         */
131        static boolean isInitializer(Env<AttrContext> env) {
132            Symbol owner = env.info.scope.owner;
133            return owner.isConstructor() ||
134                owner.owner.kind == TYP &&
135                (owner.kind == VAR ||
136                 owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
137                (owner.flags() & STATIC) == 0;
138        }
139    
140        /** Is class accessible in given evironment?
141         *  @param env    The current environment.
142         *  @param c      The class whose accessibility is checked.
143         */
144        public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
145            switch ((short)(c.flags() & AccessFlags)) {
146            case PRIVATE:
147                return
148                    env.enclClass.sym.outermostClass() ==
149                    c.owner.outermostClass();
150            case 0:
151                return
152                    env.toplevel.packge == c.owner // fast special case
153                    ||
154                    env.toplevel.packge == c.packge()
155                    ||
156                    // Hack: this case is added since synthesized default constructors
157                    // of anonymous classes should be allowed to access
158                    // classes which would be inaccessible otherwise.
159                    env.enclMethod != null &&
160                    (env.enclMethod.mods.flags & ANONCONSTR) != 0;
161            default: // error recovery
162            case PUBLIC:
163                return true;
164            case PROTECTED:
165                return
166                    env.toplevel.packge == c.owner // fast special case
167                    ||
168                    env.toplevel.packge == c.packge()
169                    ||
170                    isInnerSubClass(env.enclClass.sym, c.owner);
171            }
172        }
173        //where
174            /** Is given class a subclass of given base class, or an inner class
175             *  of a subclass?
176             *  Return null if no such class exists.
177             *  @param c     The class which is the subclass or is contained in it.
178             *  @param base  The base class
179             */
180            private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
181                while (c != null && !c.isSubClass(base, types)) {
182                    c = c.owner.enclClass();
183                }
184                return c != null;
185            }
186    
187        boolean isAccessible(Env<AttrContext> env, Type t) {
188            return (t.tag == ARRAY)
189                ? isAccessible(env, types.elemtype(t))
190                : isAccessible(env, t.tsym);
191        }
192    
193        /** Is symbol accessible as a member of given type in given evironment?
194         *  @param env    The current environment.
195         *  @param site   The type of which the tested symbol is regarded
196         *                as a member.
197         *  @param sym    The symbol.
198         */
199        public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
200            if (sym.name == names.init && sym.owner != site.tsym) return false;
201            ClassSymbol sub;
202            switch ((short)(sym.flags() & AccessFlags)) {
203            case PRIVATE:
204                return
205                    (env.enclClass.sym == sym.owner // fast special case
206                     ||
207                     env.enclClass.sym.outermostClass() ==
208                     sym.owner.outermostClass())
209                    &&
210                    sym.isInheritedIn(site.tsym, types);
211            case 0:
212                return
213                    (env.toplevel.packge == sym.owner.owner // fast special case
214                     ||
215                     env.toplevel.packge == sym.packge())
216                    &&
217                    isAccessible(env, site)
218                    &&
219                    sym.isInheritedIn(site.tsym, types);
220            case PROTECTED:
221                return
222                    (env.toplevel.packge == sym.owner.owner // fast special case
223                     ||
224                     env.toplevel.packge == sym.packge()
225                     ||
226                     isProtectedAccessible(sym, env.enclClass.sym, site)
227                     ||
228                     // OK to select instance method or field from 'super' or type name
229                     // (but type names should be disallowed elsewhere!)
230                     env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
231                    &&
232                    isAccessible(env, site)
233                    &&
234                    // `sym' is accessible only if not overridden by
235                    // another symbol which is a member of `site'
236                    // (because, if it is overridden, `sym' is not strictly
237                    // speaking a member of `site'.)
238                    (sym.kind != MTH || sym.isConstructor() || sym.isStatic() ||
239                     ((MethodSymbol)sym).implementation(site.tsym, types, true) == sym);
240            default: // this case includes erroneous combinations as well
241                return isAccessible(env, site);
242            }
243        }
244        //where
245            /** Is given protected symbol accessible if it is selected from given site
246             *  and the selection takes place in given class?
247             *  @param sym     The symbol with protected access
248             *  @param c       The class where the access takes place
249             *  @site          The type of the qualifier
250             */
251            private
252            boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
253                while (c != null &&
254                       !(c.isSubClass(sym.owner, types) &&
255                         (c.flags() & INTERFACE) == 0 &&
256                         // In JLS 2e 6.6.2.1, the subclass restriction applies
257                         // only to instance fields and methods -- types are excluded
258                         // regardless of whether they are declared 'static' or not.
259                         ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
260                    c = c.owner.enclClass();
261                return c != null;
262            }
263    
264        /** Try to instantiate the type of a method so that it fits
265         *  given type arguments and argument types. If succesful, return
266         *  the method's instantiated type, else return null.
267         *  The instantiation will take into account an additional leading
268         *  formal parameter if the method is an instance method seen as a member
269         *  of un underdetermined site In this case, we treat site as an additional
270         *  parameter and the parameters of the class containing the method as
271         *  additional type variables that get instantiated.
272         *
273         *  @param env         The current environment
274         *  @param site        The type of which the method is a member.
275         *  @param m           The method symbol.
276         *  @param argtypes    The invocation's given value arguments.
277         *  @param typeargtypes    The invocation's given type arguments.
278         *  @param allowBoxing Allow boxing conversions of arguments.
279         *  @param useVarargs Box trailing arguments into an array for varargs.
280         */
281        Type rawInstantiate(Env<AttrContext> env,
282                            Type site,
283                            Symbol m,
284                            List<Type> argtypes,
285                            List<Type> typeargtypes,
286                            boolean allowBoxing,
287                            boolean useVarargs,
288                            Warner warn)
289            throws Infer.NoInstanceException {
290            if (useVarargs && (m.flags() & VARARGS) == 0) return null;
291            Type mt = types.memberType(site, m);
292    
293            // tvars is the list of formal type variables for which type arguments
294            // need to inferred.
295            List<Type> tvars = env.info.tvars;
296            if (typeargtypes == null) typeargtypes = List.nil();
297            if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
298                // This is not a polymorphic method, but typeargs are supplied
299                // which is fine, see JLS3 15.12.2.1
300            } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
301                ForAll pmt = (ForAll) mt;
302                if (typeargtypes.length() != pmt.tvars.length())
303                    return null;
304                // Check type arguments are within bounds
305                List<Type> formals = pmt.tvars;
306                List<Type> actuals = typeargtypes;
307                while (formals.nonEmpty() && actuals.nonEmpty()) {
308                    List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
309                                                    pmt.tvars, typeargtypes);
310                    for (; bounds.nonEmpty(); bounds = bounds.tail)
311                        if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
312                            return null;
313                    formals = formals.tail;
314                    actuals = actuals.tail;
315                }
316                mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
317            } else if (mt.tag == FORALL) {
318                ForAll pmt = (ForAll) mt;
319                List<Type> tvars1 = types.newInstances(pmt.tvars);
320                tvars = tvars.appendList(tvars1);
321                mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
322            }
323    
324            // find out whether we need to go the slow route via infer
325            boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/;
326            for (List<Type> l = argtypes;
327                 l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
328                 l = l.tail) {
329                if (l.head.tag == FORALL) instNeeded = true;
330            }
331    
332            if (instNeeded)
333                return
334                infer.instantiateMethod(tvars,
335                                        (MethodType)mt,
336                                        argtypes,
337                                        allowBoxing,
338                                        useVarargs,
339                                        warn);
340            return
341                argumentsAcceptable(argtypes, mt.getParameterTypes(),
342                                    allowBoxing, useVarargs, warn)
343                ? mt
344                : null;
345        }
346    
347        /** Same but returns null instead throwing a NoInstanceException
348         */
349        Type instantiate(Env<AttrContext> env,
350                         Type site,
351                         Symbol m,
352                         List<Type> argtypes,
353                         List<Type> typeargtypes,
354                         boolean allowBoxing,
355                         boolean useVarargs,
356                         Warner warn) {
357            try {
358                return rawInstantiate(env, site, m, argtypes, typeargtypes,
359                                      allowBoxing, useVarargs, warn);
360            } catch (Infer.NoInstanceException ex) {
361                return null;
362            }
363        }
364    
365        /** Check if a parameter list accepts a list of args.
366         */
367        boolean argumentsAcceptable(List<Type> argtypes,
368                                    List<Type> formals,
369                                    boolean allowBoxing,
370                                    boolean useVarargs,
371                                    Warner warn) {
372            Type varargsFormal = useVarargs ? formals.last() : null;
373            while (argtypes.nonEmpty() && formals.head != varargsFormal) {
374                boolean works = allowBoxing
375                    ? types.isConvertible(argtypes.head, formals.head, warn)
376                    : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
377                if (!works) return false;
378                argtypes = argtypes.tail;
379                formals = formals.tail;
380            }
381            if (formals.head != varargsFormal) return false; // not enough args
382            if (!useVarargs)
383                return argtypes.isEmpty();
384            Type elt = types.elemtype(varargsFormal);
385            while (argtypes.nonEmpty()) {
386                if (!types.isConvertible(argtypes.head, elt, warn))
387                    return false;
388                argtypes = argtypes.tail;
389            }
390            return true;
391        }
392    
393    /* ***************************************************************************
394     *  Symbol lookup
395     *  the following naming conventions for arguments are used
396     *
397     *       env      is the environment where the symbol was mentioned
398     *       site     is the type of which the symbol is a member
399     *       name     is the symbol's name
400     *                if no arguments are given
401     *       argtypes are the value arguments, if we search for a method
402     *
403     *  If no symbol was found, a ResolveError detailing the problem is returned.
404     ****************************************************************************/
405    
406        /** Find field. Synthetic fields are always skipped.
407         *  @param env     The current environment.
408         *  @param site    The original type from where the selection takes place.
409         *  @param name    The name of the field.
410         *  @param c       The class to search for the field. This is always
411         *                 a superclass or implemented interface of site's class.
412         */
413        Symbol findField(Env<AttrContext> env,
414                         Type site,
415                         Name name,
416                         TypeSymbol c) {
417            while (c.type.tag == TYPEVAR)
418                c = c.type.getUpperBound().tsym;
419            Symbol bestSoFar = varNotFound;
420            Symbol sym;
421            Scope.Entry e = c.members().lookup(name);
422            while (e.scope != null) {
423                if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
424                    return isAccessible(env, site, e.sym)
425                        ? e.sym : new AccessError(env, site, e.sym);
426                }
427                e = e.next();
428            }
429            Type st = types.supertype(c.type);
430            if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
431                sym = findField(env, site, name, st.tsym);
432                if (sym.kind < bestSoFar.kind) bestSoFar = sym;
433            }
434            for (List<Type> l = types.interfaces(c.type);
435                 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
436                 l = l.tail) {
437                sym = findField(env, site, name, l.head.tsym);
438                if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
439                    sym.owner != bestSoFar.owner)
440                    bestSoFar = new AmbiguityError(bestSoFar, sym);
441                else if (sym.kind < bestSoFar.kind)
442                    bestSoFar = sym;
443            }
444            return bestSoFar;
445        }
446    
447        /** Resolve a field identifier, throw a fatal error if not found.
448         *  @param pos       The position to use for error reporting.
449         *  @param env       The environment current at the method invocation.
450         *  @param site      The type of the qualifying expression, in which
451         *                   identifier is searched.
452         *  @param name      The identifier's name.
453         */
454        public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
455                                              Type site, Name name) {
456            Symbol sym = findField(env, site, name, site.tsym);
457            if (sym.kind == VAR) return (VarSymbol)sym;
458            else throw new FatalError(
459                     diags.fragment("fatal.err.cant.locate.field",
460                                    name));
461        }
462    
463        /** Find unqualified variable or field with given name.
464         *  Synthetic fields always skipped.
465         *  @param env     The current environment.
466         *  @param name    The name of the variable or field.
467         */
468        Symbol findVar(Env<AttrContext> env, Name name) {
469            Symbol bestSoFar = varNotFound;
470            Symbol sym;
471            Env<AttrContext> env1 = env;
472            boolean staticOnly = false;
473            while (env1.outer != null) {
474                if (isStatic(env1)) staticOnly = true;
475                Scope.Entry e = env1.info.scope.lookup(name);
476                while (e.scope != null &&
477                       (e.sym.kind != VAR ||
478                        (e.sym.flags_field & SYNTHETIC) != 0))
479                    e = e.next();
480                sym = (e.scope != null)
481                    ? e.sym
482                    : findField(
483                        env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
484                if (sym.exists()) {
485                    if (staticOnly &&
486                        sym.kind == VAR &&
487                        sym.owner.kind == TYP &&
488                        (sym.flags() & STATIC) == 0)
489                        return new StaticError(sym);
490                    else
491                        return sym;
492                } else if (sym.kind < bestSoFar.kind) {
493                    bestSoFar = sym;
494                }
495    
496                if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
497                env1 = env1.outer;
498            }
499    
500            sym = findField(env, syms.predefClass.type, name, syms.predefClass);
501            if (sym.exists())
502                return sym;
503            if (bestSoFar.exists())
504                return bestSoFar;
505    
506            Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
507            for (; e.scope != null; e = e.next()) {
508                sym = e.sym;
509                Type origin = e.getOrigin().owner.type;
510                if (sym.kind == VAR) {
511                    if (e.sym.owner.type != origin)
512                        sym = sym.clone(e.getOrigin().owner);
513                    return isAccessible(env, origin, sym)
514                        ? sym : new AccessError(env, origin, sym);
515                }
516            }
517    
518            Symbol origin = null;
519            e = env.toplevel.starImportScope.lookup(name);
520            for (; e.scope != null; e = e.next()) {
521                sym = e.sym;
522                if (sym.kind != VAR)
523                    continue;
524                // invariant: sym.kind == VAR
525                if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
526                    return new AmbiguityError(bestSoFar, sym);
527                else if (bestSoFar.kind >= VAR) {
528                    origin = e.getOrigin().owner;
529                    bestSoFar = isAccessible(env, origin.type, sym)
530                        ? sym : new AccessError(env, origin.type, sym);
531                }
532            }
533            if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
534                return bestSoFar.clone(origin);
535            else
536                return bestSoFar;
537        }
538    
539        Warner noteWarner = new Warner();
540    
541        /** Select the best method for a call site among two choices.
542         *  @param env              The current environment.
543         *  @param site             The original type from where the
544         *                          selection takes place.
545         *  @param argtypes         The invocation's value arguments,
546         *  @param typeargtypes     The invocation's type arguments,
547         *  @param sym              Proposed new best match.
548         *  @param bestSoFar        Previously found best match.
549         *  @param allowBoxing Allow boxing conversions of arguments.
550         *  @param useVarargs Box trailing arguments into an array for varargs.
551         */
552        Symbol selectBest(Env<AttrContext> env,
553                          Type site,
554                          List<Type> argtypes,
555                          List<Type> typeargtypes,
556                          Symbol sym,
557                          Symbol bestSoFar,
558                          boolean allowBoxing,
559                          boolean useVarargs,
560                          boolean operator) {
561            if (sym.kind == ERR) return bestSoFar;
562            if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
563            assert sym.kind < AMBIGUOUS;
564            try {
565                if (rawInstantiate(env, site, sym, argtypes, typeargtypes,
566                                   allowBoxing, useVarargs, Warner.noWarnings) == null) {
567                    // inapplicable
568                    switch (bestSoFar.kind) {
569                    case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
570                    case WRONG_MTH: return wrongMethods;
571                    default: return bestSoFar;
572                    }
573                }
574            } catch (Infer.NoInstanceException ex) {
575                switch (bestSoFar.kind) {
576                case ABSENT_MTH:
577                    return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
578                case WRONG_MTH:
579                    return wrongMethods;
580                default:
581                    return bestSoFar;
582                }
583            }
584            if (!isAccessible(env, site, sym)) {
585                return (bestSoFar.kind == ABSENT_MTH)
586                    ? new AccessError(env, site, sym)
587                    : bestSoFar;
588            }
589            return (bestSoFar.kind > AMBIGUOUS)
590                ? sym
591                : mostSpecific(sym, bestSoFar, env, site,
592                               allowBoxing && operator, useVarargs);
593        }
594    
595        /* Return the most specific of the two methods for a call,
596         *  given that both are accessible and applicable.
597         *  @param m1               A new candidate for most specific.
598         *  @param m2               The previous most specific candidate.
599         *  @param env              The current environment.
600         *  @param site             The original type from where the selection
601         *                          takes place.
602         *  @param allowBoxing Allow boxing conversions of arguments.
603         *  @param useVarargs Box trailing arguments into an array for varargs.
604         */
605        Symbol mostSpecific(Symbol m1,
606                            Symbol m2,
607                            Env<AttrContext> env,
608                            Type site,
609                            boolean allowBoxing,
610                            boolean useVarargs) {
611            switch (m2.kind) {
612            case MTH:
613                if (m1 == m2) return m1;
614                Type mt1 = types.memberType(site, m1);
615                noteWarner.unchecked = false;
616                boolean m1SignatureMoreSpecific =
617                    (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
618                                 allowBoxing, false, noteWarner) != null ||
619                     useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
620                                               allowBoxing, true, noteWarner) != null) &&
621                    !noteWarner.unchecked;
622                Type mt2 = types.memberType(site, m2);
623                noteWarner.unchecked = false;
624                boolean m2SignatureMoreSpecific =
625                    (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
626                                 allowBoxing, false, noteWarner) != null ||
627                     useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
628                                               allowBoxing, true, noteWarner) != null) &&
629                    !noteWarner.unchecked;
630                if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
631                    if (!types.overrideEquivalent(mt1, mt2))
632                        return new AmbiguityError(m1, m2);
633                    // same signature; select (a) the non-bridge method, or
634                    // (b) the one that overrides the other, or (c) the concrete
635                    // one, or (d) merge both abstract signatures
636                    if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
637                        return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
638                    }
639                    // if one overrides or hides the other, use it
640                    TypeSymbol m1Owner = (TypeSymbol)m1.owner;
641                    TypeSymbol m2Owner = (TypeSymbol)m2.owner;
642                    if (types.asSuper(m1Owner.type, m2Owner) != null &&
643                        ((m1.owner.flags_field & INTERFACE) == 0 ||
644                         (m2.owner.flags_field & INTERFACE) != 0) &&
645                        m1.overrides(m2, m1Owner, types, false))
646                        return m1;
647                    if (types.asSuper(m2Owner.type, m1Owner) != null &&
648                        ((m2.owner.flags_field & INTERFACE) == 0 ||
649                         (m1.owner.flags_field & INTERFACE) != 0) &&
650                        m2.overrides(m1, m2Owner, types, false))
651                        return m2;
652                    boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
653                    boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
654                    if (m1Abstract && !m2Abstract) return m2;
655                    if (m2Abstract && !m1Abstract) return m1;
656                    // both abstract or both concrete
657                    if (!m1Abstract && !m2Abstract)
658                        return new AmbiguityError(m1, m2);
659                    // check that both signatures have the same erasure
660                    if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
661                                           m2.erasure(types).getParameterTypes()))
662                        return new AmbiguityError(m1, m2);
663                    // both abstract, neither overridden; merge throws clause and result type
664                    Symbol result;
665                    Type result2 = mt2.getReturnType();
666                    if (mt2.tag == FORALL)
667                        result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
668                    if (types.isSubtype(mt1.getReturnType(), result2)) {
669                        result = m1;
670                    } else if (types.isSubtype(result2, mt1.getReturnType())) {
671                        result = m2;
672                    } else {
673                        // Theoretically, this can't happen, but it is possible
674                        // due to error recovery or mixing incompatible class files
675                        return new AmbiguityError(m1, m2);
676                    }
677                    result = result.clone(result.owner);
678                    result.type = (Type)result.type.clone();
679                    result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
680                                                        mt2.getThrownTypes()));
681                    return result;
682                }
683                if (m1SignatureMoreSpecific) return m1;
684                if (m2SignatureMoreSpecific) return m2;
685                return new AmbiguityError(m1, m2);
686            case AMBIGUOUS:
687                AmbiguityError e = (AmbiguityError)m2;
688                Symbol err1 = mostSpecific(m1, e.sym1, env, site, allowBoxing, useVarargs);
689                Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
690                if (err1 == err2) return err1;
691                if (err1 == e.sym1 && err2 == e.sym2) return m2;
692                if (err1 instanceof AmbiguityError &&
693                    err2 instanceof AmbiguityError &&
694                    ((AmbiguityError)err1).sym1 == ((AmbiguityError)err2).sym1)
695                    return new AmbiguityError(m1, m2);
696                else
697                    return new AmbiguityError(err1, err2);
698            default:
699                throw new AssertionError();
700            }
701        }
702    
703        /** Find best qualified method matching given name, type and value
704         *  arguments.
705         *  @param env       The current environment.
706         *  @param site      The original type from where the selection
707         *                   takes place.
708         *  @param name      The method's name.
709         *  @param argtypes  The method's value arguments.
710         *  @param typeargtypes The method's type arguments
711         *  @param allowBoxing Allow boxing conversions of arguments.
712         *  @param useVarargs Box trailing arguments into an array for varargs.
713         */
714        Symbol findMethod(Env<AttrContext> env,
715                          Type site,
716                          Name name,
717                          List<Type> argtypes,
718                          List<Type> typeargtypes,
719                          boolean allowBoxing,
720                          boolean useVarargs,
721                          boolean operator) {
722            return findMethod(env,
723                              site,
724                              name,
725                              argtypes,
726                              typeargtypes,
727                              site.tsym.type,
728                              true,
729                              methodNotFound,
730                              allowBoxing,
731                              useVarargs,
732                              operator);
733        }
734        // where
735        private Symbol findMethod(Env<AttrContext> env,
736                                  Type site,
737                                  Name name,
738                                  List<Type> argtypes,
739                                  List<Type> typeargtypes,
740                                  Type intype,
741                                  boolean abstractok,
742                                  Symbol bestSoFar,
743                                  boolean allowBoxing,
744                                  boolean useVarargs,
745                                  boolean operator) {
746            for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
747                while (ct.tag == TYPEVAR)
748                    ct = ct.getUpperBound();
749                ClassSymbol c = (ClassSymbol)ct.tsym;
750                if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
751                    abstractok = false;
752                for (Scope.Entry e = c.members().lookup(name);
753                     e.scope != null;
754                     e = e.next()) {
755                    //- System.out.println(" e " + e.sym);
756                    if (e.sym.kind == MTH &&
757                        (e.sym.flags_field & SYNTHETIC) == 0) {
758                        bestSoFar = selectBest(env, site, argtypes, typeargtypes,
759                                               e.sym, bestSoFar,
760                                               allowBoxing,
761                                               useVarargs,
762                                               operator);
763                    }
764                }
765                //- System.out.println(" - " + bestSoFar);
766                if (abstractok) {
767                    Symbol concrete = methodNotFound;
768                    if ((bestSoFar.flags() & ABSTRACT) == 0)
769                        concrete = bestSoFar;
770                    for (List<Type> l = types.interfaces(c.type);
771                         l.nonEmpty();
772                         l = l.tail) {
773                        bestSoFar = findMethod(env, site, name, argtypes,
774                                               typeargtypes,
775                                               l.head, abstractok, bestSoFar,
776                                               allowBoxing, useVarargs, operator);
777                    }
778                    if (concrete != bestSoFar &&
779                        concrete.kind < ERR  && bestSoFar.kind < ERR &&
780                        types.isSubSignature(concrete.type, bestSoFar.type))
781                        bestSoFar = concrete;
782                }
783            }
784            return bestSoFar;
785        }
786    
787        /** Find unqualified method matching given name, type and value arguments.
788         *  @param env       The current environment.
789         *  @param name      The method's name.
790         *  @param argtypes  The method's value arguments.
791         *  @param typeargtypes  The method's type arguments.
792         *  @param allowBoxing Allow boxing conversions of arguments.
793         *  @param useVarargs Box trailing arguments into an array for varargs.
794         */
795        Symbol findFun(Env<AttrContext> env, Name name,
796                       List<Type> argtypes, List<Type> typeargtypes,
797                       boolean allowBoxing, boolean useVarargs) {
798            Symbol bestSoFar = methodNotFound;
799            Symbol sym;
800            Env<AttrContext> env1 = env;
801            boolean staticOnly = false;
802            while (env1.outer != null) {
803                if (isStatic(env1)) staticOnly = true;
804                sym = findMethod(
805                    env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
806                    allowBoxing, useVarargs, false);
807                if (sym.exists()) {
808                    if (staticOnly &&
809                        sym.kind == MTH &&
810                        sym.owner.kind == TYP &&
811                        (sym.flags() & STATIC) == 0) return new StaticError(sym);
812                    else return sym;
813                } else if (sym.kind < bestSoFar.kind) {
814                    bestSoFar = sym;
815                }
816                if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
817                env1 = env1.outer;
818            }
819    
820            sym = findMethod(env, syms.predefClass.type, name, argtypes,
821                             typeargtypes, allowBoxing, useVarargs, false);
822            if (sym.exists())
823                return sym;
824    
825            Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
826            for (; e.scope != null; e = e.next()) {
827                sym = e.sym;
828                Type origin = e.getOrigin().owner.type;
829                if (sym.kind == MTH) {
830                    if (e.sym.owner.type != origin)
831                        sym = sym.clone(e.getOrigin().owner);
832                    if (!isAccessible(env, origin, sym))
833                        sym = new AccessError(env, origin, sym);
834                    bestSoFar = selectBest(env, origin,
835                                           argtypes, typeargtypes,
836                                           sym, bestSoFar,
837                                           allowBoxing, useVarargs, false);
838                }
839            }
840            if (bestSoFar.exists())
841                return bestSoFar;
842    
843            e = env.toplevel.starImportScope.lookup(name);
844            for (; e.scope != null; e = e.next()) {
845                sym = e.sym;
846                Type origin = e.getOrigin().owner.type;
847                if (sym.kind == MTH) {
848                    if (e.sym.owner.type != origin)
849                        sym = sym.clone(e.getOrigin().owner);
850                    if (!isAccessible(env, origin, sym))
851                        sym = new AccessError(env, origin, sym);
852                    bestSoFar = selectBest(env, origin,
853                                           argtypes, typeargtypes,
854                                           sym, bestSoFar,
855                                           allowBoxing, useVarargs, false);
856                }
857            }
858            return bestSoFar;
859        }
860    
861        /** Load toplevel or member class with given fully qualified name and
862         *  verify that it is accessible.
863         *  @param env       The current environment.
864         *  @param name      The fully qualified name of the class to be loaded.
865         */
866        Symbol loadClass(Env<AttrContext> env, Name name) {
867            try {
868                ClassSymbol c = reader.loadClass(name);
869                return isAccessible(env, c) ? c : new AccessError(c);
870            } catch (ClassReader.BadClassFile err) {
871                throw err;
872            } catch (CompletionFailure ex) {
873                return typeNotFound;
874            }
875        }
876    
877        /** Find qualified member type.
878         *  @param env       The current environment.
879         *  @param site      The original type from where the selection takes
880         *                   place.
881         *  @param name      The type's name.
882         *  @param c         The class to search for the member type. This is
883         *                   always a superclass or implemented interface of
884         *                   site's class.
885         */
886        Symbol findMemberType(Env<AttrContext> env,
887                              Type site,
888                              Name name,
889                              TypeSymbol c) {
890            Symbol bestSoFar = typeNotFound;
891            Symbol sym;
892            Scope.Entry e = c.members().lookup(name);
893            while (e.scope != null) {
894                if (e.sym.kind == TYP) {
895                    return isAccessible(env, site, e.sym)
896                        ? e.sym
897                        : new AccessError(env, site, e.sym);
898                }
899                e = e.next();
900            }
901            Type st = types.supertype(c.type);
902            if (st != null && st.tag == CLASS) {
903                sym = findMemberType(env, site, name, st.tsym);
904                if (sym.kind < bestSoFar.kind) bestSoFar = sym;
905            }
906            for (List<Type> l = types.interfaces(c.type);
907                 bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
908                 l = l.tail) {
909                sym = findMemberType(env, site, name, l.head.tsym);
910                if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
911                    sym.owner != bestSoFar.owner)
912                    bestSoFar = new AmbiguityError(bestSoFar, sym);
913                else if (sym.kind < bestSoFar.kind)
914                    bestSoFar = sym;
915            }
916            return bestSoFar;
917        }
918    
919        /** Find a global type in given scope and load corresponding class.
920         *  @param env       The current environment.
921         *  @param scope     The scope in which to look for the type.
922         *  @param name      The type's name.
923         */
924        Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
925            Symbol bestSoFar = typeNotFound;
926            for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
927                Symbol sym = loadClass(env, e.sym.flatName());
928                if (bestSoFar.kind == TYP && sym.kind == TYP &&
929                    bestSoFar != sym)
930                    return new AmbiguityError(bestSoFar, sym);
931                else if (sym.kind < bestSoFar.kind)
932                    bestSoFar = sym;
933            }
934            return bestSoFar;
935        }
936    
937        /** Find an unqualified type symbol.
938         *  @param env       The current environment.
939         *  @param name      The type's name.
940         */
941        Symbol findType(Env<AttrContext> env, Name name) {
942            Symbol bestSoFar = typeNotFound;
943            Symbol sym;
944            boolean staticOnly = false;
945            for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
946                if (isStatic(env1)) staticOnly = true;
947                for (Scope.Entry e = env1.info.scope.lookup(name);
948                     e.scope != null;
949                     e = e.next()) {
950                    if (e.sym.kind == TYP) {
951                        if (staticOnly &&
952                            e.sym.type.tag == TYPEVAR &&
953                            e.sym.owner.kind == TYP) return new StaticError(e.sym);
954                        return e.sym;
955                    }
956                }
957    
958                sym = findMemberType(env1, env1.enclClass.sym.type, name,
959                                     env1.enclClass.sym);
960                if (staticOnly && sym.kind == TYP &&
961                    sym.type.tag == CLASS &&
962                    sym.type.getEnclosingType().tag == CLASS &&
963                    env1.enclClass.sym.type.isParameterized() &&
964                    sym.type.getEnclosingType().isParameterized())
965                    return new StaticError(sym);
966                else if (sym.exists()) return sym;
967                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
968    
969                JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
970                if ((encl.sym.flags() & STATIC) != 0)
971                    staticOnly = true;
972            }
973    
974            if (env.tree.getTag() != JCTree.IMPORT) {
975                sym = findGlobalType(env, env.toplevel.namedImportScope, name);
976                if (sym.exists()) return sym;
977                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
978    
979                sym = findGlobalType(env, env.toplevel.packge.members(), name);
980                if (sym.exists()) return sym;
981                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
982    
983                sym = findGlobalType(env, env.toplevel.starImportScope, name);
984                if (sym.exists()) return sym;
985                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
986            }
987    
988            return bestSoFar;
989        }
990    
991        /** Find an unqualified identifier which matches a specified kind set.
992         *  @param env       The current environment.
993         *  @param name      The indentifier's name.
994         *  @param kind      Indicates the possible symbol kinds
995         *                   (a subset of VAL, TYP, PCK).
996         */
997        Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
998            Symbol bestSoFar = typeNotFound;
999            Symbol sym;
1000    
1001            if ((kind & VAR) != 0) {
1002                sym = findVar(env, name);
1003                if (sym.exists()) return sym;
1004                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1005            }
1006    
1007            if ((kind & TYP) != 0) {
1008                sym = findType(env, name);
1009                if (sym.exists()) return sym;
1010                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1011            }
1012    
1013            if ((kind & PCK) != 0) return reader.enterPackage(name);
1014            else return bestSoFar;
1015        }
1016    
1017        /** Find an identifier in a package which matches a specified kind set.
1018         *  @param env       The current environment.
1019         *  @param name      The identifier's name.
1020         *  @param kind      Indicates the possible symbol kinds
1021         *                   (a nonempty subset of TYP, PCK).
1022         */
1023        Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
1024                                  Name name, int kind) {
1025            Name fullname = TypeSymbol.formFullName(name, pck);
1026            Symbol bestSoFar = typeNotFound;
1027            PackageSymbol pack = null;
1028            if ((kind & PCK) != 0) {
1029                pack = reader.enterPackage(fullname);
1030                if (pack.exists()) return pack;
1031            }
1032            if ((kind & TYP) != 0) {
1033                Symbol sym = loadClass(env, fullname);
1034                if (sym.exists()) {
1035                    // don't allow programs to use flatnames
1036                    if (name == sym.name) return sym;
1037                }
1038                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1039            }
1040            return (pack != null) ? pack : bestSoFar;
1041        }
1042    
1043        /** Find an identifier among the members of a given type `site'.
1044         *  @param env       The current environment.
1045         *  @param site      The type containing the symbol to be found.
1046         *  @param name      The identifier's name.
1047         *  @param kind      Indicates the possible symbol kinds
1048         *                   (a subset of VAL, TYP).
1049         */
1050        Symbol findIdentInType(Env<AttrContext> env, Type site,
1051                               Name name, int kind) {
1052            Symbol bestSoFar = typeNotFound;
1053            Symbol sym;
1054            if ((kind & VAR) != 0) {
1055                sym = findField(env, site, name, site.tsym);
1056                if (sym.exists()) return sym;
1057                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1058            }
1059    
1060            if ((kind & TYP) != 0) {
1061                sym = findMemberType(env, site, name, site.tsym);
1062                if (sym.exists()) return sym;
1063                else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
1064            }
1065            return bestSoFar;
1066        }
1067    
1068    /* ***************************************************************************
1069     *  Access checking
1070     *  The following methods convert ResolveErrors to ErrorSymbols, issuing
1071     *  an error message in the process
1072     ****************************************************************************/
1073    
1074        /** If `sym' is a bad symbol: report error and return errSymbol
1075         *  else pass through unchanged,
1076         *  additional arguments duplicate what has been used in trying to find the
1077         *  symbol (--> flyweight pattern). This improves performance since we
1078         *  expect misses to happen frequently.
1079         *
1080         *  @param sym       The symbol that was found, or a ResolveError.
1081         *  @param pos       The position to use for error reporting.
1082         *  @param site      The original type from where the selection took place.
1083         *  @param name      The symbol's name.
1084         *  @param argtypes  The invocation's value arguments,
1085         *                   if we looked for a method.
1086         *  @param typeargtypes  The invocation's type arguments,
1087         *                   if we looked for a method.
1088         */
1089        Symbol access(Symbol sym,
1090                      DiagnosticPosition pos,
1091                      Type site,
1092                      Name name,
1093                      boolean qualified,
1094                      List<Type> argtypes,
1095                      List<Type> typeargtypes) {
1096            if (sym.kind >= AMBIGUOUS) {
1097    //          printscopes(site.tsym.members());//DEBUG
1098                if (!site.isErroneous() &&
1099                    !Type.isErroneous(argtypes) &&
1100                    (typeargtypes==null || !Type.isErroneous(typeargtypes)))
1101                    ((ResolveError)sym).report(log, pos, site, name, argtypes, typeargtypes);
1102                do {
1103                    sym = ((ResolveError)sym).sym;
1104                } while (sym.kind >= AMBIGUOUS);
1105                if (sym == syms.errSymbol // preserve the symbol name through errors
1106                    || ((sym.kind & ERRONEOUS) == 0 // make sure an error symbol is returned
1107                        && (sym.kind & TYP) != 0))
1108                    sym = types.createErrorType(name, qualified ? site.tsym : syms.noSymbol, sym.type).tsym;
1109            }
1110            return sym;
1111        }
1112    
1113        /** Same as above, but without type arguments and arguments.
1114         */
1115        Symbol access(Symbol sym,
1116                      DiagnosticPosition pos,
1117                      Type site,
1118                      Name name,
1119                      boolean qualified) {
1120            if (sym.kind >= AMBIGUOUS)
1121                return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
1122            else
1123                return sym;
1124        }
1125    
1126        /** Check that sym is not an abstract method.
1127         */
1128        void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
1129            if ((sym.flags() & ABSTRACT) != 0)
1130                log.error(pos, "abstract.cant.be.accessed.directly",
1131                          kindName(sym), sym, sym.location());
1132        }
1133    
1134    /* ***************************************************************************
1135     *  Debugging
1136     ****************************************************************************/
1137    
1138        /** print all scopes starting with scope s and proceeding outwards.
1139         *  used for debugging.
1140         */
1141        public void printscopes(Scope s) {
1142            while (s != null) {
1143                if (s.owner != null)
1144                    System.err.print(s.owner + ": ");
1145                for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
1146                    if ((e.sym.flags() & ABSTRACT) != 0)
1147                        System.err.print("abstract ");
1148                    System.err.print(e.sym + " ");
1149                }
1150                System.err.println();
1151                s = s.next;
1152            }
1153        }
1154    
1155        void printscopes(Env<AttrContext> env) {
1156            while (env.outer != null) {
1157                System.err.println("------------------------------");
1158                printscopes(env.info.scope);
1159                env = env.outer;
1160            }
1161        }
1162    
1163        public void printscopes(Type t) {
1164            while (t.tag == CLASS) {
1165                printscopes(t.tsym.members());
1166                t = types.supertype(t);
1167            }
1168        }
1169    
1170    /* ***************************************************************************
1171     *  Name resolution
1172     *  Naming conventions are as for symbol lookup
1173     *  Unlike the find... methods these methods will report access errors
1174     ****************************************************************************/
1175    
1176        /** Resolve an unqualified (non-method) identifier.
1177         *  @param pos       The position to use for error reporting.
1178         *  @param env       The environment current at the identifier use.
1179         *  @param name      The identifier's name.
1180         *  @param kind      The set of admissible symbol kinds for the identifier.
1181         */
1182        Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
1183                            Name name, int kind) {
1184            return access(
1185                findIdent(env, name, kind),
1186                pos, env.enclClass.sym.type, name, false);
1187        }
1188    
1189        /** Resolve an unqualified method identifier.
1190         *  @param pos       The position to use for error reporting.
1191         *  @param env       The environment current at the method invocation.
1192         *  @param name      The identifier's name.
1193         *  @param argtypes  The types of the invocation's value arguments.
1194         *  @param typeargtypes  The types of the invocation's type arguments.
1195         */
1196        Symbol resolveMethod(DiagnosticPosition pos,
1197                             Env<AttrContext> env,
1198                             Name name,
1199                             List<Type> argtypes,
1200                             List<Type> typeargtypes) {
1201            Symbol sym = methodNotFound;
1202            List<MethodResolutionPhase> steps = methodResolutionSteps;
1203            while (steps.nonEmpty() &&
1204                   steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1205                   sym.kind >= ERRONEOUS) {
1206                sym = findFun(env, name, argtypes, typeargtypes,
1207                        steps.head.isBoxingRequired,
1208                        env.info.varArgs = steps.head.isVarargsRequired);
1209                methodResolutionCache.put(steps.head, sym);
1210                steps = steps.tail;
1211            }
1212            if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1213                MethodResolutionPhase errPhase =
1214                        firstErroneousResolutionPhase();
1215                sym = access(methodResolutionCache.get(errPhase),
1216                        pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
1217                env.info.varArgs = errPhase.isVarargsRequired;
1218            }
1219            return sym;
1220        }
1221    
1222        /** Resolve a qualified method identifier
1223         *  @param pos       The position to use for error reporting.
1224         *  @param env       The environment current at the method invocation.
1225         *  @param site      The type of the qualifying expression, in which
1226         *                   identifier is searched.
1227         *  @param name      The identifier's name.
1228         *  @param argtypes  The types of the invocation's value arguments.
1229         *  @param typeargtypes  The types of the invocation's type arguments.
1230         */
1231        Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
1232                                      Type site, Name name, List<Type> argtypes,
1233                                      List<Type> typeargtypes) {
1234            Symbol sym = methodNotFound;
1235            List<MethodResolutionPhase> steps = methodResolutionSteps;
1236            while (steps.nonEmpty() &&
1237                   steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1238                   sym.kind >= ERRONEOUS) {
1239                sym = findMethod(env, site, name, argtypes, typeargtypes,
1240                        steps.head.isBoxingRequired(),
1241                        env.info.varArgs = steps.head.isVarargsRequired(), false);
1242                methodResolutionCache.put(steps.head, sym);
1243                steps = steps.tail;
1244            }
1245            if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1246                MethodResolutionPhase errPhase =
1247                        firstErroneousResolutionPhase();
1248                sym = access(methodResolutionCache.get(errPhase),
1249                        pos, site, name, true, argtypes, typeargtypes);
1250                env.info.varArgs = errPhase.isVarargsRequired;
1251            }
1252            return sym;
1253        }
1254    
1255        /** Resolve a qualified method identifier, throw a fatal error if not
1256         *  found.
1257         *  @param pos       The position to use for error reporting.
1258         *  @param env       The environment current at the method invocation.
1259         *  @param site      The type of the qualifying expression, in which
1260         *                   identifier is searched.
1261         *  @param name      The identifier's name.
1262         *  @param argtypes  The types of the invocation's value arguments.
1263         *  @param typeargtypes  The types of the invocation's type arguments.
1264         */
1265        public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
1266                                            Type site, Name name,
1267                                            List<Type> argtypes,
1268                                            List<Type> typeargtypes) {
1269            Symbol sym = resolveQualifiedMethod(
1270                pos, env, site, name, argtypes, typeargtypes);
1271            if (sym.kind == MTH) return (MethodSymbol)sym;
1272            else throw new FatalError(
1273                     diags.fragment("fatal.err.cant.locate.meth",
1274                                    name));
1275        }
1276    
1277        /** Resolve constructor.
1278         *  @param pos       The position to use for error reporting.
1279         *  @param env       The environment current at the constructor invocation.
1280         *  @param site      The type of class for which a constructor is searched.
1281         *  @param argtypes  The types of the constructor invocation's value
1282         *                   arguments.
1283         *  @param typeargtypes  The types of the constructor invocation's type
1284         *                   arguments.
1285         */
1286        Symbol resolveConstructor(DiagnosticPosition pos,
1287                                  Env<AttrContext> env,
1288                                  Type site,
1289                                  List<Type> argtypes,
1290                                  List<Type> typeargtypes) {
1291            Symbol sym = methodNotFound;
1292            List<MethodResolutionPhase> steps = methodResolutionSteps;
1293            while (steps.nonEmpty() &&
1294                   steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1295                   sym.kind >= ERRONEOUS) {
1296                sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
1297                        steps.head.isBoxingRequired(),
1298                        env.info.varArgs = steps.head.isVarargsRequired());
1299                methodResolutionCache.put(steps.head, sym);
1300                steps = steps.tail;
1301            }
1302            if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
1303                MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
1304                sym = access(methodResolutionCache.get(errPhase),
1305                        pos, site, names.init, true, argtypes, typeargtypes);
1306                env.info.varArgs = errPhase.isVarargsRequired();
1307            }
1308            return sym;
1309        }
1310    
1311        /** Resolve constructor.
1312         *  @param pos       The position to use for error reporting.
1313         *  @param env       The environment current at the constructor invocation.
1314         *  @param site      The type of class for which a constructor is searched.
1315         *  @param argtypes  The types of the constructor invocation's value
1316         *                   arguments.
1317         *  @param typeargtypes  The types of the constructor invocation's type
1318         *                   arguments.
1319         *  @param allowBoxing Allow boxing and varargs conversions.
1320         *  @param useVarargs Box trailing arguments into an array for varargs.
1321         */
1322        public Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1323                                         Type site, List<Type> argtypes,
1324                                         List<Type> typeargtypes,
1325                                         boolean allowBoxing,
1326                                         boolean useVarargs) {
1327            Symbol sym = findMethod(env, site,
1328                                    names.init, argtypes,
1329                                    typeargtypes, allowBoxing,
1330                                    useVarargs, false);
1331            if ((sym.flags() & DEPRECATED) != 0 &&
1332                (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
1333                env.info.scope.owner.outermostClass() != sym.outermostClass())
1334                chk.warnDeprecated(pos, sym);
1335            return sym;
1336        }
1337    
1338        /** Resolve a constructor, throw a fatal error if not found.
1339         *  @param pos       The position to use for error reporting.
1340         *  @param env       The environment current at the method invocation.
1341         *  @param site      The type to be constructed.
1342         *  @param argtypes  The types of the invocation's value arguments.
1343         *  @param typeargtypes  The types of the invocation's type arguments.
1344         */
1345        public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
1346                                            Type site,
1347                                            List<Type> argtypes,
1348                                            List<Type> typeargtypes) {
1349            Symbol sym = resolveConstructor(
1350                pos, env, site, argtypes, typeargtypes);
1351            if (sym.kind == MTH) return (MethodSymbol)sym;
1352            else throw new FatalError(
1353                     diags.fragment("fatal.err.cant.locate.ctor", site));
1354        }
1355    
1356        /** Resolve operator.
1357         *  @param pos       The position to use for error reporting.
1358         *  @param optag     The tag of the operation tree.
1359         *  @param env       The environment current at the operation.
1360         *  @param argtypes  The types of the operands.
1361         */
1362        Symbol resolveOperator(DiagnosticPosition pos, int optag,
1363                               Env<AttrContext> env, List<Type> argtypes) {
1364            Name name = treeinfo.operatorName(optag);
1365            Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
1366                                    null, false, false, true);
1367            if (boxingEnabled && sym.kind >= WRONG_MTHS)
1368                sym = findMethod(env, syms.predefClass.type, name, argtypes,
1369                                 null, true, false, true);
1370            return access(sym, pos, env.enclClass.sym.type, name,
1371                          false, argtypes, null);
1372        }
1373    
1374        /** Resolve operator.
1375         *  @param pos       The position to use for error reporting.
1376         *  @param optag     The tag of the operation tree.
1377         *  @param env       The environment current at the operation.
1378         *  @param arg       The type of the operand.
1379         */
1380        Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
1381            return resolveOperator(pos, optag, env, List.of(arg));
1382        }
1383    
1384        /** Resolve binary operator.
1385         *  @param pos       The position to use for error reporting.
1386         *  @param optag     The tag of the operation tree.
1387         *  @param env       The environment current at the operation.
1388         *  @param left      The types of the left operand.
1389         *  @param right     The types of the right operand.
1390         */
1391        Symbol resolveBinaryOperator(DiagnosticPosition pos,
1392                                     int optag,
1393                                     Env<AttrContext> env,
1394                                     Type left,
1395                                     Type right) {
1396            return resolveOperator(pos, optag, env, List.of(left, right));
1397        }
1398    
1399        /**
1400         * Resolve `c.name' where name == this or name == super.
1401         * @param pos           The position to use for error reporting.
1402         * @param env           The environment current at the expression.
1403         * @param c             The qualifier.
1404         * @param name          The identifier's name.
1405         */
1406        Symbol resolveSelf(DiagnosticPosition pos,
1407                           Env<AttrContext> env,
1408                           TypeSymbol c,
1409                           Name name) {
1410            Env<AttrContext> env1 = env;
1411            boolean staticOnly = false;
1412            while (env1.outer != null) {
1413                if (isStatic(env1)) staticOnly = true;
1414                if (env1.enclClass.sym == c) {
1415                    Symbol sym = env1.info.scope.lookup(name).sym;
1416                    if (sym != null) {
1417                        if (staticOnly) sym = new StaticError(sym);
1418                        return access(sym, pos, env.enclClass.sym.type,
1419                                      name, true);
1420                    }
1421                }
1422                if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1423                env1 = env1.outer;
1424            }
1425            log.error(pos, "not.encl.class", c);
1426            return syms.errSymbol;
1427        }
1428    
1429        /**
1430         * Resolve `c.this' for an enclosing class c that contains the
1431         * named member.
1432         * @param pos           The position to use for error reporting.
1433         * @param env           The environment current at the expression.
1434         * @param member        The member that must be contained in the result.
1435         */
1436        Symbol resolveSelfContaining(DiagnosticPosition pos,
1437                                     Env<AttrContext> env,
1438                                     Symbol member) {
1439            Name name = names._this;
1440            Env<AttrContext> env1 = env;
1441            boolean staticOnly = false;
1442            while (env1.outer != null) {
1443                if (isStatic(env1)) staticOnly = true;
1444                if (env1.enclClass.sym.isSubClass(member.owner, types) &&
1445                    isAccessible(env, env1.enclClass.sym.type, member)) {
1446                    Symbol sym = env1.info.scope.lookup(name).sym;
1447                    if (sym != null) {
1448                        if (staticOnly) sym = new StaticError(sym);
1449                        return access(sym, pos, env.enclClass.sym.type,
1450                                      name, true);
1451                    }
1452                }
1453                if ((env1.enclClass.sym.flags() & STATIC) != 0)
1454                    staticOnly = true;
1455                env1 = env1.outer;
1456            }
1457            log.error(pos, "encl.class.required", member);
1458            return syms.errSymbol;
1459        }
1460    
1461        /**
1462         * Resolve an appropriate implicit this instance for t's container.
1463         * JLS2 8.8.5.1 and 15.9.2
1464         */
1465        Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
1466            Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
1467                             ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
1468                             : resolveSelfContaining(pos, env, t.tsym)).type;
1469            if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
1470                log.error(pos, "cant.ref.before.ctor.called", "this");
1471            return thisType;
1472        }
1473    
1474    /* ***************************************************************************
1475     *  ResolveError classes, indicating error situations when accessing symbols
1476     ****************************************************************************/
1477    
1478        public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
1479            AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
1480            error.report(log, tree.pos(), type.getEnclosingType(), null, null, null);
1481        }
1482    
1483        private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
1484    
1485        public Object methodArguments(List<Type> argtypes) {
1486            return argtypes.isEmpty() ? noArgs : argtypes;
1487        }
1488    
1489        /** Root class for resolve errors.
1490         *  Instances of this class indicate "Symbol not found".
1491         *  Instances of subclass indicate other errors.
1492         */
1493        private class ResolveError extends Symbol {
1494    
1495            ResolveError(int kind, Symbol sym, String debugName) {
1496                super(kind, 0, null, null, null);
1497                this.debugName = debugName;
1498                this.sym = sym;
1499            }
1500    
1501            /** The name of the kind of error, for debugging only.
1502             */
1503            final String debugName;
1504    
1505            /** The symbol that was determined by resolution, or errSymbol if none
1506             *  was found.
1507             */
1508            final Symbol sym;
1509    
1510            /** The symbol that was a close mismatch, or null if none was found.
1511             *  wrongSym is currently set if a simgle method with the correct name, but
1512             *  the wrong parameters was found.
1513             */
1514            Symbol wrongSym;
1515    
1516            /** An auxiliary explanation set in case of instantiation errors.
1517             */
1518            JCDiagnostic explanation;
1519    
1520    
1521            public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1522                throw new AssertionError();
1523            }
1524    
1525            /** Print the (debug only) name of the kind of error.
1526             */
1527            public String toString() {
1528                return debugName + " wrongSym=" + wrongSym + " explanation=" + explanation;
1529            }
1530    
1531            /** Update wrongSym and explanation and return this.
1532             */
1533            ResolveError setWrongSym(Symbol sym, JCDiagnostic explanation) {
1534                this.wrongSym = sym;
1535                this.explanation = explanation;
1536                return this;
1537            }
1538    
1539            /** Update wrongSym and return this.
1540             */
1541            ResolveError setWrongSym(Symbol sym) {
1542                this.wrongSym = sym;
1543                this.explanation = null;
1544                return this;
1545            }
1546    
1547            public boolean exists() {
1548                switch (kind) {
1549                case HIDDEN:
1550                case ABSENT_VAR:
1551                case ABSENT_MTH:
1552                case ABSENT_TYP:
1553                    return false;
1554                default:
1555                    return true;
1556                }
1557            }
1558    
1559            /** Report error.
1560             *  @param log       The error log to be used for error reporting.
1561             *  @param pos       The position to be used for error reporting.
1562             *  @param site      The original type from where the selection took place.
1563             *  @param name      The name of the symbol to be resolved.
1564             *  @param argtypes  The invocation's value arguments,
1565             *                   if we looked for a method.
1566             *  @param typeargtypes  The invocation's type arguments,
1567             *                   if we looked for a method.
1568             */
1569            void report(Log log, DiagnosticPosition pos, Type site, Name name,
1570                        List<Type> argtypes, List<Type> typeargtypes) {
1571                if (argtypes == null)
1572                    argtypes = List.nil();
1573                if (typeargtypes == null)
1574                    typeargtypes = List.nil();
1575                if (name != names.error) {
1576                    KindName kindname = absentKind(kind);
1577                    Name idname = name;
1578                    if (kind >= WRONG_MTHS && kind <= ABSENT_MTH) {
1579                        if (isOperator(name)) {
1580                            log.error(pos, "operator.cant.be.applied",
1581                                      name, argtypes);
1582                            return;
1583                        }
1584                        if (name == names.init) {
1585                            kindname = KindName.CONSTRUCTOR;
1586                            idname = site.tsym.name;
1587                        }
1588                    }
1589                    if (kind == WRONG_MTH) {
1590                        Symbol ws = wrongSym.asMemberOf(site, types);
1591                        log.error(pos,
1592                                  "cant.apply.symbol" + (explanation != null ? ".1" : ""),
1593                                  kindname,
1594                                  ws.name == names.init ? ws.owner.name : ws.name,
1595                                  methodArguments(ws.type.getParameterTypes()),
1596                                  methodArguments(argtypes),
1597                                  kindName(ws.owner),
1598                                  ws.owner.type,
1599                                  explanation);
1600                    } else if (!site.tsym.name.isEmpty()) {
1601                        if (site.tsym.kind == PCK && !site.tsym.exists())
1602                            log.error(pos, "doesnt.exist", site.tsym);
1603                        else {
1604                            String errKey = getErrorKey("cant.resolve.location",
1605                                                        argtypes, typeargtypes,
1606                                                        kindname);
1607                            log.error(pos, errKey, kindname, idname, //symbol kindname, name
1608                                      typeargtypes, argtypes, //type parameters and arguments (if any)
1609                                      typeKindName(site), site); //location kindname, type
1610                        }
1611                    } else {
1612                        String errKey = getErrorKey("cant.resolve",
1613                                                    argtypes, typeargtypes,
1614                                                    kindname);
1615                        log.error(pos, errKey, kindname, idname, //symbol kindname, name
1616                                  typeargtypes, argtypes); //type parameters and arguments (if any)
1617                    }
1618                }
1619            }
1620            //where
1621            String getErrorKey(String key, List<Type> argtypes, List<Type> typeargtypes, KindName kindname) {
1622                String suffix = "";
1623                switch (kindname) {
1624                    case METHOD:
1625                    case CONSTRUCTOR: {
1626                        suffix += ".args";
1627                        suffix += typeargtypes.nonEmpty() ? ".params" : "";
1628                    }
1629                }
1630                return key + suffix;
1631            }
1632    
1633            /** A name designates an operator if it consists
1634             *  of a non-empty sequence of operator symbols +-~!/*%&|^<>=
1635             */
1636            boolean isOperator(Name name) {
1637                int i = 0;
1638                while (i < name.getByteLength() &&
1639                       "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
1640                return i > 0 && i == name.getByteLength();
1641            }
1642        }
1643    
1644        /** Resolve error class indicating that a symbol is not accessible.
1645         */
1646        class AccessError extends ResolveError {
1647    
1648            AccessError(Symbol sym) {
1649                this(null, null, sym);
1650            }
1651    
1652            AccessError(Env<AttrContext> env, Type site, Symbol sym) {
1653                super(HIDDEN, sym, "access error");
1654                this.env = env;
1655                this.site = site;
1656                if (debugResolve)
1657                    log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
1658            }
1659    
1660            private Env<AttrContext> env;
1661            private Type site;
1662    
1663            /** Report error.
1664             *  @param log       The error log to be used for error reporting.
1665             *  @param pos       The position to be used for error reporting.
1666             *  @param site      The original type from where the selection took place.
1667             *  @param name      The name of the symbol to be resolved.
1668             *  @param argtypes  The invocation's value arguments,
1669             *                   if we looked for a method.
1670             *  @param typeargtypes  The invocation's type arguments,
1671             *                   if we looked for a method.
1672             */
1673            void report(Log log, DiagnosticPosition pos, Type site, Name name,
1674                        List<Type> argtypes, List<Type> typeargtypes) {
1675                if (sym.owner.type.tag != ERROR) {
1676                    if (sym.name == names.init && sym.owner != site.tsym)
1677                        new ResolveError(ABSENT_MTH, sym.owner, "absent method " + sym).report(
1678                            log, pos, site, name, argtypes, typeargtypes);
1679                    if ((sym.flags() & PUBLIC) != 0
1680                        || (env != null && this.site != null
1681                            && !isAccessible(env, this.site)))
1682                        log.error(pos, "not.def.access.class.intf.cant.access",
1683                            sym, sym.location());
1684                    else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0)
1685                        log.error(pos, "report.access", sym,
1686                                  asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
1687                                  sym.location());
1688                    else
1689                        log.error(pos, "not.def.public.cant.access",
1690                                  sym, sym.location());
1691                }
1692            }
1693        }
1694    
1695        /** Resolve error class indicating that an instance member was accessed
1696         *  from a static context.
1697         */
1698        class StaticError extends ResolveError {
1699            StaticError(Symbol sym) {
1700                super(STATICERR, sym, "static error");
1701            }
1702    
1703            /** Report error.
1704             *  @param log       The error log to be used for error reporting.
1705             *  @param pos       The position to be used for error reporting.
1706             *  @param site      The original type from where the selection took place.
1707             *  @param name      The name of the symbol to be resolved.
1708             *  @param argtypes  The invocation's value arguments,
1709             *                   if we looked for a method.
1710             *  @param typeargtypes  The invocation's type arguments,
1711             *                   if we looked for a method.
1712             */
1713            void report(Log log,
1714                        DiagnosticPosition pos,
1715                        Type site,
1716                        Name name,
1717                        List<Type> argtypes,
1718                        List<Type> typeargtypes) {
1719                Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
1720                    ? types.erasure(sym.type).tsym
1721                    : sym);
1722                log.error(pos, "non-static.cant.be.ref",
1723                          kindName(sym), errSym);
1724            }
1725        }
1726    
1727        /** Resolve error class indicating an ambiguous reference.
1728         */
1729        class AmbiguityError extends ResolveError {
1730            Symbol sym1;
1731            Symbol sym2;
1732    
1733            AmbiguityError(Symbol sym1, Symbol sym2) {
1734                super(AMBIGUOUS, sym1, "ambiguity error");
1735                this.sym1 = sym1;
1736                this.sym2 = sym2;
1737            }
1738    
1739            /** Report error.
1740             *  @param log       The error log to be used for error reporting.
1741             *  @param pos       The position to be used for error reporting.
1742             *  @param site      The original type from where the selection took place.
1743             *  @param name      The name of the symbol to be resolved.
1744             *  @param argtypes  The invocation's value arguments,
1745             *                   if we looked for a method.
1746             *  @param typeargtypes  The invocation's type arguments,
1747             *                   if we looked for a method.
1748             */
1749            void report(Log log, DiagnosticPosition pos, Type site, Name name,
1750                        List<Type> argtypes, List<Type> typeargtypes) {
1751                AmbiguityError pair = this;
1752                while (true) {
1753                    if (pair.sym1.kind == AMBIGUOUS)
1754                        pair = (AmbiguityError)pair.sym1;
1755                    else if (pair.sym2.kind == AMBIGUOUS)
1756                        pair = (AmbiguityError)pair.sym2;
1757                    else break;
1758                }
1759                Name sname = pair.sym1.name;
1760                if (sname == names.init) sname = pair.sym1.owner.name;
1761                log.error(pos, "ref.ambiguous", sname,
1762                          kindName(pair.sym1),
1763                          pair.sym1,
1764                          pair.sym1.location(site, types),
1765                          kindName(pair.sym2),
1766                          pair.sym2,
1767                          pair.sym2.location(site, types));
1768            }
1769        }
1770    
1771        enum MethodResolutionPhase {
1772            BASIC(false, false),
1773            BOX(true, false),
1774            VARARITY(true, true);
1775    
1776            boolean isBoxingRequired;
1777            boolean isVarargsRequired;
1778    
1779            MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
1780               this.isBoxingRequired = isBoxingRequired;
1781               this.isVarargsRequired = isVarargsRequired;
1782            }
1783    
1784            public boolean isBoxingRequired() {
1785                return isBoxingRequired;
1786            }
1787    
1788            public boolean isVarargsRequired() {
1789                return isVarargsRequired;
1790            }
1791    
1792            public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
1793                return (varargsEnabled || !isVarargsRequired) &&
1794                       (boxingEnabled || !isBoxingRequired);
1795            }
1796        }
1797    
1798        private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
1799            new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
1800    
1801        final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
1802    
1803        private MethodResolutionPhase firstErroneousResolutionPhase() {
1804            MethodResolutionPhase bestSoFar = BASIC;
1805            Symbol sym = methodNotFound;
1806            List<MethodResolutionPhase> steps = methodResolutionSteps;
1807            while (steps.nonEmpty() &&
1808                   steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
1809                   sym.kind >= WRONG_MTHS) {
1810                sym = methodResolutionCache.get(steps.head);
1811                bestSoFar = steps.head;
1812                steps = steps.tail;
1813            }
1814            return bestSoFar;
1815        }
1816    }