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

Fri, 22 Mar 2013 12:41:13 +0000

author
mcimadamore
date
Fri, 22 Mar 2013 12:41:13 +0000
changeset 1654
b6cf07c54c29
parent 1613
d2a98dde7ecc
child 1674
b71a61d39cf7
permissions
-rw-r--r--

8009820: AssertionError when compiling java code with two identical static imports
Summary: Speculative attribution is carried out twice with same method symbol in case of static imports
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                     //Note: if a symbol is imported twice we might do two identical
   233                     //speculative rounds...
   234                     Assert.check(dt.mode == null || dt.mode == AttrMode.SPECULATIVE);
   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         final 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         Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
   283                 new Log.DeferredDiagnosticHandler(log, new Filter<JCDiagnostic>() {
   284             public boolean accepts(final JCDiagnostic d) {
   285                 class PosScanner extends TreeScanner {
   286                     boolean found = false;
   288                     @Override
   289                     public void scan(JCTree tree) {
   290                         if (tree != null &&
   291                                 tree.pos() == d.getDiagnosticPosition()) {
   292                             found = true;
   293                         }
   294                         super.scan(tree);
   295                     }
   296                 };
   297                 PosScanner posScanner = new PosScanner();
   298                 posScanner.scan(newTree);
   299                 return posScanner.found;
   300             }
   301         });
   302         try {
   303             attr.attribTree(newTree, speculativeEnv, resultInfo);
   304             unenterScanner.scan(newTree);
   305             return newTree;
   306         } finally {
   307             unenterScanner.scan(newTree);
   308             log.popDiagnosticHandler(deferredDiagnosticHandler);
   309         }
   310     }
   311     //where
   312         protected TreeScanner unenterScanner = new TreeScanner() {
   313             @Override
   314             public void visitClassDef(JCClassDecl tree) {
   315                 ClassSymbol csym = tree.sym;
   316                 //if something went wrong during method applicability check
   317                 //it is possible that nested expressions inside argument expression
   318                 //are left unchecked - in such cases there's nothing to clean up.
   319                 if (csym == null) return;
   320                 enter.typeEnvs.remove(csym);
   321                 chk.compiled.remove(csym.flatname);
   322                 syms.classes.remove(csym.flatname);
   323                 super.visitClassDef(tree);
   324             }
   325         };
   327     /**
   328      * A deferred context is created on each method check. A deferred context is
   329      * used to keep track of information associated with the method check, such as
   330      * the symbol of the method being checked, the overload resolution phase,
   331      * the kind of attribution mode to be applied to deferred types and so forth.
   332      * As deferred types are processed (by the method check routine) stuck AST nodes
   333      * are added (as new deferred attribution nodes) to this context. The complete()
   334      * routine makes sure that all pending nodes are properly processed, by
   335      * progressively instantiating all inference variables on which one or more
   336      * deferred attribution node is stuck.
   337      */
   338     class DeferredAttrContext {
   340         /** attribution mode */
   341         final AttrMode mode;
   343         /** symbol of the method being checked */
   344         final Symbol msym;
   346         /** method resolution step */
   347         final Resolve.MethodResolutionPhase phase;
   349         /** inference context */
   350         final InferenceContext inferenceContext;
   352         /** parent deferred context */
   353         final DeferredAttrContext parent;
   355         /** Warner object to report warnings */
   356         final Warner warn;
   358         /** list of deferred attribution nodes to be processed */
   359         ArrayList<DeferredAttrNode> deferredAttrNodes = new ArrayList<DeferredAttrNode>();
   361         DeferredAttrContext(AttrMode mode, Symbol msym, MethodResolutionPhase phase,
   362                 InferenceContext inferenceContext, DeferredAttrContext parent, Warner warn) {
   363             this.mode = mode;
   364             this.msym = msym;
   365             this.phase = phase;
   366             this.parent = parent;
   367             this.warn = warn;
   368             this.inferenceContext = inferenceContext;
   369         }
   371         /**
   372          * Adds a node to the list of deferred attribution nodes - used by Resolve.rawCheckArgumentsApplicable
   373          * Nodes added this way act as 'roots' for the out-of-order method checking process.
   374          */
   375         void addDeferredAttrNode(final DeferredType dt, ResultInfo resultInfo, List<Type> stuckVars) {
   376             deferredAttrNodes.add(new DeferredAttrNode(dt, resultInfo, stuckVars));
   377         }
   379         /**
   380          * Incrementally process all nodes, by skipping 'stuck' nodes and attributing
   381          * 'unstuck' ones. If at any point no progress can be made (no 'unstuck' nodes)
   382          * some inference variable might get eagerly instantiated so that all nodes
   383          * can be type-checked.
   384          */
   385         void complete() {
   386             while (!deferredAttrNodes.isEmpty()) {
   387                 Set<Type> stuckVars = new LinkedHashSet<Type>();
   388                 boolean progress = false;
   389                 //scan a defensive copy of the node list - this is because a deferred
   390                 //attribution round can add new nodes to the list
   391                 for (DeferredAttrNode deferredAttrNode : List.from(deferredAttrNodes)) {
   392                     if (!deferredAttrNode.process(this)) {
   393                         stuckVars.addAll(deferredAttrNode.stuckVars);
   394                     } else {
   395                         deferredAttrNodes.remove(deferredAttrNode);
   396                         progress = true;
   397                     }
   398                 }
   399                 if (!progress) {
   400                     //remove all variables that have already been instantiated
   401                     //from the list of stuck variables
   402                     inferenceContext.solveAny(List.from(stuckVars), warn);
   403                     inferenceContext.notifyChange();
   404                 }
   405             }
   406         }
   407     }
   409     /**
   410      * Class representing a deferred attribution node. It keeps track of
   411      * a deferred type, along with the expected target type information.
   412      */
   413     class DeferredAttrNode implements Infer.FreeTypeListener {
   415         /** underlying deferred type */
   416         DeferredType dt;
   418         /** underlying target type information */
   419         ResultInfo resultInfo;
   421         /** list of uninferred inference variables causing this node to be stuck */
   422         List<Type> stuckVars;
   424         DeferredAttrNode(DeferredType dt, ResultInfo resultInfo, List<Type> stuckVars) {
   425             this.dt = dt;
   426             this.resultInfo = resultInfo;
   427             this.stuckVars = stuckVars;
   428             if (!stuckVars.isEmpty()) {
   429                 resultInfo.checkContext.inferenceContext().addFreeTypeListener(stuckVars, this);
   430             }
   431         }
   433         @Override
   434         public void typesInferred(InferenceContext inferenceContext) {
   435             stuckVars = List.nil();
   436             resultInfo = resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   437         }
   439         /**
   440          * Process a deferred attribution node.
   441          * Invariant: a stuck node cannot be processed.
   442          */
   443         @SuppressWarnings("fallthrough")
   444         boolean process(DeferredAttrContext deferredAttrContext) {
   445             switch (deferredAttrContext.mode) {
   446                 case SPECULATIVE:
   447                     dt.check(resultInfo, List.<Type>nil(), new StructuralStuckChecker());
   448                     return true;
   449                 case CHECK:
   450                     if (stuckVars.nonEmpty()) {
   451                         //stuck expression - see if we can propagate
   452                         if (deferredAttrContext.parent != emptyDeferredAttrContext &&
   453                                 Type.containsAny(deferredAttrContext.parent.inferenceContext.inferencevars, List.from(stuckVars))) {
   454                             deferredAttrContext.parent.deferredAttrNodes.add(this);
   455                             dt.check(resultInfo, List.<Type>nil(), dummyCompleter);
   456                             return true;
   457                         } else {
   458                             return false;
   459                         }
   460                     } else {
   461                         dt.check(resultInfo, stuckVars, basicCompleter);
   462                         return true;
   463                     }
   464                 default:
   465                     throw new AssertionError("Bad mode");
   466             }
   467         }
   469         /**
   470          * Structural checker for stuck expressions
   471          */
   472         class StructuralStuckChecker extends TreeScanner implements DeferredTypeCompleter {
   474             ResultInfo resultInfo;
   475             InferenceContext inferenceContext;
   476             Env<AttrContext> env;
   478             public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
   479                 this.resultInfo = resultInfo;
   480                 this.inferenceContext = deferredAttrContext.inferenceContext;
   481                 this.env = dt.env.dup(dt.tree, dt.env.info.dup());
   482                 dt.tree.accept(this);
   483                 dt.speculativeCache.put(deferredAttrContext.msym, stuckTree, deferredAttrContext.phase);
   484                 return Type.noType;
   485             }
   487             @Override
   488             public void visitLambda(JCLambda tree) {
   489                 Check.CheckContext checkContext = resultInfo.checkContext;
   490                 Type pt = resultInfo.pt;
   491                 if (inferenceContext.inferencevars.contains(pt)) {
   492                     //ok
   493                     return;
   494                 } else {
   495                     //must be a functional descriptor
   496                     try {
   497                         Type desc = types.findDescriptorType(pt);
   498                         if (desc.getParameterTypes().length() != tree.params.length()) {
   499                             checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
   500                         }
   501                     } catch (Types.FunctionDescriptorLookupError ex) {
   502                         checkContext.report(null, ex.getDiagnostic());
   503                     }
   504                 }
   505             }
   507             @Override
   508             public void visitNewClass(JCNewClass tree) {
   509                 //do nothing
   510             }
   512             @Override
   513             public void visitApply(JCMethodInvocation tree) {
   514                 //do nothing
   515             }
   517             @Override
   518             public void visitReference(JCMemberReference tree) {
   519                 Check.CheckContext checkContext = resultInfo.checkContext;
   520                 Type pt = resultInfo.pt;
   521                 if (inferenceContext.inferencevars.contains(pt)) {
   522                     //ok
   523                     return;
   524                 } else {
   525                     try {
   526                         types.findDescriptorType(pt);
   527                     } catch (Types.FunctionDescriptorLookupError ex) {
   528                         checkContext.report(null, ex.getDiagnostic());
   529                     }
   530                     JCExpression exprTree = (JCExpression)attribSpeculative(tree.getQualifierExpression(), env,
   531                             attr.memberReferenceQualifierResult(tree));
   532                     ListBuffer<Type> argtypes = ListBuffer.lb();
   533                     for (Type t : types.findDescriptorType(pt).getParameterTypes()) {
   534                         argtypes.append(syms.errType);
   535                     }
   536                     JCMemberReference mref2 = new TreeCopier<Void>(make).copy(tree);
   537                     mref2.expr = exprTree;
   538                     Pair<Symbol, ?> lookupRes =
   539                             rs.resolveMemberReference(tree, env, mref2, exprTree.type, tree.name, argtypes.toList(), null, true);
   540                     switch (lookupRes.fst.kind) {
   541                         //note: as argtypes are erroneous types, type-errors must
   542                         //have been caused by arity mismatch
   543                         case Kinds.ABSENT_MTH:
   544                         case Kinds.WRONG_MTH:
   545                         case Kinds.WRONG_MTHS:
   546                         case Kinds.STATICERR:
   547                         case Kinds.MISSING_ENCL:
   548                            checkContext.report(null, diags.fragment("incompatible.arg.types.in.mref"));
   549                     }
   550                 }
   551             }
   552         }
   553     }
   555     /** an empty deferred attribution context - all methods throw exceptions */
   556     final DeferredAttrContext emptyDeferredAttrContext =
   557             new DeferredAttrContext(AttrMode.CHECK, null, MethodResolutionPhase.BOX, null, null, null) {
   558                 @Override
   559                 void addDeferredAttrNode(DeferredType dt, ResultInfo ri, List<Type> stuckVars) {
   560                     Assert.error("Empty deferred context!");
   561                 }
   562                 @Override
   563                 void complete() {
   564                     Assert.error("Empty deferred context!");
   565                 }
   566             };
   568     /**
   569      * Map a list of types possibly containing one or more deferred types
   570      * into a list of ordinary types. Each deferred type D is mapped into a type T,
   571      * where T is computed by retrieving the type that has already been
   572      * computed for D during a previous deferred attribution round of the given kind.
   573      */
   574     class DeferredTypeMap extends Type.Mapping {
   576         DeferredAttrContext deferredAttrContext;
   578         protected DeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   579             super(String.format("deferredTypeMap[%s]", mode));
   580             this.deferredAttrContext = new DeferredAttrContext(mode, msym, phase,
   581                     infer.emptyContext, emptyDeferredAttrContext, types.noWarnings);
   582         }
   584         protected boolean validState(DeferredType dt) {
   585             return dt.mode != null &&
   586                     deferredAttrContext.mode.ordinal() <= dt.mode.ordinal();
   587         }
   589         @Override
   590         public Type apply(Type t) {
   591             if (!t.hasTag(DEFERRED)) {
   592                 return t.map(this);
   593             } else {
   594                 DeferredType dt = (DeferredType)t;
   595                 Assert.check(validState(dt));
   596                 return typeOf(dt);
   597             }
   598         }
   600         protected Type typeOf(DeferredType dt) {
   601             switch (deferredAttrContext.mode) {
   602                 case CHECK:
   603                     return dt.tree.type == null ? Type.noType : dt.tree.type;
   604                 case SPECULATIVE:
   605                     return dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase);
   606             }
   607             Assert.error();
   608             return null;
   609         }
   610     }
   612     /**
   613      * Specialized recovery deferred mapping.
   614      * Each deferred type D is mapped into a type T, where T is computed either by
   615      * (i) retrieving the type that has already been computed for D during a previous
   616      * attribution round (as before), or (ii) by synthesizing a new type R for D
   617      * (the latter step is useful in a recovery scenario).
   618      */
   619     public class RecoveryDeferredTypeMap extends DeferredTypeMap {
   621         public RecoveryDeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) {
   622             super(mode, msym, phase != null ? phase : MethodResolutionPhase.BOX);
   623         }
   625         @Override
   626         protected Type typeOf(DeferredType dt) {
   627             Type owntype = super.typeOf(dt);
   628             return owntype == Type.noType ?
   629                         recover(dt) : owntype;
   630         }
   632         @Override
   633         protected boolean validState(DeferredType dt) {
   634             return true;
   635         }
   637         /**
   638          * Synthesize a type for a deferred type that hasn't been previously
   639          * reduced to an ordinary type. Functional deferred types and conditionals
   640          * are mapped to themselves, in order to have a richer diagnostic
   641          * representation. Remaining deferred types are attributed using
   642          * a default expected type (j.l.Object).
   643          */
   644         private Type recover(DeferredType dt) {
   645             dt.check(attr.new RecoveryInfo(deferredAttrContext));
   646             return super.apply(dt);
   647         }
   648     }
   650     /**
   651      * Retrieves the list of inference variables that need to be inferred before
   652      * an AST node can be type-checked
   653      */
   654     @SuppressWarnings("fallthrough")
   655     List<Type> stuckVars(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   656                 if (resultInfo.pt.hasTag(NONE) || resultInfo.pt.isErroneous()) {
   657             return List.nil();
   658         } else {
   659             return stuckVarsInternal(tree, resultInfo.pt, resultInfo.checkContext.inferenceContext());
   660         }
   661     }
   662     //where
   663         private List<Type> stuckVarsInternal(JCTree tree, Type pt, Infer.InferenceContext inferenceContext) {
   664             StuckChecker sc = new StuckChecker(pt, inferenceContext);
   665             sc.scan(tree);
   666             return List.from(sc.stuckVars);
   667         }
   669     /**
   670      * A special tree scanner that would only visit portions of a given tree.
   671      * The set of nodes visited by the scanner can be customized at construction-time.
   672      */
   673     abstract static class FilterScanner extends TreeScanner {
   675         final Filter<JCTree> treeFilter;
   677         FilterScanner(final Set<JCTree.Tag> validTags) {
   678             this.treeFilter = new Filter<JCTree>() {
   679                 public boolean accepts(JCTree t) {
   680                     return validTags.contains(t.getTag());
   681                 }
   682             };
   683         }
   685         @Override
   686         public void scan(JCTree tree) {
   687             if (tree != null) {
   688                 if (treeFilter.accepts(tree)) {
   689                     super.scan(tree);
   690                 } else {
   691                     skip(tree);
   692                 }
   693             }
   694         }
   696         /**
   697          * handler that is executed when a node has been discarded
   698          */
   699         abstract void skip(JCTree tree);
   700     }
   702     /**
   703      * A tree scanner suitable for visiting the target-type dependent nodes of
   704      * a given argument expression.
   705      */
   706     static class PolyScanner extends FilterScanner {
   708         PolyScanner() {
   709             super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE));
   710         }
   712         @Override
   713         void skip(JCTree tree) {
   714             //do nothing
   715         }
   716     }
   718     /**
   719      * A tree scanner suitable for visiting the target-type dependent nodes nested
   720      * within a lambda expression body.
   721      */
   722     static class LambdaReturnScanner extends FilterScanner {
   724         LambdaReturnScanner() {
   725             super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
   726                     FORLOOP, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
   727         }
   729         @Override
   730         void skip(JCTree tree) {
   731             //do nothing
   732         }
   733     }
   735     /**
   736      * This visitor is used to check that structural expressions conform
   737      * to their target - this step is required as inference could end up
   738      * inferring types that make some of the nested expressions incompatible
   739      * with their corresponding instantiated target
   740      */
   741     class StuckChecker extends PolyScanner {
   743         Type pt;
   744         Infer.InferenceContext inferenceContext;
   745         Set<Type> stuckVars = new LinkedHashSet<Type>();
   747         StuckChecker(Type pt, Infer.InferenceContext inferenceContext) {
   748             this.pt = pt;
   749             this.inferenceContext = inferenceContext;
   750         }
   752         @Override
   753         public void visitLambda(JCLambda tree) {
   754             if (inferenceContext.inferenceVars().contains(pt)) {
   755                 stuckVars.add(pt);
   756             }
   757             if (!types.isFunctionalInterface(pt)) {
   758                 return;
   759             }
   760             Type descType = types.findDescriptorType(pt);
   761             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
   762             if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT &&
   763                     freeArgVars.nonEmpty()) {
   764                 stuckVars.addAll(freeArgVars);
   765             }
   766             scanLambdaBody(tree, descType.getReturnType());
   767         }
   769         @Override
   770         public void visitReference(JCMemberReference tree) {
   771             scan(tree.expr);
   772             if (inferenceContext.inferenceVars().contains(pt)) {
   773                 stuckVars.add(pt);
   774                 return;
   775             }
   776             if (!types.isFunctionalInterface(pt)) {
   777                 return;
   778             }
   780             Type descType = types.findDescriptorType(pt);
   781             List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
   782             stuckVars.addAll(freeArgVars);
   783         }
   785         void scanLambdaBody(JCLambda lambda, final Type pt) {
   786             if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
   787                 stuckVars.addAll(stuckVarsInternal(lambda.body, pt, inferenceContext));
   788             } else {
   789                 LambdaReturnScanner lambdaScanner = new LambdaReturnScanner() {
   790                     @Override
   791                     public void visitReturn(JCReturn tree) {
   792                         if (tree.expr != null) {
   793                             stuckVars.addAll(stuckVarsInternal(tree.expr, pt, inferenceContext));
   794                         }
   795                     }
   796                 };
   797                 lambdaScanner.scan(lambda.body);
   798             }
   799         }
   800     }
   801 }

mercurial