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

Fri, 15 Feb 2013 16:29:58 +0000

author
mcimadamore
date
Fri, 15 Feb 2013 16:29:58 +0000
changeset 1581
4ff468de829d
parent 1562
2154ed9ff6c8
child 1596
3a39d123d33a
permissions
-rw-r--r--

8007462: Fix provisional applicability for method references
Summary: Add speculative arity-based check to rule out potential candidates when stuck reference is passed to method
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import com.sun.tools.javac.code.*;
    29 import com.sun.tools.javac.tree.*;
    30 import com.sun.tools.javac.util.*;
    31 import com.sun.tools.javac.code.Symbol.*;
    32 import com.sun.tools.javac.code.Type.*;
    33 import com.sun.tools.javac.comp.Attr.ResultInfo;
    34 import com.sun.tools.javac.comp.Infer.InferenceContext;
    35 import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase;
    36 import com.sun.tools.javac.tree.JCTree.*;
    38 import javax.tools.JavaFileObject;
    40 import java.util.ArrayList;
    41 import java.util.EnumSet;
    42 import java.util.LinkedHashSet;
    43 import java.util.Map;
    44 import java.util.Queue;
    45 import java.util.Set;
    46 import java.util.WeakHashMap;
    48 import static com.sun.tools.javac.code.TypeTag.*;
    49 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    51 /**
    52  * This is an helper class that is used to perform deferred type-analysis.
    53  * Each time a poly expression occurs in argument position, javac attributes it
    54  * with a temporary 'deferred type' that is checked (possibly multiple times)
    55  * against an expected formal type.
    56  *
    57  *  <p><b>This is NOT part of any supported API.
    58  *  If you write code that depends on this, you do so at your own risk.
    59  *  This code and its internal interfaces are subject to change or
    60  *  deletion without notice.</b>
    61  */
    62 public class DeferredAttr extends JCTree.Visitor {
    63     protected static final Context.Key<DeferredAttr> deferredAttrKey =
    64         new Context.Key<DeferredAttr>();
    66     final Attr attr;
    67     final Check chk;
    68     final JCDiagnostic.Factory diags;
    69     final Enter enter;
    70     final Infer infer;
    71     final Resolve rs;
    72     final Log log;
    73     final Symtab syms;
    74     final TreeMaker make;
    75     final Types types;
    77     public static DeferredAttr instance(Context context) {
    78         DeferredAttr instance = context.get(deferredAttrKey);
    79         if (instance == null)
    80             instance = new DeferredAttr(context);
    81         return instance;
    82     }
    84     protected DeferredAttr(Context context) {
    85         context.put(deferredAttrKey, this);
    86         attr = Attr.instance(context);
    87         chk = Check.instance(context);
    88         diags = JCDiagnostic.Factory.instance(context);
    89         enter = Enter.instance(context);
    90         infer = Infer.instance(context);
    91         rs = Resolve.instance(context);
    92         log = Log.instance(context);
    93         syms = Symtab.instance(context);
    94         make = TreeMaker.instance(context);
    95         types = Types.instance(context);
    96         Names names = Names.instance(context);
    97         stuckTree = make.Ident(names.empty).setType(Type.noType);
    98     }
   100     /** shared tree for stuck expressions */
   101     final JCTree stuckTree;
   103     /**
   104      * This type represents a deferred type. A deferred type starts off with
   105      * no information on the underlying expression type. Such info needs to be
   106      * discovered through type-checking the deferred type against a target-type.
   107      * Every deferred type keeps a pointer to the AST node from which it originated.
   108      */
   109     public class DeferredType extends Type {
   111         public JCExpression tree;
   112         Env<AttrContext> env;
   113         AttrMode mode;
   114         SpeculativeCache speculativeCache;
   116         DeferredType(JCExpression tree, Env<AttrContext> env) {
   117             super(DEFERRED, null);
   118             this.tree = tree;
   119             this.env = env.dup(tree, env.info.dup());
   120             this.speculativeCache = new SpeculativeCache();
   121         }
   123         /**
   124          * A speculative cache is used to keep track of all overload resolution rounds
   125          * that triggered speculative attribution on a given deferred type. Each entry
   126          * stores a pointer to the speculative tree and the resolution phase in which the entry
   127          * has been added.
   128          */
   129         class SpeculativeCache {
   131             private Map<Symbol, List<Entry>> cache =
   132                     new WeakHashMap<Symbol, List<Entry>>();
   134             class Entry {
   135                 JCTree speculativeTree;
   136                 Resolve.MethodResolutionPhase phase;
   138                 public Entry(JCTree speculativeTree, MethodResolutionPhase phase) {
   139                     this.speculativeTree = speculativeTree;
   140                     this.phase = phase;
   141                 }
   143                 boolean matches(Resolve.MethodResolutionPhase phase) {
   144                     return this.phase == phase;
   145                 }
   146             }
   148             /**
   149              * Retrieve a speculative cache entry corresponding to given symbol
   150              * and resolution phase
   151              */
   152             Entry get(Symbol msym, MethodResolutionPhase phase) {
   153                 List<Entry> entries = cache.get(msym);
   154                 if (entries == null) return null;
   155                 for (Entry e : entries) {
   156                     if (e.matches(phase)) return e;
   157                 }
   158                 return null;
   159             }
   161             /**
   162              * Stores a speculative cache entry corresponding to given symbol
   163              * and resolution phase
   164              */
   165             void put(Symbol msym, JCTree speculativeTree, MethodResolutionPhase phase) {
   166                 List<Entry> entries = cache.get(msym);
   167                 if (entries == null) {
   168                     entries = List.nil();
   169                 }
   170                 cache.put(msym, entries.prepend(new Entry(speculativeTree, phase)));
   171             }
   172         }
   174         /**
   175          * Get the type that has been computed during a speculative attribution round
   176          */
   177         Type speculativeType(Symbol msym, MethodResolutionPhase phase) {
   178             SpeculativeCache.Entry e = speculativeCache.get(msym, phase);
   179             return e != null ? e.speculativeTree.type : Type.noType;
   180         }
   182         /**
   183          * Check a deferred type against a potential target-type. Depending on
   184          * the current attribution mode, a normal vs. speculative attribution
   185          * round is performed on the underlying AST node. There can be only one
   186          * speculative round for a given target method symbol; moreover, a normal
   187          * attribution round must follow one or more speculative rounds.
   188          */
   189         Type check(ResultInfo resultInfo) {
   190             return check(resultInfo, stuckVars(tree, env, resultInfo), basicCompleter);
   191         }
   193         Type check(ResultInfo resultInfo, List<Type> stuckVars, DeferredTypeCompleter deferredTypeCompleter) {
   194             DeferredAttrContext deferredAttrContext =
   195                     resultInfo.checkContext.deferredAttrContext();
   196             Assert.check(deferredAttrContext != emptyDeferredAttrContext);
   197             if (stuckVars.nonEmpty()) {
   198                 deferredAttrContext.addDeferredAttrNode(this, resultInfo, stuckVars);
   199                 return Type.noType;
   200             } else {
   201                 try {
   202                     return deferredTypeCompleter.complete(this, resultInfo, deferredAttrContext);
   203                 } finally {
   204                     mode = deferredAttrContext.mode;
   205                 }
   206             }
   207         }
   208     }
   210     /**
   211      * A completer for deferred types. Defines an entry point for type-checking
   212      * a deferred type.
   213      */
   214     interface DeferredTypeCompleter {
   215         /**
   216          * Entry point for type-checking a deferred type. Depending on the
   217          * circumstances, type-checking could amount to full attribution
   218          * or partial structural check (aka potential applicability).
   219          */
   220         Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext);
   221     }
   223     /**
   224      * A basic completer for deferred types. This completer type-checks a deferred type
   225      * using attribution; depending on the attribution mode, this could be either standard
   226      * or speculative attribution.
   227      */
   228     DeferredTypeCompleter basicCompleter = new DeferredTypeCompleter() {
   229         public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   230             switch (deferredAttrContext.mode) {
   231                 case SPECULATIVE:
   232                     Assert.check(dt.mode == null ||
   233                             (dt.mode == AttrMode.SPECULATIVE &&
   234                             dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase).hasTag(NONE)));
   235                     JCTree speculativeTree = attribSpeculative(dt.tree, dt.env, resultInfo);
   236                     dt.speculativeCache.put(deferredAttrContext.msym, speculativeTree, deferredAttrContext.phase);
   237                     return speculativeTree.type;
   238                 case CHECK:
   239                     Assert.check(dt.mode != null);
   240                     return attr.attribTree(dt.tree, dt.env, resultInfo);
   241             }
   242             Assert.error();
   243             return null;
   244         }
   245     };
   247     DeferredTypeCompleter dummyCompleter = new DeferredTypeCompleter() {
   248         public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   249             Assert.check(deferredAttrContext.mode == AttrMode.CHECK);
   250             return dt.tree.type = Type.noType;
   251         }
   252     };
   254     /**
   255      * The 'mode' in which the deferred type is to be type-checked
   256      */
   257     public enum AttrMode {
   258         /**
   259          * A speculative type-checking round is used during overload resolution
   260          * mainly to generate constraints on inference variables. Side-effects
   261          * arising from type-checking the expression associated with the deferred
   262          * type are reversed after the speculative round finishes. This means the
   263          * expression tree will be left in a blank state.
   264          */
   265         SPECULATIVE,
   266         /**
   267          * This is the plain type-checking mode. Produces side-effects on the underlying AST node
   268          */
   269         CHECK;
   270     }
   272     /**
   273      * Routine that performs speculative type-checking; the input AST node is
   274      * cloned (to avoid side-effects cause by Attr) and compiler state is
   275      * restored after type-checking. All diagnostics (but critical ones) are
   276      * disabled during speculative type-checking.
   277      */
   278     JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   279         JCTree newTree = new TreeCopier<Object>(make).copy(tree);
   280         Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared()));
   281         speculativeEnv.info.scope.owner = env.info.scope.owner;
   282         final JavaFileObject currentSource = log.currentSourceFile();
   283         Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
   284                 new Log.DeferredDiagnosticHandler(log, new Filter<JCDiagnostic>() {
   285             public boolean accepts(JCDiagnostic t) {
   286                 return t.getDiagnosticSource().getFile().equals(currentSource);
   287             }
   288         });
   289         try {
   290             attr.attribTree(newTree, speculativeEnv, resultInfo);
   291             unenterScanner.scan(newTree);
   292             return newTree;
   293         } catch (Abort ex) {
   294             //if some very bad condition occurred during deferred attribution
   295             //we should dump all errors before killing javac
   296             deferredDiagnosticHandler.reportDeferredDiagnostics();
   297             throw ex;
   298         } finally {
   299             unenterScanner.scan(newTree);
   300             log.popDiagnosticHandler(deferredDiagnosticHandler);
   301         }
   302     }
   303     //where
   304         protected TreeScanner unenterScanner = new TreeScanner() {
   305             @Override
   306             public void visitClassDef(JCClassDecl tree) {
   307                 ClassSymbol csym = tree.sym;
   308                 //if something went wrong during method applicability check
   309                 //it is possible that nested expressions inside argument expression
   310                 //are left unchecked - in such cases there's nothing to clean up.
   311                 if (csym == null) return;
   312                 enter.typeEnvs.remove(csym);
   313                 chk.compiled.remove(csym.flatname);
   314                 syms.classes.remove(csym.flatname);
   315                 super.visitClassDef(tree);
   316             }
   317         };
   319     /**
   320      * A deferred context is created on each method check. A deferred context is
   321      * used to keep track of information associated with the method check, such as
   322      * the symbol of the method being checked, the overload resolution phase,
   323      * the kind of attribution mode to be applied to deferred types and so forth.
   324      * As deferred types are processed (by the method check routine) stuck AST nodes
   325      * are added (as new deferred attribution nodes) to this context. The complete()
   326      * routine makes sure that all pending nodes are properly processed, by
   327      * progressively instantiating all inference variables on which one or more
   328      * deferred attribution node is stuck.
   329      */
   330     class DeferredAttrContext {
   332         /** attribution mode */
   333         final AttrMode mode;
   335         /** symbol of the method being checked */
   336         final Symbol msym;
   338         /** method resolution step */
   339         final Resolve.MethodResolutionPhase phase;
   341         /** inference context */
   342         final InferenceContext inferenceContext;
   344         /** parent deferred context */
   345         final DeferredAttrContext parent;
   347         /** Warner object to report warnings */
   348         final Warner warn;
   350         /** list of deferred attribution nodes to be processed */
   351         ArrayList<DeferredAttrNode> deferredAttrNodes = new ArrayList<DeferredAttrNode>();
   353         DeferredAttrContext(AttrMode mode, Symbol msym, MethodResolutionPhase phase,
   354                 InferenceContext inferenceContext, DeferredAttrContext parent, Warner warn) {
   355             this.mode = mode;
   356             this.msym = msym;
   357             this.phase = phase;
   358             this.parent = parent;
   359             this.warn = warn;
   360             this.inferenceContext = inferenceContext;
   361         }
   363         /**
   364          * Adds a node to the list of deferred attribution nodes - used by Resolve.rawCheckArgumentsApplicable
   365          * Nodes added this way act as 'roots' for the out-of-order method checking process.
   366          */
   367         void addDeferredAttrNode(final DeferredType dt, ResultInfo resultInfo, List<Type> stuckVars) {
   368             deferredAttrNodes.add(new DeferredAttrNode(dt, resultInfo, stuckVars));
   369         }
   371         /**
   372          * Incrementally process all nodes, by skipping 'stuck' nodes and attributing
   373          * 'unstuck' ones. If at any point no progress can be made (no 'unstuck' nodes)
   374          * some inference variable might get eagerly instantiated so that all nodes
   375          * can be type-checked.
   376          */
   377         void complete() {
   378             while (!deferredAttrNodes.isEmpty()) {
   379                 Set<Type> stuckVars = new LinkedHashSet<Type>();
   380                 boolean progress = false;
   381                 //scan a defensive copy of the node list - this is because a deferred
   382                 //attribution round can add new nodes to the list
   383                 for (DeferredAttrNode deferredAttrNode : List.from(deferredAttrNodes)) {
   384                     if (!deferredAttrNode.process(this)) {
   385                         stuckVars.addAll(deferredAttrNode.stuckVars);
   386                     } else {
   387                         deferredAttrNodes.remove(deferredAttrNode);
   388                         progress = true;
   389                     }
   390                 }
   391                 if (!progress) {
   392                     //remove all variables that have already been instantiated
   393                     //from the list of stuck variables
   394                     inferenceContext.solveAny(List.from(stuckVars), warn);
   395                     inferenceContext.notifyChange();
   396                 }
   397             }
   398         }
   399     }
   401     /**
   402      * Class representing a deferred attribution node. It keeps track of
   403      * a deferred type, along with the expected target type information.
   404      */
   405     class DeferredAttrNode implements Infer.FreeTypeListener {
   407         /** underlying deferred type */
   408         DeferredType dt;
   410         /** underlying target type information */
   411         ResultInfo resultInfo;
   413         /** list of uninferred inference variables causing this node to be stuck */
   414         List<Type> stuckVars;
   416         DeferredAttrNode(DeferredType dt, ResultInfo resultInfo, List<Type> stuckVars) {
   417             this.dt = dt;
   418             this.resultInfo = resultInfo;
   419             this.stuckVars = stuckVars;
   420             if (!stuckVars.isEmpty()) {
   421                 resultInfo.checkContext.inferenceContext().addFreeTypeListener(stuckVars, this);
   422             }
   423         }
   425         @Override
   426         public void typesInferred(InferenceContext inferenceContext) {
   427             stuckVars = List.nil();
   428             resultInfo = resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   429         }
   431         /**
   432          * Process a deferred attribution node.
   433          * Invariant: a stuck node cannot be processed.
   434          */
   435         @SuppressWarnings("fallthrough")
   436         boolean process(DeferredAttrContext deferredAttrContext) {
   437             switch (deferredAttrContext.mode) {
   438                 case SPECULATIVE:
   439                     dt.check(resultInfo, List.<Type>nil(), new StructuralStuckChecker());
   440                     return true;
   441                 case CHECK:
   442                     if (stuckVars.nonEmpty()) {
   443                         //stuck expression - see if we can propagate
   444                         if (deferredAttrContext.parent != emptyDeferredAttrContext &&
   445                                 Type.containsAny(deferredAttrContext.parent.inferenceContext.inferencevars, List.from(stuckVars))) {
   446                             deferredAttrContext.parent.deferredAttrNodes.add(this);
   447                             dt.check(resultInfo, List.<Type>nil(), dummyCompleter);
   448                             return true;
   449                         } else {
   450                             return false;
   451                         }
   452                     } else {
   453                         dt.check(resultInfo, stuckVars, basicCompleter);
   454                         return true;
   455                     }
   456                 default:
   457                     throw new AssertionError("Bad mode");
   458             }
   459         }
   461         /**
   462          * Structural checker for stuck expressions
   463          */
   464         class StructuralStuckChecker extends TreeScanner implements DeferredTypeCompleter {
   466             ResultInfo resultInfo;
   467             InferenceContext inferenceContext;
   468             Env<AttrContext> env;
   470             public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   471                 this.resultInfo = resultInfo;
   472                 this.inferenceContext = deferredAttrContext.inferenceContext;
   473                 this.env = dt.env.dup(dt.tree, dt.env.info.dup());
   474                 dt.tree.accept(this);
   475                 dt.speculativeCache.put(deferredAttrContext.msym, stuckTree, deferredAttrContext.phase);
   476                 return Type.noType;
   477             }
   479             @Override
   480             public void visitLambda(JCLambda tree) {
   481                 Check.CheckContext checkContext = resultInfo.checkContext;
   482                 Type pt = resultInfo.pt;
   483                 if (inferenceContext.inferencevars.contains(pt)) {
   484                     //ok
   485                     return;
   486                 } else {
   487                     //must be a functional descriptor
   488                     try {
   489                         Type desc = types.findDescriptorType(pt);
   490                         if (desc.getParameterTypes().length() != tree.params.length()) {
   491                             checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
   492                         }
   493                     } catch (Types.FunctionDescriptorLookupError ex) {
   494                         checkContext.report(null, ex.getDiagnostic());
   495                     }
   496                 }
   497             }
   499             @Override
   500             public void visitNewClass(JCNewClass tree) {
   501                 //do nothing
   502             }
   504             @Override
   505             public void visitApply(JCMethodInvocation tree) {
   506                 //do nothing
   507             }
   509             @Override
   510             public void visitReference(JCMemberReference tree) {
   511                 Check.CheckContext checkContext = resultInfo.checkContext;
   512                 Type pt = resultInfo.pt;
   513                 if (inferenceContext.inferencevars.contains(pt)) {
   514                     //ok
   515                     return;
   516                 } else {
   517                     try {
   518                         types.findDescriptorType(pt);
   519                     } catch (Types.FunctionDescriptorLookupError ex) {
   520                         checkContext.report(null, ex.getDiagnostic());
   521                     }
   522                     JCExpression exprTree = (JCExpression)attribSpeculative(tree.getQualifierExpression(), env,
   523                             attr.memberReferenceQualifierResult(tree));
   524                     ListBuffer<Type> argtypes = ListBuffer.lb();
   525                     for (Type t : types.findDescriptorType(pt).getParameterTypes()) {
   526                         argtypes.append(syms.errType);
   527                     }
   528                     JCMemberReference mref2 = new TreeCopier<Void>(make).copy(tree);
   529                     mref2.expr = exprTree;
   530                     Pair<Symbol, ?> lookupRes =
   531                             rs.resolveMemberReference(tree, env, mref2, exprTree.type, tree.name, argtypes.toList(), null, true);
   532                     switch (lookupRes.fst.kind) {
   533                         //note: as argtypes are erroneous types, type-errors must
   534                         //have been caused by arity mismatch
   535                         case Kinds.ABSENT_MTH:
   536                         case Kinds.WRONG_MTH:
   537                         case Kinds.WRONG_MTHS:
   538                         case Kinds.STATICERR:
   539                         case Kinds.MISSING_ENCL:
   540                            checkContext.report(null, diags.fragment("incompatible.arg.types.in.mref"));
   541                     }
   542                 }
   543             }
   544         }
   545     }
   547     /** an empty deferred attribution context - all methods throw exceptions */
   548     final DeferredAttrContext emptyDeferredAttrContext =
   549             new DeferredAttrContext(AttrMode.CHECK, null, MethodResolutionPhase.BOX, null, null, null) {
   550                 @Override
   551                 void addDeferredAttrNode(DeferredType dt, ResultInfo ri, List<Type> stuckVars) {
   552                     Assert.error("Empty deferred context!");
   553                 }
   554                 @Override
   555                 void complete() {
   556                     Assert.error("Empty deferred context!");
   557                 }
   558             };
   560     /**
   561      * Map a list of types possibly containing one or more deferred types
   562      * into a list of ordinary types. Each deferred type D is mapped into a type T,
   563      * where T is computed by retrieving the type that has already been
   564      * computed for D during a previous deferred attribution round of the given kind.
   565      */
   566     class DeferredTypeMap extends Type.Mapping {
   568         DeferredAttrContext deferredAttrContext;
   570         protected DeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   571             super(String.format("deferredTypeMap[%s]", mode));
   572             this.deferredAttrContext = new DeferredAttrContext(mode, msym, phase,
   573                     infer.emptyContext, emptyDeferredAttrContext, types.noWarnings);
   574         }
   576         protected boolean validState(DeferredType dt) {
   577             return dt.mode != null &&
   578                     deferredAttrContext.mode.ordinal() <= dt.mode.ordinal();
   579         }
   581         @Override
   582         public Type apply(Type t) {
   583             if (!t.hasTag(DEFERRED)) {
   584                 return t.map(this);
   585             } else {
   586                 DeferredType dt = (DeferredType)t;
   587                 Assert.check(validState(dt));
   588                 return typeOf(dt);
   589             }
   590         }
   592         protected Type typeOf(DeferredType dt) {
   593             switch (deferredAttrContext.mode) {
   594                 case CHECK:
   595                     return dt.tree.type == null ? Type.noType : dt.tree.type;
   596                 case SPECULATIVE:
   597                     return dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase);
   598             }
   599             Assert.error();
   600             return null;
   601         }
   602     }
   604     /**
   605      * Specialized recovery deferred mapping.
   606      * Each deferred type D is mapped into a type T, where T is computed either by
   607      * (i) retrieving the type that has already been computed for D during a previous
   608      * attribution round (as before), or (ii) by synthesizing a new type R for D
   609      * (the latter step is useful in a recovery scenario).
   610      */
   611     public class RecoveryDeferredTypeMap extends DeferredTypeMap {
   613         public RecoveryDeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   614             super(mode, msym, phase != null ? phase : MethodResolutionPhase.BOX);
   615         }
   617         @Override
   618         protected Type typeOf(DeferredType dt) {
   619             Type owntype = super.typeOf(dt);
   620             return owntype == Type.noType ?
   621                         recover(dt) : owntype;
   622         }
   624         @Override
   625         protected boolean validState(DeferredType dt) {
   626             return true;
   627         }
   629         /**
   630          * Synthesize a type for a deferred type that hasn't been previously
   631          * reduced to an ordinary type. Functional deferred types and conditionals
   632          * are mapped to themselves, in order to have a richer diagnostic
   633          * representation. Remaining deferred types are attributed using
   634          * a default expected type (j.l.Object).
   635          */
   636         private Type recover(DeferredType dt) {
   637             dt.check(attr.new RecoveryInfo(deferredAttrContext));
   638             return super.apply(dt);
   639         }
   640     }
   642     /**
   643      * Retrieves the list of inference variables that need to be inferred before
   644      * an AST node can be type-checked
   645      */
   646     @SuppressWarnings("fallthrough")
   647     List<Type> stuckVars(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   648                 if (resultInfo.pt.hasTag(NONE) || resultInfo.pt.isErroneous()) {
   649             return List.nil();
   650         } else {
   651             return stuckVarsInternal(tree, resultInfo.pt, resultInfo.checkContext.inferenceContext());
   652         }
   653     }
   654     //where
   655         private List<Type> stuckVarsInternal(JCTree tree, Type pt, Infer.InferenceContext inferenceContext) {
   656             StuckChecker sc = new StuckChecker(pt, inferenceContext);
   657             sc.scan(tree);
   658             return List.from(sc.stuckVars);
   659         }
   661     /**
   662      * A special tree scanner that would only visit portions of a given tree.
   663      * The set of nodes visited by the scanner can be customized at construction-time.
   664      */
   665     abstract static class FilterScanner extends TreeScanner {
   667         final Filter<JCTree> treeFilter;
   669         FilterScanner(final Set<JCTree.Tag> validTags) {
   670             this.treeFilter = new Filter<JCTree>() {
   671                 public boolean accepts(JCTree t) {
   672                     return validTags.contains(t.getTag());
   673                 }
   674             };
   675         }
   677         @Override
   678         public void scan(JCTree tree) {
   679             if (tree != null) {
   680                 if (treeFilter.accepts(tree)) {
   681                     super.scan(tree);
   682                 } else {
   683                     skip(tree);
   684                 }
   685             }
   686         }
   688         /**
   689          * handler that is executed when a node has been discarded
   690          */
   691         abstract void skip(JCTree tree);
   692     }
   694     /**
   695      * A tree scanner suitable for visiting the target-type dependent nodes of
   696      * a given argument expression.
   697      */
   698     static class PolyScanner extends FilterScanner {
   700         PolyScanner() {
   701             super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE));
   702         }
   704         @Override
   705         void skip(JCTree tree) {
   706             //do nothing
   707         }
   708     }
   710     /**
   711      * A tree scanner suitable for visiting the target-type dependent nodes nested
   712      * within a lambda expression body.
   713      */
   714     static class LambdaReturnScanner extends FilterScanner {
   716         LambdaReturnScanner() {
   717             super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
   718                     FORLOOP, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
   719         }
   721         @Override
   722         void skip(JCTree tree) {
   723             //do nothing
   724         }
   725     }
   727     /**
   728      * This visitor is used to check that structural expressions conform
   729      * to their target - this step is required as inference could end up
   730      * inferring types that make some of the nested expressions incompatible
   731      * with their corresponding instantiated target
   732      */
   733     class StuckChecker extends PolyScanner {
   735         Type pt;
   736         Infer.InferenceContext inferenceContext;
   737         Set<Type> stuckVars = new LinkedHashSet<Type>();
   739         StuckChecker(Type pt, Infer.InferenceContext inferenceContext) {
   740             this.pt = pt;
   741             this.inferenceContext = inferenceContext;
   742         }
   744         @Override
   745         public void visitLambda(JCLambda tree) {
   746             if (inferenceContext.inferenceVars().contains(pt)) {
   747                 stuckVars.add(pt);
   748             }
   749             if (!types.isFunctionalInterface(pt)) {
   750                 return;
   751             }
   752             Type descType = types.findDescriptorType(pt);
   753             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
   754             if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT &&
   755                     freeArgVars.nonEmpty()) {
   756                 stuckVars.addAll(freeArgVars);
   757             }
   758             scanLambdaBody(tree, descType.getReturnType());
   759         }
   761         @Override
   762         public void visitReference(JCMemberReference tree) {
   763             scan(tree.expr);
   764             if (inferenceContext.inferenceVars().contains(pt)) {
   765                 stuckVars.add(pt);
   766                 return;
   767             }
   768             if (!types.isFunctionalInterface(pt)) {
   769                 return;
   770             }
   772             Type descType = types.findDescriptorType(pt);
   773             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
   774             stuckVars.addAll(freeArgVars);
   775         }
   777         void scanLambdaBody(JCLambda lambda, final Type pt) {
   778             if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
   779                 stuckVars.addAll(stuckVarsInternal(lambda.body, pt, inferenceContext));
   780             } else {
   781                 LambdaReturnScanner lambdaScanner = new LambdaReturnScanner() {
   782                     @Override
   783                     public void visitReturn(JCReturn tree) {
   784                         if (tree.expr != null) {
   785                             stuckVars.addAll(stuckVarsInternal(tree.expr, pt, inferenceContext));
   786                         }
   787                     }
   788                 };
   789                 lambdaScanner.scan(lambda.body);
   790             }
   791         }
   792     }
   793 }

mercurial