DeferredAttr.java revision 3041:37b60162a2db
1/* 2 * Copyright (c) 2012, 2015, 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 */ 25 26package com.sun.tools.javac.comp; 27 28import com.sun.source.tree.LambdaExpressionTree.BodyKind; 29import com.sun.source.tree.NewClassTree; 30import com.sun.tools.javac.code.*; 31import com.sun.tools.javac.code.Type.TypeMapping; 32import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext; 33import com.sun.tools.javac.comp.Resolve.ResolveError; 34import com.sun.tools.javac.resources.CompilerProperties.Fragments; 35import com.sun.tools.javac.tree.*; 36import com.sun.tools.javac.util.*; 37import com.sun.tools.javac.util.DefinedBy.Api; 38import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 39import com.sun.tools.javac.code.Symbol.*; 40import com.sun.tools.javac.comp.Attr.ResultInfo; 41import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase; 42import com.sun.tools.javac.tree.JCTree.*; 43import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType; 44import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler; 45 46import java.util.ArrayList; 47import java.util.Collections; 48import java.util.EnumSet; 49import java.util.LinkedHashMap; 50import java.util.LinkedHashSet; 51import java.util.Map; 52import java.util.Set; 53import java.util.WeakHashMap; 54import java.util.function.Function; 55 56import static com.sun.tools.javac.code.TypeTag.*; 57import static com.sun.tools.javac.tree.JCTree.Tag.*; 58 59/** 60 * This is an helper class that is used to perform deferred type-analysis. 61 * Each time a poly expression occurs in argument position, javac attributes it 62 * with a temporary 'deferred type' that is checked (possibly multiple times) 63 * against an expected formal type. 64 * 65 * <p><b>This is NOT part of any supported API. 66 * If you write code that depends on this, you do so at your own risk. 67 * This code and its internal interfaces are subject to change or 68 * deletion without notice.</b> 69 */ 70public class DeferredAttr extends JCTree.Visitor { 71 protected static final Context.Key<DeferredAttr> deferredAttrKey = new Context.Key<>(); 72 73 final Attr attr; 74 final ArgumentAttr argumentAttr; 75 final Check chk; 76 final JCDiagnostic.Factory diags; 77 final Enter enter; 78 final Infer infer; 79 final Resolve rs; 80 final Log log; 81 final Symtab syms; 82 final TreeMaker make; 83 final TreeCopier<Void> treeCopier; 84 final TypeMapping<Void> deferredCopier; 85 final Types types; 86 final Flow flow; 87 final Names names; 88 final TypeEnvs typeEnvs; 89 90 public static DeferredAttr instance(Context context) { 91 DeferredAttr instance = context.get(deferredAttrKey); 92 if (instance == null) 93 instance = new DeferredAttr(context); 94 return instance; 95 } 96 97 protected DeferredAttr(Context context) { 98 context.put(deferredAttrKey, this); 99 attr = Attr.instance(context); 100 argumentAttr = ArgumentAttr.instance(context); 101 chk = Check.instance(context); 102 diags = JCDiagnostic.Factory.instance(context); 103 enter = Enter.instance(context); 104 infer = Infer.instance(context); 105 rs = Resolve.instance(context); 106 log = Log.instance(context); 107 syms = Symtab.instance(context); 108 make = TreeMaker.instance(context); 109 types = Types.instance(context); 110 flow = Flow.instance(context); 111 names = Names.instance(context); 112 stuckTree = make.Ident(names.empty).setType(Type.stuckType); 113 typeEnvs = TypeEnvs.instance(context); 114 emptyDeferredAttrContext = 115 new DeferredAttrContext(AttrMode.CHECK, null, MethodResolutionPhase.BOX, infer.emptyContext, null, null) { 116 @Override 117 void addDeferredAttrNode(DeferredType dt, ResultInfo ri, DeferredStuckPolicy deferredStuckPolicy) { 118 Assert.error("Empty deferred context!"); 119 } 120 @Override 121 void complete() { 122 Assert.error("Empty deferred context!"); 123 } 124 125 @Override 126 public String toString() { 127 return "Empty deferred context!"; 128 } 129 }; 130 131 // For speculative attribution, skip the class definition in <>. 132 treeCopier = 133 new TreeCopier<Void>(make) { 134 @Override @DefinedBy(Api.COMPILER_TREE) 135 public JCTree visitNewClass(NewClassTree node, Void p) { 136 JCNewClass t = (JCNewClass) node; 137 if (TreeInfo.isDiamond(t)) { 138 JCExpression encl = copy(t.encl, p); 139 List<JCExpression> typeargs = copy(t.typeargs, p); 140 JCExpression clazz = copy(t.clazz, p); 141 List<JCExpression> args = copy(t.args, p); 142 JCClassDecl def = null; 143 return make.at(t.pos).NewClass(encl, typeargs, clazz, args, def); 144 } else { 145 return super.visitNewClass(node, p); 146 } 147 } 148 }; 149 deferredCopier = new TypeMapping<Void> () { 150 @Override 151 public Type visitType(Type t, Void v) { 152 if (t.hasTag(DEFERRED)) { 153 DeferredType dt = (DeferredType) t; 154 return new DeferredType(treeCopier.copy(dt.tree), dt.env); 155 } 156 return t; 157 } 158 }; 159 } 160 161 /** shared tree for stuck expressions */ 162 final JCTree stuckTree; 163 164 /** 165 * This type represents a deferred type. A deferred type starts off with 166 * no information on the underlying expression type. Such info needs to be 167 * discovered through type-checking the deferred type against a target-type. 168 * Every deferred type keeps a pointer to the AST node from which it originated. 169 */ 170 public class DeferredType extends Type { 171 172 public JCExpression tree; 173 Env<AttrContext> env; 174 AttrMode mode; 175 SpeculativeCache speculativeCache; 176 177 DeferredType(JCExpression tree, Env<AttrContext> env) { 178 super(null, TypeMetadata.EMPTY); 179 this.tree = tree; 180 this.env = attr.copyEnv(env); 181 this.speculativeCache = new SpeculativeCache(); 182 } 183 184 @Override 185 public DeferredType cloneWithMetadata(TypeMetadata md) { 186 throw new AssertionError("Cannot add metadata to a deferred type"); 187 } 188 189 @Override 190 public TypeTag getTag() { 191 return DEFERRED; 192 } 193 194 @Override @DefinedBy(Api.LANGUAGE_MODEL) 195 public String toString() { 196 return "DeferredType"; 197 } 198 199 /** 200 * A speculative cache is used to keep track of all overload resolution rounds 201 * that triggered speculative attribution on a given deferred type. Each entry 202 * stores a pointer to the speculative tree and the resolution phase in which the entry 203 * has been added. 204 */ 205 class SpeculativeCache { 206 207 private Map<Symbol, List<Entry>> cache = new WeakHashMap<>(); 208 209 class Entry { 210 JCTree speculativeTree; 211 ResultInfo resultInfo; 212 213 public Entry(JCTree speculativeTree, ResultInfo resultInfo) { 214 this.speculativeTree = speculativeTree; 215 this.resultInfo = resultInfo; 216 } 217 218 boolean matches(MethodResolutionPhase phase) { 219 return resultInfo.checkContext.deferredAttrContext().phase == phase; 220 } 221 } 222 223 /** 224 * Retrieve a speculative cache entry corresponding to given symbol 225 * and resolution phase 226 */ 227 Entry get(Symbol msym, MethodResolutionPhase phase) { 228 List<Entry> entries = cache.get(msym); 229 if (entries == null) return null; 230 for (Entry e : entries) { 231 if (e.matches(phase)) return e; 232 } 233 return null; 234 } 235 236 /** 237 * Stores a speculative cache entry corresponding to given symbol 238 * and resolution phase 239 */ 240 void put(JCTree speculativeTree, ResultInfo resultInfo) { 241 Symbol msym = resultInfo.checkContext.deferredAttrContext().msym; 242 List<Entry> entries = cache.get(msym); 243 if (entries == null) { 244 entries = List.nil(); 245 } 246 cache.put(msym, entries.prepend(new Entry(speculativeTree, resultInfo))); 247 } 248 } 249 250 /** 251 * Get the type that has been computed during a speculative attribution round 252 */ 253 Type speculativeType(Symbol msym, MethodResolutionPhase phase) { 254 SpeculativeCache.Entry e = speculativeCache.get(msym, phase); 255 return e != null ? e.speculativeTree.type : Type.noType; 256 } 257 258 JCTree speculativeTree(DeferredAttrContext deferredAttrContext) { 259 DeferredType.SpeculativeCache.Entry e = speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase); 260 return e != null ? e.speculativeTree : stuckTree; 261 } 262 263 DeferredTypeCompleter completer() { 264 return basicCompleter; 265 } 266 267 /** 268 * Check a deferred type against a potential target-type. Depending on 269 * the current attribution mode, a normal vs. speculative attribution 270 * round is performed on the underlying AST node. There can be only one 271 * speculative round for a given target method symbol; moreover, a normal 272 * attribution round must follow one or more speculative rounds. 273 */ 274 Type check(ResultInfo resultInfo) { 275 DeferredStuckPolicy deferredStuckPolicy; 276 if (resultInfo.pt.hasTag(NONE) || resultInfo.pt.isErroneous()) { 277 deferredStuckPolicy = dummyStuckPolicy; 278 } else if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.SPECULATIVE || 279 resultInfo.checkContext.deferredAttrContext().insideOverloadPhase()) { 280 deferredStuckPolicy = new OverloadStuckPolicy(resultInfo, this); 281 } else { 282 deferredStuckPolicy = new CheckStuckPolicy(resultInfo, this); 283 } 284 return check(resultInfo, deferredStuckPolicy, completer()); 285 } 286 287 private Type check(ResultInfo resultInfo, DeferredStuckPolicy deferredStuckPolicy, 288 DeferredTypeCompleter deferredTypeCompleter) { 289 DeferredAttrContext deferredAttrContext = 290 resultInfo.checkContext.deferredAttrContext(); 291 Assert.check(deferredAttrContext != emptyDeferredAttrContext); 292 if (deferredStuckPolicy.isStuck()) { 293 deferredAttrContext.addDeferredAttrNode(this, resultInfo, deferredStuckPolicy); 294 return Type.noType; 295 } else { 296 try { 297 return deferredTypeCompleter.complete(this, resultInfo, deferredAttrContext); 298 } finally { 299 mode = deferredAttrContext.mode; 300 } 301 } 302 } 303 } 304 305 /** 306 * A completer for deferred types. Defines an entry point for type-checking 307 * a deferred type. 308 */ 309 interface DeferredTypeCompleter { 310 /** 311 * Entry point for type-checking a deferred type. Depending on the 312 * circumstances, type-checking could amount to full attribution 313 * or partial structural check (aka potential applicability). 314 */ 315 Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext); 316 } 317 318 319 /** 320 * A basic completer for deferred types. This completer type-checks a deferred type 321 * using attribution; depending on the attribution mode, this could be either standard 322 * or speculative attribution. 323 */ 324 DeferredTypeCompleter basicCompleter = new DeferredTypeCompleter() { 325 public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) { 326 switch (deferredAttrContext.mode) { 327 case SPECULATIVE: 328 //Note: if a symbol is imported twice we might do two identical 329 //speculative rounds... 330 Assert.check(dt.mode == null || dt.mode == AttrMode.SPECULATIVE); 331 JCTree speculativeTree = attribSpeculative(dt.tree, dt.env, resultInfo); 332 dt.speculativeCache.put(speculativeTree, resultInfo); 333 return speculativeTree.type; 334 case CHECK: 335 Assert.check(dt.mode != null); 336 return attr.attribTree(dt.tree, dt.env, resultInfo); 337 } 338 Assert.error(); 339 return null; 340 } 341 }; 342 343 /** 344 * Policy for detecting stuck expressions. Different criteria might cause 345 * an expression to be judged as stuck, depending on whether the check 346 * is performed during overload resolution or after most specific. 347 */ 348 interface DeferredStuckPolicy { 349 /** 350 * Has the policy detected that a given expression should be considered stuck? 351 */ 352 boolean isStuck(); 353 /** 354 * Get the set of inference variables a given expression depends upon. 355 */ 356 Set<Type> stuckVars(); 357 /** 358 * Get the set of inference variables which might get new constraints 359 * if a given expression is being type-checked. 360 */ 361 Set<Type> depVars(); 362 } 363 364 /** 365 * Basic stuck policy; an expression is never considered to be stuck. 366 */ 367 DeferredStuckPolicy dummyStuckPolicy = new DeferredStuckPolicy() { 368 @Override 369 public boolean isStuck() { 370 return false; 371 } 372 @Override 373 public Set<Type> stuckVars() { 374 return Collections.emptySet(); 375 } 376 @Override 377 public Set<Type> depVars() { 378 return Collections.emptySet(); 379 } 380 }; 381 382 /** 383 * The 'mode' in which the deferred type is to be type-checked 384 */ 385 public enum AttrMode { 386 /** 387 * A speculative type-checking round is used during overload resolution 388 * mainly to generate constraints on inference variables. Side-effects 389 * arising from type-checking the expression associated with the deferred 390 * type are reversed after the speculative round finishes. This means the 391 * expression tree will be left in a blank state. 392 */ 393 SPECULATIVE, 394 /** 395 * This is the plain type-checking mode. Produces side-effects on the underlying AST node 396 */ 397 CHECK 398 } 399 400 /** 401 * Performs speculative attribution of a lambda body and returns the speculative lambda tree, 402 * in the absence of a target-type. Since {@link Attr#visitLambda(JCLambda)} cannot type-check 403 * lambda bodies w/o a suitable target-type, this routine 'unrolls' the lambda by turning it 404 * into a regular block, speculatively type-checks the block and then puts back the pieces. 405 */ 406 JCLambda attribSpeculativeLambda(JCLambda that, Env<AttrContext> env, ResultInfo resultInfo) { 407 ListBuffer<JCStatement> stats = new ListBuffer<>(); 408 stats.addAll(that.params); 409 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 410 stats.add(make.Return((JCExpression)that.body)); 411 } else { 412 stats.add((JCBlock)that.body); 413 } 414 JCBlock lambdaBlock = make.Block(0, stats.toList()); 415 Env<AttrContext> localEnv = attr.lambdaEnv(that, env); 416 try { 417 localEnv.info.returnResult = resultInfo; 418 JCBlock speculativeTree = (JCBlock)attribSpeculative(lambdaBlock, localEnv, resultInfo); 419 List<JCVariableDecl> args = speculativeTree.getStatements().stream() 420 .filter(s -> s.hasTag(Tag.VARDEF)) 421 .map(t -> (JCVariableDecl)t) 422 .collect(List.collector()); 423 JCTree lambdaBody = speculativeTree.getStatements().last(); 424 if (lambdaBody.hasTag(Tag.RETURN)) { 425 lambdaBody = ((JCReturn)lambdaBody).expr; 426 } 427 JCLambda speculativeLambda = make.Lambda(args, lambdaBody); 428 attr.preFlow(speculativeLambda); 429 flow.analyzeLambda(env, speculativeLambda, make, false); 430 return speculativeLambda; 431 } finally { 432 localEnv.info.scope.leave(); 433 } 434 } 435 436 /** 437 * Routine that performs speculative type-checking; the input AST node is 438 * cloned (to avoid side-effects cause by Attr) and compiler state is 439 * restored after type-checking. All diagnostics (but critical ones) are 440 * disabled during speculative type-checking. 441 */ 442 JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 443 return attribSpeculative(tree, env, resultInfo, treeCopier, 444 (newTree)->new DeferredAttrDiagHandler(log, newTree)); 445 } 446 447 <Z> JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo, TreeCopier<Z> deferredCopier, 448 Function<JCTree, DeferredDiagnosticHandler> diagHandlerCreator) { 449 final JCTree newTree = deferredCopier.copy(tree); 450 Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner))); 451 speculativeEnv.info.isSpeculative = true; 452 Log.DeferredDiagnosticHandler deferredDiagnosticHandler = diagHandlerCreator.apply(newTree); 453 try { 454 attr.attribTree(newTree, speculativeEnv, resultInfo); 455 unenterScanner.scan(newTree); 456 return newTree; 457 } finally { 458 unenterScanner.scan(newTree); 459 log.popDiagnosticHandler(deferredDiagnosticHandler); 460 } 461 } 462 //where 463 protected UnenterScanner unenterScanner = new UnenterScanner(); 464 465 class UnenterScanner extends TreeScanner { 466 @Override 467 public void visitClassDef(JCClassDecl tree) { 468 ClassSymbol csym = tree.sym; 469 //if something went wrong during method applicability check 470 //it is possible that nested expressions inside argument expression 471 //are left unchecked - in such cases there's nothing to clean up. 472 if (csym == null) return; 473 typeEnvs.remove(csym); 474 chk.compiled.remove(csym.flatname); 475 syms.classes.remove(csym.flatname); 476 super.visitClassDef(tree); 477 } 478 } 479 480 static class DeferredAttrDiagHandler extends Log.DeferredDiagnosticHandler { 481 482 static class PosScanner extends TreeScanner { 483 DiagnosticPosition pos; 484 boolean found = false; 485 486 PosScanner(DiagnosticPosition pos) { 487 this.pos = pos; 488 } 489 490 @Override 491 public void scan(JCTree tree) { 492 if (tree != null && 493 tree.pos() == pos) { 494 found = true; 495 } 496 super.scan(tree); 497 } 498 } 499 500 DeferredAttrDiagHandler(Log log, JCTree newTree) { 501 super(log, new Filter<JCDiagnostic>() { 502 public boolean accepts(JCDiagnostic d) { 503 PosScanner posScanner = new PosScanner(d.getDiagnosticPosition()); 504 posScanner.scan(newTree); 505 return posScanner.found; 506 } 507 }); 508 } 509 } 510 511 /** 512 * A deferred context is created on each method check. A deferred context is 513 * used to keep track of information associated with the method check, such as 514 * the symbol of the method being checked, the overload resolution phase, 515 * the kind of attribution mode to be applied to deferred types and so forth. 516 * As deferred types are processed (by the method check routine) stuck AST nodes 517 * are added (as new deferred attribution nodes) to this context. The complete() 518 * routine makes sure that all pending nodes are properly processed, by 519 * progressively instantiating all inference variables on which one or more 520 * deferred attribution node is stuck. 521 */ 522 class DeferredAttrContext { 523 524 /** attribution mode */ 525 final AttrMode mode; 526 527 /** symbol of the method being checked */ 528 final Symbol msym; 529 530 /** method resolution step */ 531 final Resolve.MethodResolutionPhase phase; 532 533 /** inference context */ 534 final InferenceContext inferenceContext; 535 536 /** parent deferred context */ 537 final DeferredAttrContext parent; 538 539 /** Warner object to report warnings */ 540 final Warner warn; 541 542 /** list of deferred attribution nodes to be processed */ 543 ArrayList<DeferredAttrNode> deferredAttrNodes = new ArrayList<>(); 544 545 DeferredAttrContext(AttrMode mode, Symbol msym, MethodResolutionPhase phase, 546 InferenceContext inferenceContext, DeferredAttrContext parent, Warner warn) { 547 this.mode = mode; 548 this.msym = msym; 549 this.phase = phase; 550 this.parent = parent; 551 this.warn = warn; 552 this.inferenceContext = inferenceContext; 553 } 554 555 /** 556 * Adds a node to the list of deferred attribution nodes - used by Resolve.rawCheckArgumentsApplicable 557 * Nodes added this way act as 'roots' for the out-of-order method checking process. 558 */ 559 void addDeferredAttrNode(final DeferredType dt, ResultInfo resultInfo, 560 DeferredStuckPolicy deferredStuckPolicy) { 561 deferredAttrNodes.add(new DeferredAttrNode(dt, resultInfo, deferredStuckPolicy)); 562 } 563 564 /** 565 * Incrementally process all nodes, by skipping 'stuck' nodes and attributing 566 * 'unstuck' ones. If at any point no progress can be made (no 'unstuck' nodes) 567 * some inference variable might get eagerly instantiated so that all nodes 568 * can be type-checked. 569 */ 570 void complete() { 571 while (!deferredAttrNodes.isEmpty()) { 572 Map<Type, Set<Type>> depVarsMap = new LinkedHashMap<>(); 573 List<Type> stuckVars = List.nil(); 574 boolean progress = false; 575 //scan a defensive copy of the node list - this is because a deferred 576 //attribution round can add new nodes to the list 577 for (DeferredAttrNode deferredAttrNode : List.from(deferredAttrNodes)) { 578 if (!deferredAttrNode.process(this)) { 579 List<Type> restStuckVars = 580 List.from(deferredAttrNode.deferredStuckPolicy.stuckVars()) 581 .intersect(inferenceContext.restvars()); 582 stuckVars = stuckVars.prependList(restStuckVars); 583 //update dependency map 584 for (Type t : List.from(deferredAttrNode.deferredStuckPolicy.depVars()) 585 .intersect(inferenceContext.restvars())) { 586 Set<Type> prevDeps = depVarsMap.get(t); 587 if (prevDeps == null) { 588 prevDeps = new LinkedHashSet<>(); 589 depVarsMap.put(t, prevDeps); 590 } 591 prevDeps.addAll(restStuckVars); 592 } 593 } else { 594 deferredAttrNodes.remove(deferredAttrNode); 595 progress = true; 596 } 597 } 598 if (!progress) { 599 if (insideOverloadPhase()) { 600 for (DeferredAttrNode deferredNode: deferredAttrNodes) { 601 deferredNode.dt.tree.type = Type.noType; 602 } 603 return; 604 } 605 //remove all variables that have already been instantiated 606 //from the list of stuck variables 607 try { 608 inferenceContext.solveAny(stuckVars, depVarsMap, warn); 609 inferenceContext.notifyChange(); 610 } catch (Infer.GraphStrategy.NodeNotFoundException ex) { 611 //this means that we are in speculative mode and the 612 //set of contraints are too tight for progess to be made. 613 //Just leave the remaining expressions as stuck. 614 break; 615 } 616 } 617 } 618 } 619 620 public boolean insideOverloadPhase() { 621 DeferredAttrContext dac = this; 622 if (dac == emptyDeferredAttrContext) { 623 return false; 624 } 625 if (dac.mode == AttrMode.SPECULATIVE) { 626 return true; 627 } 628 return dac.parent.insideOverloadPhase(); 629 } 630 } 631 632 /** 633 * Class representing a deferred attribution node. It keeps track of 634 * a deferred type, along with the expected target type information. 635 */ 636 class DeferredAttrNode { 637 638 /** underlying deferred type */ 639 DeferredType dt; 640 641 /** underlying target type information */ 642 ResultInfo resultInfo; 643 644 /** stuck policy associated with this node */ 645 DeferredStuckPolicy deferredStuckPolicy; 646 647 DeferredAttrNode(DeferredType dt, ResultInfo resultInfo, DeferredStuckPolicy deferredStuckPolicy) { 648 this.dt = dt; 649 this.resultInfo = resultInfo; 650 this.deferredStuckPolicy = deferredStuckPolicy; 651 } 652 653 /** 654 * Process a deferred attribution node. 655 * Invariant: a stuck node cannot be processed. 656 */ 657 @SuppressWarnings("fallthrough") 658 boolean process(final DeferredAttrContext deferredAttrContext) { 659 switch (deferredAttrContext.mode) { 660 case SPECULATIVE: 661 if (deferredStuckPolicy.isStuck()) { 662 dt.check(resultInfo, dummyStuckPolicy, new StructuralStuckChecker()); 663 return true; 664 } else { 665 Assert.error("Cannot get here"); 666 } 667 case CHECK: 668 if (deferredStuckPolicy.isStuck()) { 669 //stuck expression - see if we can propagate 670 if (deferredAttrContext.parent != emptyDeferredAttrContext && 671 Type.containsAny(deferredAttrContext.parent.inferenceContext.inferencevars, 672 List.from(deferredStuckPolicy.stuckVars()))) { 673 deferredAttrContext.parent.addDeferredAttrNode(dt, 674 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) { 675 @Override 676 public InferenceContext inferenceContext() { 677 return deferredAttrContext.parent.inferenceContext; 678 } 679 @Override 680 public DeferredAttrContext deferredAttrContext() { 681 return deferredAttrContext.parent; 682 } 683 }), deferredStuckPolicy); 684 dt.tree.type = Type.stuckType; 685 return true; 686 } else { 687 return false; 688 } 689 } else { 690 Assert.check(!deferredAttrContext.insideOverloadPhase(), 691 "attribution shouldn't be happening here"); 692 ResultInfo instResultInfo = 693 resultInfo.dup(deferredAttrContext.inferenceContext.asInstType(resultInfo.pt)); 694 dt.check(instResultInfo, dummyStuckPolicy, basicCompleter); 695 return true; 696 } 697 default: 698 throw new AssertionError("Bad mode"); 699 } 700 } 701 702 /** 703 * Structural checker for stuck expressions 704 */ 705 class StructuralStuckChecker extends TreeScanner implements DeferredTypeCompleter { 706 707 ResultInfo resultInfo; 708 InferenceContext inferenceContext; 709 Env<AttrContext> env; 710 711 public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) { 712 this.resultInfo = resultInfo; 713 this.inferenceContext = deferredAttrContext.inferenceContext; 714 this.env = dt.env; 715 dt.tree.accept(this); 716 dt.speculativeCache.put(stuckTree, resultInfo); 717 return Type.noType; 718 } 719 720 @Override 721 public void visitLambda(JCLambda tree) { 722 Check.CheckContext checkContext = resultInfo.checkContext; 723 Type pt = resultInfo.pt; 724 if (!inferenceContext.inferencevars.contains(pt)) { 725 //must be a functional descriptor 726 Type descriptorType = null; 727 try { 728 descriptorType = types.findDescriptorType(pt); 729 } catch (Types.FunctionDescriptorLookupError ex) { 730 checkContext.report(null, ex.getDiagnostic()); 731 } 732 733 if (descriptorType.getParameterTypes().length() != tree.params.length()) { 734 checkContext.report(tree, 735 diags.fragment("incompatible.arg.types.in.lambda")); 736 } 737 738 Type currentReturnType = descriptorType.getReturnType(); 739 boolean returnTypeIsVoid = currentReturnType.hasTag(VOID); 740 if (tree.getBodyKind() == BodyKind.EXPRESSION) { 741 boolean isExpressionCompatible = !returnTypeIsVoid || 742 TreeInfo.isExpressionStatement((JCExpression)tree.getBody()); 743 if (!isExpressionCompatible) { 744 resultInfo.checkContext.report(tree.pos(), 745 diags.fragment("incompatible.ret.type.in.lambda", 746 diags.fragment("missing.ret.val", currentReturnType))); 747 } 748 } else { 749 LambdaBodyStructChecker lambdaBodyChecker = 750 new LambdaBodyStructChecker(); 751 752 tree.body.accept(lambdaBodyChecker); 753 boolean isVoidCompatible = lambdaBodyChecker.isVoidCompatible; 754 755 if (returnTypeIsVoid) { 756 if (!isVoidCompatible) { 757 resultInfo.checkContext.report(tree.pos(), 758 diags.fragment("unexpected.ret.val")); 759 } 760 } else { 761 boolean isValueCompatible = lambdaBodyChecker.isPotentiallyValueCompatible 762 && !canLambdaBodyCompleteNormally(tree); 763 if (!isValueCompatible && !isVoidCompatible) { 764 log.error(tree.body.pos(), 765 "lambda.body.neither.value.nor.void.compatible"); 766 } 767 768 if (!isValueCompatible) { 769 resultInfo.checkContext.report(tree.pos(), 770 diags.fragment("incompatible.ret.type.in.lambda", 771 diags.fragment("missing.ret.val", currentReturnType))); 772 } 773 } 774 } 775 } 776 } 777 778 boolean canLambdaBodyCompleteNormally(JCLambda tree) { 779 List<JCVariableDecl> oldParams = tree.params; 780 LocalCacheContext localCacheContext = argumentAttr.withLocalCacheContext(); 781 try { 782 tree.params = tree.params.stream() 783 .map(vd -> make.VarDef(vd.mods, vd.name, make.Erroneous(), null)) 784 .collect(List.collector()); 785 return attribSpeculativeLambda(tree, env, attr.unknownExprInfo).canCompleteNormally; 786 } finally { 787 localCacheContext.leave(); 788 tree.params = oldParams; 789 } 790 } 791 792 @Override 793 public void visitNewClass(JCNewClass tree) { 794 //do nothing 795 } 796 797 @Override 798 public void visitApply(JCMethodInvocation tree) { 799 //do nothing 800 } 801 802 @Override 803 public void visitReference(JCMemberReference tree) { 804 Check.CheckContext checkContext = resultInfo.checkContext; 805 Type pt = resultInfo.pt; 806 if (!inferenceContext.inferencevars.contains(pt)) { 807 try { 808 types.findDescriptorType(pt); 809 } catch (Types.FunctionDescriptorLookupError ex) { 810 checkContext.report(null, ex.getDiagnostic()); 811 } 812 Env<AttrContext> localEnv = env.dup(tree); 813 JCExpression exprTree = (JCExpression)attribSpeculative(tree.getQualifierExpression(), localEnv, 814 attr.memberReferenceQualifierResult(tree)); 815 ListBuffer<Type> argtypes = new ListBuffer<>(); 816 for (Type t : types.findDescriptorType(pt).getParameterTypes()) { 817 argtypes.append(Type.noType); 818 } 819 JCMemberReference mref2 = new TreeCopier<Void>(make).copy(tree); 820 mref2.expr = exprTree; 821 Symbol lookupSym = 822 rs.resolveMemberReference(localEnv, mref2, exprTree.type, 823 tree.name, argtypes.toList(), List.nil(), rs.arityMethodCheck, 824 inferenceContext, rs.structuralReferenceChooser).fst; 825 switch (lookupSym.kind) { 826 case WRONG_MTH: 827 case WRONG_MTHS: 828 //note: as argtypes are erroneous types, type-errors must 829 //have been caused by arity mismatch 830 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInMref)); 831 break; 832 case ABSENT_MTH: 833 case STATICERR: 834 //if no method found, or method found with wrong staticness, report better message 835 checkContext.report(tree, ((ResolveError)lookupSym).getDiagnostic(DiagnosticType.FRAGMENT, 836 tree, exprTree.type.tsym, exprTree.type, tree.name, argtypes.toList(), List.nil())); 837 break; 838 } 839 } 840 } 841 } 842 843 /* This visitor looks for return statements, its analysis will determine if 844 * a lambda body is void or value compatible. We must analyze return 845 * statements contained in the lambda body only, thus any return statement 846 * contained in an inner class or inner lambda body, should be ignored. 847 */ 848 class LambdaBodyStructChecker extends TreeScanner { 849 boolean isVoidCompatible = true; 850 boolean isPotentiallyValueCompatible = true; 851 852 @Override 853 public void visitClassDef(JCClassDecl tree) { 854 // do nothing 855 } 856 857 @Override 858 public void visitLambda(JCLambda tree) { 859 // do nothing 860 } 861 862 @Override 863 public void visitNewClass(JCNewClass tree) { 864 // do nothing 865 } 866 867 @Override 868 public void visitReturn(JCReturn tree) { 869 if (tree.expr != null) { 870 isVoidCompatible = false; 871 } else { 872 isPotentiallyValueCompatible = false; 873 } 874 } 875 } 876 } 877 878 /** an empty deferred attribution context - all methods throw exceptions */ 879 final DeferredAttrContext emptyDeferredAttrContext; 880 881 /** 882 * Map a list of types possibly containing one or more deferred types 883 * into a list of ordinary types. Each deferred type D is mapped into a type T, 884 * where T is computed by retrieving the type that has already been 885 * computed for D during a previous deferred attribution round of the given kind. 886 */ 887 class DeferredTypeMap extends TypeMapping<Void> { 888 DeferredAttrContext deferredAttrContext; 889 890 protected DeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) { 891 this.deferredAttrContext = new DeferredAttrContext(mode, msym, phase, 892 infer.emptyContext, emptyDeferredAttrContext, types.noWarnings); 893 } 894 895 @Override 896 public Type visitType(Type t, Void _unused) { 897 if (!t.hasTag(DEFERRED)) { 898 return super.visitType(t, null); 899 } else { 900 DeferredType dt = (DeferredType)t; 901 return typeOf(dt); 902 } 903 } 904 905 protected Type typeOf(DeferredType dt) { 906 switch (deferredAttrContext.mode) { 907 case CHECK: 908 return dt.tree.type == null ? Type.noType : dt.tree.type; 909 case SPECULATIVE: 910 return dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase); 911 } 912 Assert.error(); 913 return null; 914 } 915 } 916 917 /** 918 * Specialized recovery deferred mapping. 919 * Each deferred type D is mapped into a type T, where T is computed either by 920 * (i) retrieving the type that has already been computed for D during a previous 921 * attribution round (as before), or (ii) by synthesizing a new type R for D 922 * (the latter step is useful in a recovery scenario). 923 */ 924 public class RecoveryDeferredTypeMap extends DeferredTypeMap { 925 926 public RecoveryDeferredTypeMap(AttrMode mode, Symbol msym, MethodResolutionPhase phase) { 927 super(mode, msym, phase != null ? phase : MethodResolutionPhase.BOX); 928 } 929 930 @Override 931 protected Type typeOf(DeferredType dt) { 932 Type owntype = super.typeOf(dt); 933 return owntype == Type.noType ? 934 recover(dt) : owntype; 935 } 936 937 /** 938 * Synthesize a type for a deferred type that hasn't been previously 939 * reduced to an ordinary type. Functional deferred types and conditionals 940 * are mapped to themselves, in order to have a richer diagnostic 941 * representation. Remaining deferred types are attributed using 942 * a default expected type (j.l.Object). 943 */ 944 private Type recover(DeferredType dt) { 945 dt.check(attr.new RecoveryInfo(deferredAttrContext) { 946 @Override 947 protected Type check(DiagnosticPosition pos, Type found) { 948 return chk.checkNonVoid(pos, super.check(pos, found)); 949 } 950 }); 951 return super.visit(dt); 952 } 953 } 954 955 /** 956 * A special tree scanner that would only visit portions of a given tree. 957 * The set of nodes visited by the scanner can be customized at construction-time. 958 */ 959 abstract static class FilterScanner extends com.sun.tools.javac.tree.TreeScanner { 960 961 final Filter<JCTree> treeFilter; 962 963 FilterScanner(final Set<JCTree.Tag> validTags) { 964 this.treeFilter = new Filter<JCTree>() { 965 public boolean accepts(JCTree t) { 966 return validTags.contains(t.getTag()); 967 } 968 }; 969 } 970 971 @Override 972 public void scan(JCTree tree) { 973 if (tree != null) { 974 if (treeFilter.accepts(tree)) { 975 super.scan(tree); 976 } else { 977 skip(tree); 978 } 979 } 980 } 981 982 /** 983 * handler that is executed when a node has been discarded 984 */ 985 void skip(JCTree tree) {} 986 } 987 988 /** 989 * A tree scanner suitable for visiting the target-type dependent nodes of 990 * a given argument expression. 991 */ 992 static class PolyScanner extends FilterScanner { 993 994 PolyScanner() { 995 super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE)); 996 } 997 } 998 999 /** 1000 * A tree scanner suitable for visiting the target-type dependent nodes nested 1001 * within a lambda expression body. 1002 */ 1003 static class LambdaReturnScanner extends FilterScanner { 1004 1005 LambdaReturnScanner() { 1006 super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP, 1007 FORLOOP, IF, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP)); 1008 } 1009 } 1010 1011 /** 1012 * This visitor is used to check that structural expressions conform 1013 * to their target - this step is required as inference could end up 1014 * inferring types that make some of the nested expressions incompatible 1015 * with their corresponding instantiated target 1016 */ 1017 class CheckStuckPolicy extends PolyScanner implements DeferredStuckPolicy, Infer.FreeTypeListener { 1018 1019 Type pt; 1020 InferenceContext inferenceContext; 1021 Set<Type> stuckVars = new LinkedHashSet<>(); 1022 Set<Type> depVars = new LinkedHashSet<>(); 1023 1024 @Override 1025 public boolean isStuck() { 1026 return !stuckVars.isEmpty(); 1027 } 1028 1029 @Override 1030 public Set<Type> stuckVars() { 1031 return stuckVars; 1032 } 1033 1034 @Override 1035 public Set<Type> depVars() { 1036 return depVars; 1037 } 1038 1039 public CheckStuckPolicy(ResultInfo resultInfo, DeferredType dt) { 1040 this.pt = resultInfo.pt; 1041 this.inferenceContext = resultInfo.checkContext.inferenceContext(); 1042 scan(dt.tree); 1043 if (!stuckVars.isEmpty()) { 1044 resultInfo.checkContext.inferenceContext() 1045 .addFreeTypeListener(List.from(stuckVars), this); 1046 } 1047 } 1048 1049 @Override 1050 public void typesInferred(InferenceContext inferenceContext) { 1051 stuckVars.clear(); 1052 } 1053 1054 @Override 1055 public void visitLambda(JCLambda tree) { 1056 if (inferenceContext.inferenceVars().contains(pt)) { 1057 stuckVars.add(pt); 1058 } 1059 if (!types.isFunctionalInterface(pt)) { 1060 return; 1061 } 1062 Type descType = types.findDescriptorType(pt); 1063 List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes()); 1064 if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT && 1065 freeArgVars.nonEmpty()) { 1066 stuckVars.addAll(freeArgVars); 1067 depVars.addAll(inferenceContext.freeVarsIn(descType.getReturnType())); 1068 } 1069 scanLambdaBody(tree, descType.getReturnType()); 1070 } 1071 1072 @Override 1073 public void visitReference(JCMemberReference tree) { 1074 scan(tree.expr); 1075 if (inferenceContext.inferenceVars().contains(pt)) { 1076 stuckVars.add(pt); 1077 return; 1078 } 1079 if (!types.isFunctionalInterface(pt)) { 1080 return; 1081 } 1082 1083 Type descType = types.findDescriptorType(pt); 1084 List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes()); 1085 if (freeArgVars.nonEmpty() && 1086 tree.overloadKind == JCMemberReference.OverloadKind.OVERLOADED) { 1087 stuckVars.addAll(freeArgVars); 1088 depVars.addAll(inferenceContext.freeVarsIn(descType.getReturnType())); 1089 } 1090 } 1091 1092 void scanLambdaBody(JCLambda lambda, final Type pt) { 1093 if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) { 1094 Type prevPt = this.pt; 1095 try { 1096 this.pt = pt; 1097 scan(lambda.body); 1098 } finally { 1099 this.pt = prevPt; 1100 } 1101 } else { 1102 LambdaReturnScanner lambdaScanner = new LambdaReturnScanner() { 1103 @Override 1104 public void visitReturn(JCReturn tree) { 1105 if (tree.expr != null) { 1106 Type prevPt = CheckStuckPolicy.this.pt; 1107 try { 1108 CheckStuckPolicy.this.pt = pt; 1109 CheckStuckPolicy.this.scan(tree.expr); 1110 } finally { 1111 CheckStuckPolicy.this.pt = prevPt; 1112 } 1113 } 1114 } 1115 }; 1116 lambdaScanner.scan(lambda.body); 1117 } 1118 } 1119 } 1120 1121 /** 1122 * This visitor is used to check that structural expressions conform 1123 * to their target - this step is required as inference could end up 1124 * inferring types that make some of the nested expressions incompatible 1125 * with their corresponding instantiated target 1126 */ 1127 class OverloadStuckPolicy extends CheckStuckPolicy implements DeferredStuckPolicy { 1128 1129 boolean stuck; 1130 1131 @Override 1132 public boolean isStuck() { 1133 return super.isStuck() || stuck; 1134 } 1135 1136 public OverloadStuckPolicy(ResultInfo resultInfo, DeferredType dt) { 1137 super(resultInfo, dt); 1138 } 1139 1140 @Override 1141 public void visitLambda(JCLambda tree) { 1142 super.visitLambda(tree); 1143 if (tree.paramKind == JCLambda.ParameterKind.IMPLICIT) { 1144 stuck = true; 1145 } 1146 } 1147 1148 @Override 1149 public void visitReference(JCMemberReference tree) { 1150 super.visitReference(tree); 1151 if (tree.overloadKind == JCMemberReference.OverloadKind.OVERLOADED) { 1152 stuck = true; 1153 } 1154 } 1155 } 1156} 1157