src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java

Wed, 09 Jul 2014 10:49:32 -0400

author
vromero
date
Wed, 09 Jul 2014 10:49:32 -0400
changeset 2567
9a3e5ce68cef
parent 2564
ced008063508
child 2702
9ca8d8713094
child 2730
a513711d6171
permissions
-rw-r--r--

8033483: Should ignore nested lambda bodies during overload resolution
Reviewed-by: mcimadamore, dlsmith

     1 /*
     2  * Copyright (c) 2012, 2014, 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.source.tree.LambdaExpressionTree.BodyKind;
    29 import com.sun.tools.javac.code.*;
    30 import com.sun.tools.javac.tree.*;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    33 import com.sun.tools.javac.code.Symbol.*;
    34 import com.sun.tools.javac.code.Type.*;
    35 import com.sun.tools.javac.comp.Attr.ResultInfo;
    36 import com.sun.tools.javac.comp.Infer.InferenceContext;
    37 import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase;
    38 import com.sun.tools.javac.tree.JCTree.*;
    40 import java.util.ArrayList;
    41 import java.util.Collections;
    42 import java.util.EnumSet;
    43 import java.util.LinkedHashMap;
    44 import java.util.LinkedHashSet;
    45 import java.util.Map;
    46 import java.util.Set;
    47 import java.util.WeakHashMap;
    49 import static com.sun.tools.javac.code.Kinds.VAL;
    50 import static com.sun.tools.javac.code.TypeTag.*;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 /**
    54  * This is an helper class that is used to perform deferred type-analysis.
    55  * Each time a poly expression occurs in argument position, javac attributes it
    56  * with a temporary 'deferred type' that is checked (possibly multiple times)
    57  * against an expected formal type.
    58  *
    59  *  <p><b>This is NOT part of any supported API.
    60  *  If you write code that depends on this, you do so at your own risk.
    61  *  This code and its internal interfaces are subject to change or
    62  *  deletion without notice.</b>
    63  */
    64 public class DeferredAttr extends JCTree.Visitor {
    65     protected static final Context.Key<DeferredAttr> deferredAttrKey =
    66         new Context.Key<DeferredAttr>();
    68     final Attr attr;
    69     final Check chk;
    70     final JCDiagnostic.Factory diags;
    71     final Enter enter;
    72     final Infer infer;
    73     final Resolve rs;
    74     final Log log;
    75     final Symtab syms;
    76     final TreeMaker make;
    77     final Types types;
    78     final Flow flow;
    79     final Names names;
    80     final TypeEnvs typeEnvs;
    82     public static DeferredAttr instance(Context context) {
    83         DeferredAttr instance = context.get(deferredAttrKey);
    84         if (instance == null)
    85             instance = new DeferredAttr(context);
    86         return instance;
    87     }
    89     protected DeferredAttr(Context context) {
    90         context.put(deferredAttrKey, this);
    91         attr = Attr.instance(context);
    92         chk = Check.instance(context);
    93         diags = JCDiagnostic.Factory.instance(context);
    94         enter = Enter.instance(context);
    95         infer = Infer.instance(context);
    96         rs = Resolve.instance(context);
    97         log = Log.instance(context);
    98         syms = Symtab.instance(context);
    99         make = TreeMaker.instance(context);
   100         types = Types.instance(context);
   101         flow = Flow.instance(context);
   102         names = Names.instance(context);
   103         stuckTree = make.Ident(names.empty).setType(Type.stuckType);
   104         typeEnvs = TypeEnvs.instance(context);
   105         emptyDeferredAttrContext =
   106             new DeferredAttrContext(AttrMode.CHECK, null, MethodResolutionPhase.BOX, infer.emptyContext, null, null) {
   107                 @Override
   108                 void addDeferredAttrNode(DeferredType dt, ResultInfo ri, DeferredStuckPolicy deferredStuckPolicy) {
   109                     Assert.error("Empty deferred context!");
   110                 }
   111                 @Override
   112                 void complete() {
   113                     Assert.error("Empty deferred context!");
   114                 }
   116                 @Override
   117                 public String toString() {
   118                     return "Empty deferred context!";
   119                 }
   120             };
   121     }
   123     /** shared tree for stuck expressions */
   124     final JCTree stuckTree;
   126     /**
   127      * This type represents a deferred type. A deferred type starts off with
   128      * no information on the underlying expression type. Such info needs to be
   129      * discovered through type-checking the deferred type against a target-type.
   130      * Every deferred type keeps a pointer to the AST node from which it originated.
   131      */
   132     public class DeferredType extends Type {
   134         public JCExpression tree;
   135         Env<AttrContext> env;
   136         AttrMode mode;
   137         SpeculativeCache speculativeCache;
   139         DeferredType(JCExpression tree, Env<AttrContext> env) {
   140             super(null);
   141             this.tree = tree;
   142             this.env = attr.copyEnv(env);
   143             this.speculativeCache = new SpeculativeCache();
   144         }
   146         @Override
   147         public TypeTag getTag() {
   148             return DEFERRED;
   149         }
   151         @Override
   152         public String toString() {
   153             return "DeferredType";
   154         }
   156         /**
   157          * A speculative cache is used to keep track of all overload resolution rounds
   158          * that triggered speculative attribution on a given deferred type. Each entry
   159          * stores a pointer to the speculative tree and the resolution phase in which the entry
   160          * has been added.
   161          */
   162         class SpeculativeCache {
   164             private Map<Symbol, List<Entry>> cache =
   165                     new WeakHashMap<Symbol, List<Entry>>();
   167             class Entry {
   168                 JCTree speculativeTree;
   169                 ResultInfo resultInfo;
   171                 public Entry(JCTree speculativeTree, ResultInfo resultInfo) {
   172                     this.speculativeTree = speculativeTree;
   173                     this.resultInfo = resultInfo;
   174                 }
   176                 boolean matches(MethodResolutionPhase phase) {
   177                     return resultInfo.checkContext.deferredAttrContext().phase == phase;
   178                 }
   179             }
   181             /**
   182              * Retrieve a speculative cache entry corresponding to given symbol
   183              * and resolution phase
   184              */
   185             Entry get(Symbol msym, MethodResolutionPhase phase) {
   186                 List<Entry> entries = cache.get(msym);
   187                 if (entries == null) return null;
   188                 for (Entry e : entries) {
   189                     if (e.matches(phase)) return e;
   190                 }
   191                 return null;
   192             }
   194             /**
   195              * Stores a speculative cache entry corresponding to given symbol
   196              * and resolution phase
   197              */
   198             void put(JCTree speculativeTree, ResultInfo resultInfo) {
   199                 Symbol msym = resultInfo.checkContext.deferredAttrContext().msym;
   200                 List<Entry> entries = cache.get(msym);
   201                 if (entries == null) {
   202                     entries = List.nil();
   203                 }
   204                 cache.put(msym, entries.prepend(new Entry(speculativeTree, resultInfo)));
   205             }
   206         }
   208         /**
   209          * Get the type that has been computed during a speculative attribution round
   210          */
   211         Type speculativeType(Symbol msym, MethodResolutionPhase phase) {
   212             SpeculativeCache.Entry e = speculativeCache.get(msym, phase);
   213             return e != null ? e.speculativeTree.type : Type.noType;
   214         }
   216         /**
   217          * Check a deferred type against a potential target-type. Depending on
   218          * the current attribution mode, a normal vs. speculative attribution
   219          * round is performed on the underlying AST node. There can be only one
   220          * speculative round for a given target method symbol; moreover, a normal
   221          * attribution round must follow one or more speculative rounds.
   222          */
   223         Type check(ResultInfo resultInfo) {
   224             DeferredStuckPolicy deferredStuckPolicy;
   225             if (resultInfo.pt.hasTag(NONE) || resultInfo.pt.isErroneous()) {
   226                 deferredStuckPolicy = dummyStuckPolicy;
   227             } else if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.SPECULATIVE) {
   228                 deferredStuckPolicy = new OverloadStuckPolicy(resultInfo, this);
   229             } else {
   230                 deferredStuckPolicy = new CheckStuckPolicy(resultInfo, this);
   231             }
   232             return check(resultInfo, deferredStuckPolicy, basicCompleter);
   233         }
   235         private Type check(ResultInfo resultInfo, DeferredStuckPolicy deferredStuckPolicy,
   236                 DeferredTypeCompleter deferredTypeCompleter) {
   237             DeferredAttrContext deferredAttrContext =
   238                     resultInfo.checkContext.deferredAttrContext();
   239             Assert.check(deferredAttrContext != emptyDeferredAttrContext);
   240             if (deferredStuckPolicy.isStuck()) {
   241                 deferredAttrContext.addDeferredAttrNode(this, resultInfo, deferredStuckPolicy);
   242                 return Type.noType;
   243             } else {
   244                 try {
   245                     return deferredTypeCompleter.complete(this, resultInfo, deferredAttrContext);
   246                 } finally {
   247                     mode = deferredAttrContext.mode;
   248                 }
   249             }
   250         }
   251     }
   253     /**
   254      * A completer for deferred types. Defines an entry point for type-checking
   255      * a deferred type.
   256      */
   257     interface DeferredTypeCompleter {
   258         /**
   259          * Entry point for type-checking a deferred type. Depending on the
   260          * circumstances, type-checking could amount to full attribution
   261          * or partial structural check (aka potential applicability).
   262          */
   263         Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext);
   264     }
   267     /**
   268      * A basic completer for deferred types. This completer type-checks a deferred type
   269      * using attribution; depending on the attribution mode, this could be either standard
   270      * or speculative attribution.
   271      */
   272     DeferredTypeCompleter basicCompleter = new DeferredTypeCompleter() {
   273         public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   274             switch (deferredAttrContext.mode) {
   275                 case SPECULATIVE:
   276                     //Note: if a symbol is imported twice we might do two identical
   277                     //speculative rounds...
   278                     Assert.check(dt.mode == null || dt.mode == AttrMode.SPECULATIVE);
   279                     JCTree speculativeTree = attribSpeculative(dt.tree, dt.env, resultInfo);
   280                     dt.speculativeCache.put(speculativeTree, resultInfo);
   281                     return speculativeTree.type;
   282                 case CHECK:
   283                     Assert.check(dt.mode != null);
   284                     return attr.attribTree(dt.tree, dt.env, resultInfo);
   285             }
   286             Assert.error();
   287             return null;
   288         }
   289     };
   291     DeferredTypeCompleter dummyCompleter = new DeferredTypeCompleter() {
   292         public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   293             Assert.check(deferredAttrContext.mode == AttrMode.CHECK);
   294             return dt.tree.type = Type.stuckType;
   295         }
   296     };
   298     /**
   299      * Policy for detecting stuck expressions. Different criteria might cause
   300      * an expression to be judged as stuck, depending on whether the check
   301      * is performed during overload resolution or after most specific.
   302      */
   303     interface DeferredStuckPolicy {
   304         /**
   305          * Has the policy detected that a given expression should be considered stuck?
   306          */
   307         boolean isStuck();
   308         /**
   309          * Get the set of inference variables a given expression depends upon.
   310          */
   311         Set<Type> stuckVars();
   312         /**
   313          * Get the set of inference variables which might get new constraints
   314          * if a given expression is being type-checked.
   315          */
   316         Set<Type> depVars();
   317     }
   319     /**
   320      * Basic stuck policy; an expression is never considered to be stuck.
   321      */
   322     DeferredStuckPolicy dummyStuckPolicy = new DeferredStuckPolicy() {
   323         @Override
   324         public boolean isStuck() {
   325             return false;
   326         }
   327         @Override
   328         public Set<Type> stuckVars() {
   329             return Collections.emptySet();
   330         }
   331         @Override
   332         public Set<Type> depVars() {
   333             return Collections.emptySet();
   334         }
   335     };
   337     /**
   338      * The 'mode' in which the deferred type is to be type-checked
   339      */
   340     public enum AttrMode {
   341         /**
   342          * A speculative type-checking round is used during overload resolution
   343          * mainly to generate constraints on inference variables. Side-effects
   344          * arising from type-checking the expression associated with the deferred
   345          * type are reversed after the speculative round finishes. This means the
   346          * expression tree will be left in a blank state.
   347          */
   348         SPECULATIVE,
   349         /**
   350          * This is the plain type-checking mode. Produces side-effects on the underlying AST node
   351          */
   352         CHECK;
   353     }
   355     /**
   356      * Routine that performs speculative type-checking; the input AST node is
   357      * cloned (to avoid side-effects cause by Attr) and compiler state is
   358      * restored after type-checking. All diagnostics (but critical ones) are
   359      * disabled during speculative type-checking.
   360      */
   361     JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   362         final JCTree newTree = new TreeCopier<Object>(make).copy(tree);
   363         Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared()));
   364         speculativeEnv.info.scope.owner = env.info.scope.owner;
   365         Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
   366                 new Log.DeferredDiagnosticHandler(log, new Filter<JCDiagnostic>() {
   367             public boolean accepts(final JCDiagnostic d) {
   368                 class PosScanner extends TreeScanner {
   369                     boolean found = false;
   371                     @Override
   372                     public void scan(JCTree tree) {
   373                         if (tree != null &&
   374                                 tree.pos() == d.getDiagnosticPosition()) {
   375                             found = true;
   376                         }
   377                         super.scan(tree);
   378                     }
   379                 };
   380                 PosScanner posScanner = new PosScanner();
   381                 posScanner.scan(newTree);
   382                 return posScanner.found;
   383             }
   384         });
   385         try {
   386             attr.attribTree(newTree, speculativeEnv, resultInfo);
   387             unenterScanner.scan(newTree);
   388             return newTree;
   389         } finally {
   390             unenterScanner.scan(newTree);
   391             log.popDiagnosticHandler(deferredDiagnosticHandler);
   392         }
   393     }
   394     //where
   395         protected UnenterScanner unenterScanner = new UnenterScanner();
   397         class UnenterScanner extends TreeScanner {
   398             @Override
   399             public void visitClassDef(JCClassDecl tree) {
   400                 ClassSymbol csym = tree.sym;
   401                 //if something went wrong during method applicability check
   402                 //it is possible that nested expressions inside argument expression
   403                 //are left unchecked - in such cases there's nothing to clean up.
   404                 if (csym == null) return;
   405                 typeEnvs.remove(csym);
   406                 chk.compiled.remove(csym.flatname);
   407                 syms.classes.remove(csym.flatname);
   408                 super.visitClassDef(tree);
   409             }
   410         }
   412     /**
   413      * A deferred context is created on each method check. A deferred context is
   414      * used to keep track of information associated with the method check, such as
   415      * the symbol of the method being checked, the overload resolution phase,
   416      * the kind of attribution mode to be applied to deferred types and so forth.
   417      * As deferred types are processed (by the method check routine) stuck AST nodes
   418      * are added (as new deferred attribution nodes) to this context. The complete()
   419      * routine makes sure that all pending nodes are properly processed, by
   420      * progressively instantiating all inference variables on which one or more
   421      * deferred attribution node is stuck.
   422      */
   423     class DeferredAttrContext {
   425         /** attribution mode */
   426         final AttrMode mode;
   428         /** symbol of the method being checked */
   429         final Symbol msym;
   431         /** method resolution step */
   432         final Resolve.MethodResolutionPhase phase;
   434         /** inference context */
   435         final InferenceContext inferenceContext;
   437         /** parent deferred context */
   438         final DeferredAttrContext parent;
   440         /** Warner object to report warnings */
   441         final Warner warn;
   443         /** list of deferred attribution nodes to be processed */
   444         ArrayList<DeferredAttrNode> deferredAttrNodes = new ArrayList<DeferredAttrNode>();
   446         DeferredAttrContext(AttrMode mode, Symbol msym, MethodResolutionPhase phase,
   447                 InferenceContext inferenceContext, DeferredAttrContext parent, Warner warn) {
   448             this.mode = mode;
   449             this.msym = msym;
   450             this.phase = phase;
   451             this.parent = parent;
   452             this.warn = warn;
   453             this.inferenceContext = inferenceContext;
   454         }
   456         /**
   457          * Adds a node to the list of deferred attribution nodes - used by Resolve.rawCheckArgumentsApplicable
   458          * Nodes added this way act as 'roots' for the out-of-order method checking process.
   459          */
   460         void addDeferredAttrNode(final DeferredType dt, ResultInfo resultInfo,
   461                 DeferredStuckPolicy deferredStuckPolicy) {
   462             deferredAttrNodes.add(new DeferredAttrNode(dt, resultInfo, deferredStuckPolicy));
   463         }
   465         /**
   466          * Incrementally process all nodes, by skipping 'stuck' nodes and attributing
   467          * 'unstuck' ones. If at any point no progress can be made (no 'unstuck' nodes)
   468          * some inference variable might get eagerly instantiated so that all nodes
   469          * can be type-checked.
   470          */
   471         void complete() {
   472             while (!deferredAttrNodes.isEmpty()) {
   473                 Map<Type, Set<Type>> depVarsMap = new LinkedHashMap<Type, Set<Type>>();
   474                 List<Type> stuckVars = List.nil();
   475                 boolean progress = false;
   476                 //scan a defensive copy of the node list - this is because a deferred
   477                 //attribution round can add new nodes to the list
   478                 for (DeferredAttrNode deferredAttrNode : List.from(deferredAttrNodes)) {
   479                     if (!deferredAttrNode.process(this)) {
   480                         List<Type> restStuckVars =
   481                                 List.from(deferredAttrNode.deferredStuckPolicy.stuckVars())
   482                                 .intersect(inferenceContext.restvars());
   483                         stuckVars = stuckVars.prependList(restStuckVars);
   484                         //update dependency map
   485                         for (Type t : List.from(deferredAttrNode.deferredStuckPolicy.depVars())
   486                                 .intersect(inferenceContext.restvars())) {
   487                             Set<Type> prevDeps = depVarsMap.get(t);
   488                             if (prevDeps == null) {
   489                                 prevDeps = new LinkedHashSet<Type>();
   490                                 depVarsMap.put(t, prevDeps);
   491                             }
   492                             prevDeps.addAll(restStuckVars);
   493                         }
   494                     } else {
   495                         deferredAttrNodes.remove(deferredAttrNode);
   496                         progress = true;
   497                     }
   498                 }
   499                 if (!progress) {
   500                     if (insideOverloadPhase()) {
   501                         for (DeferredAttrNode deferredNode: deferredAttrNodes) {
   502                             deferredNode.dt.tree.type = Type.noType;
   503                         }
   504                         return;
   505                     }
   506                     //remove all variables that have already been instantiated
   507                     //from the list of stuck variables
   508                     try {
   509                         inferenceContext.solveAny(stuckVars, depVarsMap, warn);
   510                         inferenceContext.notifyChange();
   511                     } catch (Infer.GraphStrategy.NodeNotFoundException ex) {
   512                         //this means that we are in speculative mode and the
   513                         //set of contraints are too tight for progess to be made.
   514                         //Just leave the remaining expressions as stuck.
   515                         break;
   516                     }
   517                 }
   518             }
   519         }
   521         private boolean insideOverloadPhase() {
   522             DeferredAttrContext dac = this;
   523             if (dac == emptyDeferredAttrContext) {
   524                 return false;
   525             }
   526             if (dac.mode == AttrMode.SPECULATIVE) {
   527                 return true;
   528             }
   529             return dac.parent.insideOverloadPhase();
   530         }
   531     }
   533     /**
   534      * Class representing a deferred attribution node. It keeps track of
   535      * a deferred type, along with the expected target type information.
   536      */
   537     class DeferredAttrNode {
   539         /** underlying deferred type */
   540         DeferredType dt;
   542         /** underlying target type information */
   543         ResultInfo resultInfo;
   545         /** stuck policy associated with this node */
   546         DeferredStuckPolicy deferredStuckPolicy;
   548         DeferredAttrNode(DeferredType dt, ResultInfo resultInfo, DeferredStuckPolicy deferredStuckPolicy) {
   549             this.dt = dt;
   550             this.resultInfo = resultInfo;
   551             this.deferredStuckPolicy = deferredStuckPolicy;
   552         }
   554         /**
   555          * Process a deferred attribution node.
   556          * Invariant: a stuck node cannot be processed.
   557          */
   558         @SuppressWarnings("fallthrough")
   559         boolean process(final DeferredAttrContext deferredAttrContext) {
   560             switch (deferredAttrContext.mode) {
   561                 case SPECULATIVE:
   562                     if (deferredStuckPolicy.isStuck()) {
   563                         dt.check(resultInfo, dummyStuckPolicy, new StructuralStuckChecker());
   564                         return true;
   565                     } else {
   566                         Assert.error("Cannot get here");
   567                     }
   568                 case CHECK:
   569                     if (deferredStuckPolicy.isStuck()) {
   570                         //stuck expression - see if we can propagate
   571                         if (deferredAttrContext.parent != emptyDeferredAttrContext &&
   572                                 Type.containsAny(deferredAttrContext.parent.inferenceContext.inferencevars,
   573                                         List.from(deferredStuckPolicy.stuckVars()))) {
   574                             deferredAttrContext.parent.addDeferredAttrNode(dt,
   575                                     resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
   576                                 @Override
   577                                 public InferenceContext inferenceContext() {
   578                                     return deferredAttrContext.parent.inferenceContext;
   579                                 }
   580                                 @Override
   581                                 public DeferredAttrContext deferredAttrContext() {
   582                                     return deferredAttrContext.parent;
   583                                 }
   584                             }), deferredStuckPolicy);
   585                             dt.tree.type = Type.stuckType;
   586                             return true;
   587                         } else {
   588                             return false;
   589                         }
   590                     } else {
   591                         Assert.check(!deferredAttrContext.insideOverloadPhase(),
   592                                 "attribution shouldn't be happening here");
   593                         ResultInfo instResultInfo =
   594                                 resultInfo.dup(deferredAttrContext.inferenceContext.asInstType(resultInfo.pt));
   595                         dt.check(instResultInfo, dummyStuckPolicy, basicCompleter);
   596                         return true;
   597                     }
   598                 default:
   599                     throw new AssertionError("Bad mode");
   600             }
   601         }
   603         /**
   604          * Structural checker for stuck expressions
   605          */
   606         class StructuralStuckChecker extends TreeScanner implements DeferredTypeCompleter {
   608             ResultInfo resultInfo;
   609             InferenceContext inferenceContext;
   610             Env<AttrContext> env;
   612             public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   613                 this.resultInfo = resultInfo;
   614                 this.inferenceContext = deferredAttrContext.inferenceContext;
   615                 this.env = dt.env;
   616                 dt.tree.accept(this);
   617                 dt.speculativeCache.put(stuckTree, resultInfo);
   618                 return Type.noType;
   619             }
   621             @Override
   622             public void visitLambda(JCLambda tree) {
   623                 Check.CheckContext checkContext = resultInfo.checkContext;
   624                 Type pt = resultInfo.pt;
   625                 if (!inferenceContext.inferencevars.contains(pt)) {
   626                     //must be a functional descriptor
   627                     Type descriptorType = null;
   628                     try {
   629                         descriptorType = types.findDescriptorType(pt);
   630                     } catch (Types.FunctionDescriptorLookupError ex) {
   631                         checkContext.report(null, ex.getDiagnostic());
   632                     }
   634                     if (descriptorType.getParameterTypes().length() != tree.params.length()) {
   635                         checkContext.report(tree,
   636                                 diags.fragment("incompatible.arg.types.in.lambda"));
   637                     }
   639                     Type currentReturnType = descriptorType.getReturnType();
   640                     boolean returnTypeIsVoid = currentReturnType.hasTag(VOID);
   641                     if (tree.getBodyKind() == BodyKind.EXPRESSION) {
   642                         boolean isExpressionCompatible = !returnTypeIsVoid ||
   643                             TreeInfo.isExpressionStatement((JCExpression)tree.getBody());
   644                         if (!isExpressionCompatible) {
   645                             resultInfo.checkContext.report(tree.pos(),
   646                                 diags.fragment("incompatible.ret.type.in.lambda",
   647                                     diags.fragment("missing.ret.val", currentReturnType)));
   648                         }
   649                     } else {
   650                         LambdaBodyStructChecker lambdaBodyChecker =
   651                                 new LambdaBodyStructChecker();
   653                         tree.body.accept(lambdaBodyChecker);
   654                         boolean isVoidCompatible = lambdaBodyChecker.isVoidCompatible;
   656                         if (returnTypeIsVoid) {
   657                             if (!isVoidCompatible) {
   658                                 resultInfo.checkContext.report(tree.pos(),
   659                                     diags.fragment("unexpected.ret.val"));
   660                             }
   661                         } else {
   662                             boolean isValueCompatible = lambdaBodyChecker.isPotentiallyValueCompatible
   663                                 && !canLambdaBodyCompleteNormally(tree);
   664                             if (!isValueCompatible && !isVoidCompatible) {
   665                                 log.error(tree.body.pos(),
   666                                     "lambda.body.neither.value.nor.void.compatible");
   667                             }
   669                             if (!isValueCompatible) {
   670                                 resultInfo.checkContext.report(tree.pos(),
   671                                     diags.fragment("incompatible.ret.type.in.lambda",
   672                                         diags.fragment("missing.ret.val", currentReturnType)));
   673                             }
   674                         }
   675                     }
   676                 }
   677             }
   679             boolean canLambdaBodyCompleteNormally(JCLambda tree) {
   680                 JCLambda newTree = new TreeCopier<>(make).copy(tree);
   681                 /* attr.lambdaEnv will create a meaningful env for the
   682                  * lambda expression. This is specially useful when the
   683                  * lambda is used as the init of a field. But we need to
   684                  * remove any added symbol.
   685                  */
   686                 Env<AttrContext> localEnv = attr.lambdaEnv(newTree, env);
   687                 try {
   688                     List<JCVariableDecl> tmpParams = newTree.params;
   689                     while (tmpParams.nonEmpty()) {
   690                         tmpParams.head.vartype = make.at(tmpParams.head).Type(syms.errType);
   691                         tmpParams = tmpParams.tail;
   692                     }
   694                     attr.attribStats(newTree.params, localEnv);
   696                     /* set pt to Type.noType to avoid generating any bound
   697                      * which may happen if lambda's return type is an
   698                      * inference variable
   699                      */
   700                     Attr.ResultInfo bodyResultInfo = attr.new ResultInfo(VAL, Type.noType);
   701                     localEnv.info.returnResult = bodyResultInfo;
   703                     // discard any log output
   704                     Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
   705                     try {
   706                         JCBlock body = (JCBlock)newTree.body;
   707                         /* we need to attribute the lambda body before
   708                          * doing the aliveness analysis. This is because
   709                          * constant folding occurs during attribution
   710                          * and the reachability of some statements depends
   711                          * on constant values, for example:
   712                          *
   713                          *     while (true) {...}
   714                          */
   715                         attr.attribStats(body.stats, localEnv);
   717                         attr.preFlow(newTree);
   718                         /* make an aliveness / reachability analysis of the lambda
   719                          * to determine if it can complete normally
   720                          */
   721                         flow.analyzeLambda(localEnv, newTree, make, true);
   722                     } finally {
   723                         log.popDiagnosticHandler(diagHandler);
   724                     }
   725                     return newTree.canCompleteNormally;
   726                 } finally {
   727                     JCBlock body = (JCBlock)newTree.body;
   728                     unenterScanner.scan(body.stats);
   729                     localEnv.info.scope.leave();
   730                 }
   731             }
   733             @Override
   734             public void visitNewClass(JCNewClass tree) {
   735                 //do nothing
   736             }
   738             @Override
   739             public void visitApply(JCMethodInvocation tree) {
   740                 //do nothing
   741             }
   743             @Override
   744             public void visitReference(JCMemberReference tree) {
   745                 Check.CheckContext checkContext = resultInfo.checkContext;
   746                 Type pt = resultInfo.pt;
   747                 if (!inferenceContext.inferencevars.contains(pt)) {
   748                     try {
   749                         types.findDescriptorType(pt);
   750                     } catch (Types.FunctionDescriptorLookupError ex) {
   751                         checkContext.report(null, ex.getDiagnostic());
   752                     }
   753                     Env<AttrContext> localEnv = env.dup(tree);
   754                     JCExpression exprTree = (JCExpression)attribSpeculative(tree.getQualifierExpression(), localEnv,
   755                             attr.memberReferenceQualifierResult(tree));
   756                     ListBuffer<Type> argtypes = new ListBuffer<>();
   757                     for (Type t : types.findDescriptorType(pt).getParameterTypes()) {
   758                         argtypes.append(Type.noType);
   759                     }
   760                     JCMemberReference mref2 = new TreeCopier<Void>(make).copy(tree);
   761                     mref2.expr = exprTree;
   762                     Symbol lookupSym =
   763                             rs.resolveMemberReferenceByArity(localEnv, mref2, exprTree.type,
   764                                 tree.name, argtypes.toList(), inferenceContext);
   765                     switch (lookupSym.kind) {
   766                         //note: as argtypes are erroneous types, type-errors must
   767                         //have been caused by arity mismatch
   768                         case Kinds.ABSENT_MTH:
   769                         case Kinds.WRONG_MTH:
   770                         case Kinds.WRONG_MTHS:
   771                         case Kinds.WRONG_STATICNESS:
   772                            checkContext.report(tree, diags.fragment("incompatible.arg.types.in.mref"));
   773                     }
   774                 }
   775             }
   776         }
   778         /* This visitor looks for return statements, its analysis will determine if
   779          * a lambda body is void or value compatible. We must analyze return
   780          * statements contained in the lambda body only, thus any return statement
   781          * contained in an inner class or inner lambda body, should be ignored.
   782          */
   783         class LambdaBodyStructChecker extends TreeScanner {
   784             boolean isVoidCompatible = true;
   785             boolean isPotentiallyValueCompatible = true;
   787             @Override
   788             public void visitClassDef(JCClassDecl tree) {
   789                 // do nothing
   790             }
   792             @Override
   793             public void visitLambda(JCLambda tree) {
   794                 // do nothing
   795             }
   797             @Override
   798             public void visitNewClass(JCNewClass tree) {
   799                 // do nothing
   800             }
   802             @Override
   803             public void visitReturn(JCReturn tree) {
   804                 if (tree.expr != null) {
   805                     isVoidCompatible = false;
   806                 } else {
   807                     isPotentiallyValueCompatible = false;
   808                 }
   809             }
   810         }
   811     }
   813     /** an empty deferred attribution context - all methods throw exceptions */
   814     final DeferredAttrContext emptyDeferredAttrContext;
   816     /**
   817      * Map a list of types possibly containing one or more deferred types
   818      * into a list of ordinary types. Each deferred type D is mapped into a type T,
   819      * where T is computed by retrieving the type that has already been
   820      * computed for D during a previous deferred attribution round of the given kind.
   821      */
   822     class DeferredTypeMap extends Type.Mapping {
   824         DeferredAttrContext deferredAttrContext;
   826         protected DeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   827             super(String.format("deferredTypeMap[%s]", mode));
   828             this.deferredAttrContext = new DeferredAttrContext(mode, msym, phase,
   829                     infer.emptyContext, emptyDeferredAttrContext, types.noWarnings);
   830         }
   832         @Override
   833         public Type apply(Type t) {
   834             if (!t.hasTag(DEFERRED)) {
   835                 return t.map(this);
   836             } else {
   837                 DeferredType dt = (DeferredType)t;
   838                 return typeOf(dt);
   839             }
   840         }
   842         protected Type typeOf(DeferredType dt) {
   843             switch (deferredAttrContext.mode) {
   844                 case CHECK:
   845                     return dt.tree.type == null ? Type.noType : dt.tree.type;
   846                 case SPECULATIVE:
   847                     return dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase);
   848             }
   849             Assert.error();
   850             return null;
   851         }
   852     }
   854     /**
   855      * Specialized recovery deferred mapping.
   856      * Each deferred type D is mapped into a type T, where T is computed either by
   857      * (i) retrieving the type that has already been computed for D during a previous
   858      * attribution round (as before), or (ii) by synthesizing a new type R for D
   859      * (the latter step is useful in a recovery scenario).
   860      */
   861     public class RecoveryDeferredTypeMap extends DeferredTypeMap {
   863         public RecoveryDeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   864             super(mode, msym, phase != null ? phase : MethodResolutionPhase.BOX);
   865         }
   867         @Override
   868         protected Type typeOf(DeferredType dt) {
   869             Type owntype = super.typeOf(dt);
   870             return owntype == Type.noType ?
   871                         recover(dt) : owntype;
   872         }
   874         /**
   875          * Synthesize a type for a deferred type that hasn't been previously
   876          * reduced to an ordinary type. Functional deferred types and conditionals
   877          * are mapped to themselves, in order to have a richer diagnostic
   878          * representation. Remaining deferred types are attributed using
   879          * a default expected type (j.l.Object).
   880          */
   881         private Type recover(DeferredType dt) {
   882             dt.check(attr.new RecoveryInfo(deferredAttrContext) {
   883                 @Override
   884                 protected Type check(DiagnosticPosition pos, Type found) {
   885                     return chk.checkNonVoid(pos, super.check(pos, found));
   886                 }
   887             });
   888             return super.apply(dt);
   889         }
   890     }
   892     /**
   893      * A special tree scanner that would only visit portions of a given tree.
   894      * The set of nodes visited by the scanner can be customized at construction-time.
   895      */
   896     abstract static class FilterScanner extends TreeScanner {
   898         final Filter<JCTree> treeFilter;
   900         FilterScanner(final Set<JCTree.Tag> validTags) {
   901             this.treeFilter = new Filter<JCTree>() {
   902                 public boolean accepts(JCTree t) {
   903                     return validTags.contains(t.getTag());
   904                 }
   905             };
   906         }
   908         @Override
   909         public void scan(JCTree tree) {
   910             if (tree != null) {
   911                 if (treeFilter.accepts(tree)) {
   912                     super.scan(tree);
   913                 } else {
   914                     skip(tree);
   915                 }
   916             }
   917         }
   919         /**
   920          * handler that is executed when a node has been discarded
   921          */
   922         void skip(JCTree tree) {}
   923     }
   925     /**
   926      * A tree scanner suitable for visiting the target-type dependent nodes of
   927      * a given argument expression.
   928      */
   929     static class PolyScanner extends FilterScanner {
   931         PolyScanner() {
   932             super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE));
   933         }
   934     }
   936     /**
   937      * A tree scanner suitable for visiting the target-type dependent nodes nested
   938      * within a lambda expression body.
   939      */
   940     static class LambdaReturnScanner extends FilterScanner {
   942         LambdaReturnScanner() {
   943             super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
   944                     FORLOOP, IF, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
   945         }
   946     }
   948     /**
   949      * This visitor is used to check that structural expressions conform
   950      * to their target - this step is required as inference could end up
   951      * inferring types that make some of the nested expressions incompatible
   952      * with their corresponding instantiated target
   953      */
   954     class CheckStuckPolicy extends PolyScanner implements DeferredStuckPolicy, Infer.FreeTypeListener {
   956         Type pt;
   957         Infer.InferenceContext inferenceContext;
   958         Set<Type> stuckVars = new LinkedHashSet<Type>();
   959         Set<Type> depVars = new LinkedHashSet<Type>();
   961         @Override
   962         public boolean isStuck() {
   963             return !stuckVars.isEmpty();
   964         }
   966         @Override
   967         public Set<Type> stuckVars() {
   968             return stuckVars;
   969         }
   971         @Override
   972         public Set<Type> depVars() {
   973             return depVars;
   974         }
   976         public CheckStuckPolicy(ResultInfo resultInfo, DeferredType dt) {
   977             this.pt = resultInfo.pt;
   978             this.inferenceContext = resultInfo.checkContext.inferenceContext();
   979             scan(dt.tree);
   980             if (!stuckVars.isEmpty()) {
   981                 resultInfo.checkContext.inferenceContext()
   982                         .addFreeTypeListener(List.from(stuckVars), this);
   983             }
   984         }
   986         @Override
   987         public void typesInferred(InferenceContext inferenceContext) {
   988             stuckVars.clear();
   989         }
   991         @Override
   992         public void visitLambda(JCLambda tree) {
   993             if (inferenceContext.inferenceVars().contains(pt)) {
   994                 stuckVars.add(pt);
   995             }
   996             if (!types.isFunctionalInterface(pt)) {
   997                 return;
   998             }
   999             Type descType = types.findDescriptorType(pt);
  1000             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
  1001             if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1002                     freeArgVars.nonEmpty()) {
  1003                 stuckVars.addAll(freeArgVars);
  1004                 depVars.addAll(inferenceContext.freeVarsIn(descType.getReturnType()));
  1006             scanLambdaBody(tree, descType.getReturnType());
  1009         @Override
  1010         public void visitReference(JCMemberReference tree) {
  1011             scan(tree.expr);
  1012             if (inferenceContext.inferenceVars().contains(pt)) {
  1013                 stuckVars.add(pt);
  1014                 return;
  1016             if (!types.isFunctionalInterface(pt)) {
  1017                 return;
  1020             Type descType = types.findDescriptorType(pt);
  1021             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
  1022             if (freeArgVars.nonEmpty() &&
  1023                     tree.overloadKind == JCMemberReference.OverloadKind.OVERLOADED) {
  1024                 stuckVars.addAll(freeArgVars);
  1025                 depVars.addAll(inferenceContext.freeVarsIn(descType.getReturnType()));
  1029         void scanLambdaBody(JCLambda lambda, final Type pt) {
  1030             if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1031                 Type prevPt = this.pt;
  1032                 try {
  1033                     this.pt = pt;
  1034                     scan(lambda.body);
  1035                 } finally {
  1036                     this.pt = prevPt;
  1038             } else {
  1039                 LambdaReturnScanner lambdaScanner = new LambdaReturnScanner() {
  1040                     @Override
  1041                     public void visitReturn(JCReturn tree) {
  1042                         if (tree.expr != null) {
  1043                             Type prevPt = CheckStuckPolicy.this.pt;
  1044                             try {
  1045                                 CheckStuckPolicy.this.pt = pt;
  1046                                 CheckStuckPolicy.this.scan(tree.expr);
  1047                             } finally {
  1048                                 CheckStuckPolicy.this.pt = prevPt;
  1052                 };
  1053                 lambdaScanner.scan(lambda.body);
  1058     /**
  1059      * This visitor is used to check that structural expressions conform
  1060      * to their target - this step is required as inference could end up
  1061      * inferring types that make some of the nested expressions incompatible
  1062      * with their corresponding instantiated target
  1063      */
  1064     class OverloadStuckPolicy extends CheckStuckPolicy implements DeferredStuckPolicy {
  1066         boolean stuck;
  1068         @Override
  1069         public boolean isStuck() {
  1070             return super.isStuck() || stuck;
  1073         public OverloadStuckPolicy(ResultInfo resultInfo, DeferredType dt) {
  1074             super(resultInfo, dt);
  1077         @Override
  1078         public void visitLambda(JCLambda tree) {
  1079             super.visitLambda(tree);
  1080             if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  1081                 stuck = true;
  1085         @Override
  1086         public void visitReference(JCMemberReference tree) {
  1087             super.visitReference(tree);
  1088             if (tree.overloadKind == JCMemberReference.OverloadKind.OVERLOADED) {
  1089                 stuck = true;
  1094     /**
  1095      * Does the argument expression {@code expr} need speculative type-checking?
  1096      */
  1097     boolean isDeferred(Env<AttrContext> env, JCExpression expr) {
  1098         DeferredChecker dc = new DeferredChecker(env);
  1099         dc.scan(expr);
  1100         return dc.result.isPoly();
  1103     /**
  1104      * The kind of an argument expression. This is used by the analysis that
  1105      * determines as to whether speculative attribution is necessary.
  1106      */
  1107     enum ArgumentExpressionKind {
  1109         /** kind that denotes poly argument expression */
  1110         POLY,
  1111         /** kind that denotes a standalone expression */
  1112         NO_POLY,
  1113         /** kind that denotes a primitive/boxed standalone expression */
  1114         PRIMITIVE;
  1116         /**
  1117          * Does this kind denote a poly argument expression
  1118          */
  1119         public final boolean isPoly() {
  1120             return this == POLY;
  1123         /**
  1124          * Does this kind denote a primitive standalone expression
  1125          */
  1126         public final boolean isPrimitive() {
  1127             return this == PRIMITIVE;
  1130         /**
  1131          * Compute the kind of a standalone expression of a given type
  1132          */
  1133         static ArgumentExpressionKind standaloneKind(Type type, Types types) {
  1134             return types.unboxedTypeOrType(type).isPrimitive() ?
  1135                     ArgumentExpressionKind.PRIMITIVE :
  1136                     ArgumentExpressionKind.NO_POLY;
  1139         /**
  1140          * Compute the kind of a method argument expression given its symbol
  1141          */
  1142         static ArgumentExpressionKind methodKind(Symbol sym, Types types) {
  1143             Type restype = sym.type.getReturnType();
  1144             if (sym.type.hasTag(FORALL) &&
  1145                     restype.containsAny(((ForAll)sym.type).tvars)) {
  1146                 return ArgumentExpressionKind.POLY;
  1147             } else {
  1148                 return ArgumentExpressionKind.standaloneKind(restype, types);
  1153     /**
  1154      * Tree scanner used for checking as to whether an argument expression
  1155      * requires speculative attribution
  1156      */
  1157     final class DeferredChecker extends FilterScanner {
  1159         Env<AttrContext> env;
  1160         ArgumentExpressionKind result;
  1162         public DeferredChecker(Env<AttrContext> env) {
  1163             super(deferredCheckerTags);
  1164             this.env = env;
  1167         @Override
  1168         public void visitLambda(JCLambda tree) {
  1169             //a lambda is always a poly expression
  1170             result = ArgumentExpressionKind.POLY;
  1173         @Override
  1174         public void visitReference(JCMemberReference tree) {
  1175             //perform arity-based check
  1176             Env<AttrContext> localEnv = env.dup(tree);
  1177             JCExpression exprTree = (JCExpression)attribSpeculative(tree.getQualifierExpression(), localEnv,
  1178                     attr.memberReferenceQualifierResult(tree));
  1179             JCMemberReference mref2 = new TreeCopier<Void>(make).copy(tree);
  1180             mref2.expr = exprTree;
  1181             Symbol res =
  1182                     rs.getMemberReference(tree, localEnv, mref2,
  1183                         exprTree.type, tree.name);
  1184             tree.sym = res;
  1185             if (res.kind >= Kinds.ERRONEOUS ||
  1186                     res.type.hasTag(FORALL) ||
  1187                     (res.flags() & Flags.VARARGS) != 0 ||
  1188                     (TreeInfo.isStaticSelector(exprTree, tree.name.table.names) &&
  1189                     exprTree.type.isRaw())) {
  1190                 tree.overloadKind = JCMemberReference.OverloadKind.OVERLOADED;
  1191             } else {
  1192                 tree.overloadKind = JCMemberReference.OverloadKind.UNOVERLOADED;
  1194             //a method reference is always a poly expression
  1195             result = ArgumentExpressionKind.POLY;
  1198         @Override
  1199         public void visitTypeCast(JCTypeCast tree) {
  1200             //a cast is always a standalone expression
  1201             result = ArgumentExpressionKind.NO_POLY;
  1204         @Override
  1205         public void visitConditional(JCConditional tree) {
  1206             scan(tree.truepart);
  1207             if (!result.isPrimitive()) {
  1208                 result = ArgumentExpressionKind.POLY;
  1209                 return;
  1211             scan(tree.falsepart);
  1212             result = reduce(ArgumentExpressionKind.PRIMITIVE);
  1215         @Override
  1216         public void visitNewClass(JCNewClass tree) {
  1217             result = (TreeInfo.isDiamond(tree) || attr.findDiamonds) ?
  1218                     ArgumentExpressionKind.POLY : ArgumentExpressionKind.NO_POLY;
  1221         @Override
  1222         public void visitApply(JCMethodInvocation tree) {
  1223             Name name = TreeInfo.name(tree.meth);
  1225             //fast path
  1226             if (tree.typeargs.nonEmpty() ||
  1227                     name == name.table.names._this ||
  1228                     name == name.table.names._super) {
  1229                 result = ArgumentExpressionKind.NO_POLY;
  1230                 return;
  1233             //slow path
  1234             Symbol sym = quicklyResolveMethod(env, tree);
  1236             if (sym == null) {
  1237                 result = ArgumentExpressionKind.POLY;
  1238                 return;
  1241             result = analyzeCandidateMethods(sym, ArgumentExpressionKind.PRIMITIVE,
  1242                     argumentKindAnalyzer);
  1244         //where
  1245             private boolean isSimpleReceiver(JCTree rec) {
  1246                 switch (rec.getTag()) {
  1247                     case IDENT:
  1248                         return true;
  1249                     case SELECT:
  1250                         return isSimpleReceiver(((JCFieldAccess)rec).selected);
  1251                     case TYPEAPPLY:
  1252                     case TYPEARRAY:
  1253                         return true;
  1254                     case ANNOTATED_TYPE:
  1255                         return isSimpleReceiver(((JCAnnotatedType)rec).underlyingType);
  1256                     case APPLY:
  1257                         return true;
  1258                     default:
  1259                         return false;
  1262             private ArgumentExpressionKind reduce(ArgumentExpressionKind kind) {
  1263                 return argumentKindAnalyzer.reduce(result, kind);
  1265             MethodAnalyzer<ArgumentExpressionKind> argumentKindAnalyzer =
  1266                     new MethodAnalyzer<ArgumentExpressionKind>() {
  1267                 @Override
  1268                 public ArgumentExpressionKind process(MethodSymbol ms) {
  1269                     return ArgumentExpressionKind.methodKind(ms, types);
  1271                 @Override
  1272                 public ArgumentExpressionKind reduce(ArgumentExpressionKind kind1,
  1273                                                      ArgumentExpressionKind kind2) {
  1274                     switch (kind1) {
  1275                         case PRIMITIVE: return kind2;
  1276                         case NO_POLY: return kind2.isPoly() ? kind2 : kind1;
  1277                         case POLY: return kind1;
  1278                         default:
  1279                             Assert.error();
  1280                             return null;
  1283                 @Override
  1284                 public boolean shouldStop(ArgumentExpressionKind result) {
  1285                     return result.isPoly();
  1287             };
  1289         @Override
  1290         public void visitLiteral(JCLiteral tree) {
  1291             Type litType = attr.litType(tree.typetag);
  1292             result = ArgumentExpressionKind.standaloneKind(litType, types);
  1295         @Override
  1296         void skip(JCTree tree) {
  1297             result = ArgumentExpressionKind.NO_POLY;
  1300         private Symbol quicklyResolveMethod(Env<AttrContext> env, final JCMethodInvocation tree) {
  1301             final JCExpression rec = tree.meth.hasTag(SELECT) ?
  1302                     ((JCFieldAccess)tree.meth).selected :
  1303                     null;
  1305             if (rec != null && !isSimpleReceiver(rec)) {
  1306                 return null;
  1309             Type site;
  1311             if (rec != null) {
  1312                 if (rec.hasTag(APPLY)) {
  1313                     Symbol recSym = quicklyResolveMethod(env, (JCMethodInvocation) rec);
  1314                     if (recSym == null)
  1315                         return null;
  1316                     Symbol resolvedReturnType =
  1317                             analyzeCandidateMethods(recSym, syms.errSymbol, returnSymbolAnalyzer);
  1318                     if (resolvedReturnType == null)
  1319                         return null;
  1320                     site = resolvedReturnType.type;
  1321                 } else {
  1322                     site = attribSpeculative(rec, env, attr.unknownTypeExprInfo).type;
  1324             } else {
  1325                 site = env.enclClass.sym.type;
  1328             while (site.hasTag(TYPEVAR)) {
  1329                 site = site.getUpperBound();
  1332             site = types.capture(site);
  1334             List<Type> args = rs.dummyArgs(tree.args.length());
  1335             Name name = TreeInfo.name(tree.meth);
  1337             Resolve.LookupHelper lh = rs.new LookupHelper(name, site, args, List.<Type>nil(), MethodResolutionPhase.VARARITY) {
  1338                 @Override
  1339                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  1340                     return rec == null ?
  1341                         rs.findFun(env, name, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  1342                         rs.findMethod(env, site, name, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired(), false);
  1344                 @Override
  1345                 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  1346                     return sym;
  1348             };
  1350             return rs.lookupMethod(env, tree, site.tsym, rs.arityMethodCheck, lh);
  1352         //where:
  1353             MethodAnalyzer<Symbol> returnSymbolAnalyzer = new MethodAnalyzer<Symbol>() {
  1354                 @Override
  1355                 public Symbol process(MethodSymbol ms) {
  1356                     ArgumentExpressionKind kind = ArgumentExpressionKind.methodKind(ms, types);
  1357                     if (kind == ArgumentExpressionKind.POLY || ms.getReturnType().hasTag(TYPEVAR))
  1358                         return null;
  1359                     return ms.getReturnType().tsym;
  1361                 @Override
  1362                 public Symbol reduce(Symbol s1, Symbol s2) {
  1363                     return s1 == syms.errSymbol ? s2 : s1 == s2 ? s1 : null;
  1365                 @Override
  1366                 public boolean shouldStop(Symbol result) {
  1367                     return result == null;
  1369             };
  1371         /**
  1372          * Process the result of Resolve.lookupMethod. If sym is a method symbol, the result of
  1373          * MethodAnalyzer.process is returned. If sym is an ambiguous symbol, all the candidate
  1374          * methods are inspected one by one, using MethodAnalyzer.process. The outcomes are
  1375          * reduced using MethodAnalyzer.reduce (using defaultValue as the first value over which
  1376          * the reduction runs). MethodAnalyzer.shouldStop can be used to stop the inspection early.
  1377          */
  1378         <E> E analyzeCandidateMethods(Symbol sym, E defaultValue, MethodAnalyzer<E> analyzer) {
  1379             switch (sym.kind) {
  1380                 case Kinds.MTH:
  1381                     return analyzer.process((MethodSymbol) sym);
  1382                 case Kinds.AMBIGUOUS:
  1383                     Resolve.AmbiguityError err = (Resolve.AmbiguityError)sym.baseSymbol();
  1384                     E res = defaultValue;
  1385                     for (Symbol s : err.ambiguousSyms) {
  1386                         if (s.kind == Kinds.MTH) {
  1387                             res = analyzer.reduce(res, analyzer.process((MethodSymbol) s));
  1388                             if (analyzer.shouldStop(res))
  1389                                 return res;
  1392                     return res;
  1393                 default:
  1394                     return defaultValue;
  1399     /** Analyzer for methods - used by analyzeCandidateMethods. */
  1400     interface MethodAnalyzer<E> {
  1401         E process(MethodSymbol ms);
  1402         E reduce(E e1, E e2);
  1403         boolean shouldStop(E result);
  1406     //where
  1407     private EnumSet<JCTree.Tag> deferredCheckerTags =
  1408             EnumSet.of(LAMBDA, REFERENCE, PARENS, TYPECAST,
  1409                     CONDEXPR, NEWCLASS, APPLY, LITERAL);

mercurial