Attr.java revision 2906:e847f2a2c3d0
1/* 2 * Copyright (c) 1999, 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 java.util.*; 29 30import javax.lang.model.element.ElementKind; 31import javax.tools.JavaFileObject; 32 33import com.sun.source.tree.IdentifierTree; 34import com.sun.source.tree.MemberReferenceTree.ReferenceMode; 35import com.sun.source.tree.MemberSelectTree; 36import com.sun.source.tree.TreeVisitor; 37import com.sun.source.util.SimpleTreeVisitor; 38import com.sun.tools.javac.code.*; 39import com.sun.tools.javac.code.Lint.LintCategory; 40import com.sun.tools.javac.code.Scope.WriteableScope; 41import com.sun.tools.javac.code.Symbol.*; 42import com.sun.tools.javac.code.Type.*; 43import com.sun.tools.javac.code.TypeMetadata.Annotations; 44import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError; 45import com.sun.tools.javac.comp.Check.CheckContext; 46import com.sun.tools.javac.comp.DeferredAttr.AttrMode; 47import com.sun.tools.javac.comp.Infer.InferenceContext; 48import com.sun.tools.javac.comp.Infer.FreeTypeListener; 49import com.sun.tools.javac.jvm.*; 50import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond; 51import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg; 52import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs; 53import com.sun.tools.javac.resources.CompilerProperties.Errors; 54import com.sun.tools.javac.resources.CompilerProperties.Fragments; 55import com.sun.tools.javac.tree.*; 56import com.sun.tools.javac.tree.JCTree.*; 57import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 58import com.sun.tools.javac.util.*; 59import com.sun.tools.javac.util.DefinedBy.Api; 60import com.sun.tools.javac.util.Dependencies.AttributionKind; 61import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 62import com.sun.tools.javac.util.JCDiagnostic.Fragment; 63import com.sun.tools.javac.util.List; 64import static com.sun.tools.javac.code.Flags.*; 65import static com.sun.tools.javac.code.Flags.ANNOTATION; 66import static com.sun.tools.javac.code.Flags.BLOCK; 67import static com.sun.tools.javac.code.Kinds.*; 68import static com.sun.tools.javac.code.Kinds.Kind.*; 69import static com.sun.tools.javac.code.TypeTag.*; 70import static com.sun.tools.javac.code.TypeTag.WILDCARD; 71import static com.sun.tools.javac.tree.JCTree.Tag.*; 72 73/** This is the main context-dependent analysis phase in GJC. It 74 * encompasses name resolution, type checking and constant folding as 75 * subtasks. Some subtasks involve auxiliary classes. 76 * @see Check 77 * @see Resolve 78 * @see ConstFold 79 * @see Infer 80 * 81 * <p><b>This is NOT part of any supported API. 82 * If you write code that depends on this, you do so at your own risk. 83 * This code and its internal interfaces are subject to change or 84 * deletion without notice.</b> 85 */ 86public class Attr extends JCTree.Visitor { 87 protected static final Context.Key<Attr> attrKey = new Context.Key<>(); 88 89 final Names names; 90 final Log log; 91 final Symtab syms; 92 final Resolve rs; 93 final Operators operators; 94 final Infer infer; 95 final Analyzer analyzer; 96 final DeferredAttr deferredAttr; 97 final Check chk; 98 final Flow flow; 99 final MemberEnter memberEnter; 100 final TypeEnter typeEnter; 101 final TreeMaker make; 102 final ConstFold cfolder; 103 final Enter enter; 104 final Target target; 105 final Types types; 106 final JCDiagnostic.Factory diags; 107 final TypeAnnotations typeAnnotations; 108 final DeferredLintHandler deferredLintHandler; 109 final TypeEnvs typeEnvs; 110 final Dependencies dependencies; 111 final Annotate annotate; 112 113 public static Attr instance(Context context) { 114 Attr instance = context.get(attrKey); 115 if (instance == null) 116 instance = new Attr(context); 117 return instance; 118 } 119 120 protected Attr(Context context) { 121 context.put(attrKey, this); 122 123 names = Names.instance(context); 124 log = Log.instance(context); 125 syms = Symtab.instance(context); 126 rs = Resolve.instance(context); 127 operators = Operators.instance(context); 128 chk = Check.instance(context); 129 flow = Flow.instance(context); 130 memberEnter = MemberEnter.instance(context); 131 typeEnter = TypeEnter.instance(context); 132 make = TreeMaker.instance(context); 133 enter = Enter.instance(context); 134 infer = Infer.instance(context); 135 analyzer = Analyzer.instance(context); 136 deferredAttr = DeferredAttr.instance(context); 137 cfolder = ConstFold.instance(context); 138 target = Target.instance(context); 139 types = Types.instance(context); 140 diags = JCDiagnostic.Factory.instance(context); 141 annotate = Annotate.instance(context); 142 typeAnnotations = TypeAnnotations.instance(context); 143 deferredLintHandler = DeferredLintHandler.instance(context); 144 typeEnvs = TypeEnvs.instance(context); 145 dependencies = Dependencies.instance(context); 146 147 Options options = Options.instance(context); 148 149 Source source = Source.instance(context); 150 allowStringsInSwitch = source.allowStringsInSwitch(); 151 allowPoly = source.allowPoly(); 152 allowTypeAnnos = source.allowTypeAnnotations(); 153 allowLambda = source.allowLambda(); 154 allowDefaultMethods = source.allowDefaultMethods(); 155 allowStaticInterfaceMethods = source.allowStaticInterfaceMethods(); 156 sourceName = source.name; 157 relax = (options.isSet("-retrofit") || 158 options.isSet("-relax")); 159 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); 160 161 statInfo = new ResultInfo(KindSelector.NIL, Type.noType); 162 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType); 163 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType); 164 unknownAnyPolyInfo = new ResultInfo(KindSelector.VAL, Infer.anyPoly); 165 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType); 166 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType); 167 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); 168 } 169 170 /** Switch: relax some constraints for retrofit mode. 171 */ 172 boolean relax; 173 174 /** Switch: support target-typing inference 175 */ 176 boolean allowPoly; 177 178 /** Switch: support type annotations. 179 */ 180 boolean allowTypeAnnos; 181 182 /** Switch: support lambda expressions ? 183 */ 184 boolean allowLambda; 185 186 /** Switch: support default methods ? 187 */ 188 boolean allowDefaultMethods; 189 190 /** Switch: static interface methods enabled? 191 */ 192 boolean allowStaticInterfaceMethods; 193 194 /** 195 * Switch: warn about use of variable before declaration? 196 * RFE: 6425594 197 */ 198 boolean useBeforeDeclarationWarning; 199 200 /** 201 * Switch: allow strings in switch? 202 */ 203 boolean allowStringsInSwitch; 204 205 /** 206 * Switch: name of source level; used for error reporting. 207 */ 208 String sourceName; 209 210 /** Check kind and type of given tree against protokind and prototype. 211 * If check succeeds, store type in tree and return it. 212 * If check fails, store errType in tree and return it. 213 * No checks are performed if the prototype is a method type. 214 * It is not necessary in this case since we know that kind and type 215 * are correct. 216 * 217 * @param tree The tree whose kind and type is checked 218 * @param found The computed type of the tree 219 * @param ownkind The computed kind of the tree 220 * @param resultInfo The expected result of the tree 221 */ 222 Type check(final JCTree tree, 223 final Type found, 224 final KindSelector ownkind, 225 final ResultInfo resultInfo) { 226 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 227 Type owntype; 228 boolean shouldCheck = !found.hasTag(ERROR) && 229 !resultInfo.pt.hasTag(METHOD) && 230 !resultInfo.pt.hasTag(FORALL); 231 if (shouldCheck && !ownkind.subset(resultInfo.pkind)) { 232 log.error(tree.pos(), "unexpected.type", 233 resultInfo.pkind.kindNames(), 234 ownkind.kindNames()); 235 owntype = types.createErrorType(found); 236 } else if (allowPoly && inferenceContext.free(found)) { 237 //delay the check if there are inference variables in the found type 238 //this means we are dealing with a partially inferred poly expression 239 owntype = shouldCheck ? resultInfo.pt : found; 240 if (resultInfo.checkMode.installPostInferenceHook()) { 241 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), 242 instantiatedContext -> { 243 ResultInfo pendingResult = 244 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); 245 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); 246 }); 247 } 248 } else { 249 owntype = shouldCheck ? 250 resultInfo.check(tree, found) : 251 found; 252 } 253 if (resultInfo.checkMode.updateTreeType()) { 254 tree.type = owntype; 255 } 256 return owntype; 257 } 258 259 /** Is given blank final variable assignable, i.e. in a scope where it 260 * may be assigned to even though it is final? 261 * @param v The blank final variable. 262 * @param env The current environment. 263 */ 264 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 265 Symbol owner = env.info.scope.owner; 266 // owner refers to the innermost variable, method or 267 // initializer block declaration at this point. 268 return 269 v.owner == owner 270 || 271 ((owner.name == names.init || // i.e. we are in a constructor 272 owner.kind == VAR || // i.e. we are in a variable initializer 273 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 274 && 275 v.owner == owner.owner 276 && 277 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 278 } 279 280 /** Check that variable can be assigned to. 281 * @param pos The current source code position. 282 * @param v The assigned varaible 283 * @param base If the variable is referred to in a Select, the part 284 * to the left of the `.', null otherwise. 285 * @param env The current environment. 286 */ 287 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 288 if ((v.flags() & FINAL) != 0 && 289 ((v.flags() & HASINIT) != 0 290 || 291 !((base == null || 292 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) && 293 isAssignableAsBlankFinal(v, env)))) { 294 if (v.isResourceVariable()) { //TWR resource 295 log.error(pos, "try.resource.may.not.be.assigned", v); 296 } else { 297 log.error(pos, "cant.assign.val.to.final.var", v); 298 } 299 } 300 } 301 302 /** Does tree represent a static reference to an identifier? 303 * It is assumed that tree is either a SELECT or an IDENT. 304 * We have to weed out selects from non-type names here. 305 * @param tree The candidate tree. 306 */ 307 boolean isStaticReference(JCTree tree) { 308 if (tree.hasTag(SELECT)) { 309 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 310 if (lsym == null || lsym.kind != TYP) { 311 return false; 312 } 313 } 314 return true; 315 } 316 317 /** Is this symbol a type? 318 */ 319 static boolean isType(Symbol sym) { 320 return sym != null && sym.kind == TYP; 321 } 322 323 /** The current `this' symbol. 324 * @param env The current environment. 325 */ 326 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 327 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 328 } 329 330 /** Attribute a parsed identifier. 331 * @param tree Parsed identifier name 332 * @param topLevel The toplevel to use 333 */ 334 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 335 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 336 localEnv.enclClass = make.ClassDef(make.Modifiers(0), 337 syms.errSymbol.name, 338 null, null, null, null); 339 localEnv.enclClass.sym = syms.errSymbol; 340 return tree.accept(identAttributer, localEnv); 341 } 342 // where 343 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 344 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 345 @Override @DefinedBy(Api.COMPILER_TREE) 346 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 347 Symbol site = visit(node.getExpression(), env); 348 if (site.kind == ERR || site.kind == ABSENT_TYP) 349 return site; 350 Name name = (Name)node.getIdentifier(); 351 if (site.kind == PCK) { 352 env.toplevel.packge = (PackageSymbol)site; 353 return rs.findIdentInPackage(env, (TypeSymbol)site, name, 354 KindSelector.TYP_PCK); 355 } else { 356 env.enclClass.sym = (ClassSymbol)site; 357 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 358 } 359 } 360 361 @Override @DefinedBy(Api.COMPILER_TREE) 362 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 363 return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK); 364 } 365 } 366 367 public Type coerce(Type etype, Type ttype) { 368 return cfolder.coerce(etype, ttype); 369 } 370 371 public Type attribType(JCTree node, TypeSymbol sym) { 372 Env<AttrContext> env = typeEnvs.get(sym); 373 Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 374 return attribTree(node, localEnv, unknownTypeInfo); 375 } 376 377 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) { 378 // Attribute qualifying package or class. 379 JCFieldAccess s = (JCFieldAccess)tree.qualid; 380 return attribTree(s.selected, env, 381 new ResultInfo(tree.staticImport ? 382 KindSelector.TYP : KindSelector.TYP_PCK, 383 Type.noType)); 384 } 385 386 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 387 breakTree = tree; 388 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 389 try { 390 attribExpr(expr, env); 391 } catch (BreakAttr b) { 392 return b.env; 393 } catch (AssertionError ae) { 394 if (ae.getCause() instanceof BreakAttr) { 395 return ((BreakAttr)(ae.getCause())).env; 396 } else { 397 throw ae; 398 } 399 } finally { 400 breakTree = null; 401 log.useSource(prev); 402 } 403 return env; 404 } 405 406 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 407 breakTree = tree; 408 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 409 try { 410 attribStat(stmt, env); 411 } catch (BreakAttr b) { 412 return b.env; 413 } catch (AssertionError ae) { 414 if (ae.getCause() instanceof BreakAttr) { 415 return ((BreakAttr)(ae.getCause())).env; 416 } else { 417 throw ae; 418 } 419 } finally { 420 breakTree = null; 421 log.useSource(prev); 422 } 423 return env; 424 } 425 426 private JCTree breakTree = null; 427 428 private static class BreakAttr extends RuntimeException { 429 static final long serialVersionUID = -6924771130405446405L; 430 private Env<AttrContext> env; 431 private BreakAttr(Env<AttrContext> env) { 432 this.env = env; 433 } 434 } 435 436 /** 437 * Mode controlling behavior of Attr.Check 438 */ 439 enum CheckMode { 440 441 NORMAL, 442 443 NO_TREE_UPDATE { // Mode signalling 'fake check' - skip tree update 444 @Override 445 public boolean updateTreeType() { 446 return false; 447 } 448 }, 449 NO_INFERENCE_HOOK { // Mode signalling that caller will manage free types in tree decorations. 450 @Override 451 public boolean installPostInferenceHook() { 452 return false; 453 } 454 }; 455 456 public boolean updateTreeType() { 457 return true; 458 } 459 public boolean installPostInferenceHook() { 460 return true; 461 } 462 } 463 464 465 class ResultInfo { 466 final KindSelector pkind; 467 final Type pt; 468 final CheckContext checkContext; 469 final CheckMode checkMode; 470 471 ResultInfo(KindSelector pkind, Type pt) { 472 this(pkind, pt, chk.basicHandler, CheckMode.NORMAL); 473 } 474 475 ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) { 476 this(pkind, pt, chk.basicHandler, checkMode); 477 } 478 479 protected ResultInfo(KindSelector pkind, 480 Type pt, CheckContext checkContext) { 481 this(pkind, pt, checkContext, CheckMode.NORMAL); 482 } 483 484 protected ResultInfo(KindSelector pkind, 485 Type pt, CheckContext checkContext, CheckMode checkMode) { 486 this.pkind = pkind; 487 this.pt = pt; 488 this.checkContext = checkContext; 489 this.checkMode = checkMode; 490 } 491 492 protected Type check(final DiagnosticPosition pos, final Type found) { 493 return chk.checkType(pos, found, pt, checkContext); 494 } 495 496 protected ResultInfo dup(Type newPt) { 497 return new ResultInfo(pkind, newPt, checkContext, checkMode); 498 } 499 500 protected ResultInfo dup(CheckContext newContext) { 501 return new ResultInfo(pkind, pt, newContext, checkMode); 502 } 503 504 protected ResultInfo dup(Type newPt, CheckContext newContext) { 505 return new ResultInfo(pkind, newPt, newContext, checkMode); 506 } 507 508 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) { 509 return new ResultInfo(pkind, newPt, newContext, newMode); 510 } 511 512 protected ResultInfo dup(CheckMode newMode) { 513 return new ResultInfo(pkind, pt, checkContext, newMode); 514 } 515 516 @Override 517 public String toString() { 518 if (pt != null) { 519 return pt.toString(); 520 } else { 521 return ""; 522 } 523 } 524 } 525 526 class RecoveryInfo extends ResultInfo { 527 528 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { 529 super(KindSelector.VAL, Type.recoveryType, 530 new Check.NestedCheckContext(chk.basicHandler) { 531 @Override 532 public DeferredAttr.DeferredAttrContext deferredAttrContext() { 533 return deferredAttrContext; 534 } 535 @Override 536 public boolean compatible(Type found, Type req, Warner warn) { 537 return true; 538 } 539 @Override 540 public void report(DiagnosticPosition pos, JCDiagnostic details) { 541 chk.basicHandler.report(pos, details); 542 } 543 }); 544 } 545 } 546 547 final ResultInfo statInfo; 548 final ResultInfo varAssignmentInfo; 549 final ResultInfo unknownAnyPolyInfo; 550 final ResultInfo unknownExprInfo; 551 final ResultInfo unknownTypeInfo; 552 final ResultInfo unknownTypeExprInfo; 553 final ResultInfo recoveryInfo; 554 555 Type pt() { 556 return resultInfo.pt; 557 } 558 559 KindSelector pkind() { 560 return resultInfo.pkind; 561 } 562 563/* ************************************************************************ 564 * Visitor methods 565 *************************************************************************/ 566 567 /** Visitor argument: the current environment. 568 */ 569 Env<AttrContext> env; 570 571 /** Visitor argument: the currently expected attribution result. 572 */ 573 ResultInfo resultInfo; 574 575 /** Visitor result: the computed type. 576 */ 577 Type result; 578 579 /** Visitor method: attribute a tree, catching any completion failure 580 * exceptions. Return the tree's type. 581 * 582 * @param tree The tree to be visited. 583 * @param env The environment visitor argument. 584 * @param resultInfo The result info visitor argument. 585 */ 586 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 587 Env<AttrContext> prevEnv = this.env; 588 ResultInfo prevResult = this.resultInfo; 589 try { 590 this.env = env; 591 this.resultInfo = resultInfo; 592 tree.accept(this); 593 if (tree == breakTree && 594 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 595 throw new BreakAttr(copyEnv(env)); 596 } 597 return result; 598 } catch (CompletionFailure ex) { 599 tree.type = syms.errType; 600 return chk.completionError(tree.pos(), ex); 601 } finally { 602 this.env = prevEnv; 603 this.resultInfo = prevResult; 604 } 605 } 606 607 Env<AttrContext> copyEnv(Env<AttrContext> env) { 608 Env<AttrContext> newEnv = 609 env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); 610 if (newEnv.outer != null) { 611 newEnv.outer = copyEnv(newEnv.outer); 612 } 613 return newEnv; 614 } 615 616 WriteableScope copyScope(WriteableScope sc) { 617 WriteableScope newScope = WriteableScope.create(sc.owner); 618 List<Symbol> elemsList = List.nil(); 619 for (Symbol sym : sc.getSymbols()) { 620 elemsList = elemsList.prepend(sym); 621 } 622 for (Symbol s : elemsList) { 623 newScope.enter(s); 624 } 625 return newScope; 626 } 627 628 /** Derived visitor method: attribute an expression tree. 629 */ 630 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 631 return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); 632 } 633 634 /** Derived visitor method: attribute an expression tree with 635 * no constraints on the computed type. 636 */ 637 public Type attribExpr(JCTree tree, Env<AttrContext> env) { 638 return attribTree(tree, env, unknownExprInfo); 639 } 640 641 /** Derived visitor method: attribute a type tree. 642 */ 643 public Type attribType(JCTree tree, Env<AttrContext> env) { 644 Type result = attribType(tree, env, Type.noType); 645 return result; 646 } 647 648 /** Derived visitor method: attribute a type tree. 649 */ 650 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 651 Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt)); 652 return result; 653 } 654 655 /** Derived visitor method: attribute a statement or definition tree. 656 */ 657 public Type attribStat(JCTree tree, Env<AttrContext> env) { 658 Env<AttrContext> analyzeEnv = 659 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner))); 660 try { 661 return attribTree(tree, env, statInfo); 662 } finally { 663 analyzer.analyzeIfNeeded(tree, analyzeEnv); 664 } 665 } 666 667 /** Attribute a list of expressions, returning a list of types. 668 */ 669 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 670 ListBuffer<Type> ts = new ListBuffer<>(); 671 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 672 ts.append(attribExpr(l.head, env, pt)); 673 return ts.toList(); 674 } 675 676 /** Attribute a list of statements, returning nothing. 677 */ 678 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 679 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 680 attribStat(l.head, env); 681 } 682 683 /** Attribute the arguments in a method call, returning the method kind. 684 */ 685 KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) { 686 KindSelector kind = initialKind; 687 for (JCExpression arg : trees) { 688 Type argtype; 689 if (allowPoly && deferredAttr.isDeferred(env, arg)) { 690 argtype = deferredAttr.new DeferredType(arg, env); 691 kind = KindSelector.of(KindSelector.POLY, kind); 692 } else { 693 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo)); 694 } 695 argtypes.append(argtype); 696 } 697 return kind; 698 } 699 700 /** Attribute a type argument list, returning a list of types. 701 * Caller is responsible for calling checkRefTypes. 702 */ 703 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 704 ListBuffer<Type> argtypes = new ListBuffer<>(); 705 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 706 argtypes.append(attribType(l.head, env)); 707 return argtypes.toList(); 708 } 709 710 /** Attribute a type argument list, returning a list of types. 711 * Check that all the types are references. 712 */ 713 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 714 List<Type> types = attribAnyTypes(trees, env); 715 return chk.checkRefTypes(trees, types); 716 } 717 718 /** 719 * Attribute type variables (of generic classes or methods). 720 * Compound types are attributed later in attribBounds. 721 * @param typarams the type variables to enter 722 * @param env the current environment 723 */ 724 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) { 725 for (JCTypeParameter tvar : typarams) { 726 dependencies.push(AttributionKind.TVAR, tvar); 727 TypeVar a = (TypeVar)tvar.type; 728 a.tsym.flags_field |= UNATTRIBUTED; 729 a.bound = Type.noType; 730 if (!tvar.bounds.isEmpty()) { 731 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 732 for (JCExpression bound : tvar.bounds.tail) 733 bounds = bounds.prepend(attribType(bound, env)); 734 types.setBounds(a, bounds.reverse()); 735 } else { 736 // if no bounds are given, assume a single bound of 737 // java.lang.Object. 738 types.setBounds(a, List.of(syms.objectType)); 739 } 740 a.tsym.flags_field &= ~UNATTRIBUTED; 741 dependencies.pop(); 742 } 743 for (JCTypeParameter tvar : typarams) { 744 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 745 } 746 } 747 748 /** 749 * Attribute the type references in a list of annotations. 750 */ 751 void attribAnnotationTypes(List<JCAnnotation> annotations, 752 Env<AttrContext> env) { 753 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 754 JCAnnotation a = al.head; 755 attribType(a.annotationType, env); 756 } 757 } 758 759 /** 760 * Attribute a "lazy constant value". 761 * @param env The env for the const value 762 * @param initializer The initializer for the const value 763 * @param type The expected type, or null 764 * @see VarSymbol#setLazyConstValue 765 */ 766 public Object attribLazyConstantValue(Env<AttrContext> env, 767 JCVariableDecl variable, 768 Type type) { 769 770 DiagnosticPosition prevLintPos 771 = deferredLintHandler.setPos(variable.pos()); 772 773 try { 774 Type itype = attribExpr(variable.init, env, type); 775 if (itype.constValue() != null) { 776 return coerce(itype, type).constValue(); 777 } else { 778 return null; 779 } 780 } finally { 781 deferredLintHandler.setPos(prevLintPos); 782 } 783 } 784 785 /** Attribute type reference in an `extends' or `implements' clause. 786 * Supertypes of anonymous inner classes are usually already attributed. 787 * 788 * @param tree The tree making up the type reference. 789 * @param env The environment current at the reference. 790 * @param classExpected true if only a class is expected here. 791 * @param interfaceExpected true if only an interface is expected here. 792 */ 793 Type attribBase(JCTree tree, 794 Env<AttrContext> env, 795 boolean classExpected, 796 boolean interfaceExpected, 797 boolean checkExtensible) { 798 Type t = tree.type != null ? 799 tree.type : 800 attribType(tree, env); 801 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 802 } 803 Type checkBase(Type t, 804 JCTree tree, 805 Env<AttrContext> env, 806 boolean classExpected, 807 boolean interfaceExpected, 808 boolean checkExtensible) { 809 if (t.tsym.isAnonymous()) { 810 log.error(tree.pos(), "cant.inherit.from.anon"); 811 return types.createErrorType(t); 812 } 813 if (t.isErroneous()) 814 return t; 815 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 816 // check that type variable is already visible 817 if (t.getUpperBound() == null) { 818 log.error(tree.pos(), "illegal.forward.ref"); 819 return types.createErrorType(t); 820 } 821 } else { 822 t = chk.checkClassType(tree.pos(), t, checkExtensible); 823 } 824 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 825 log.error(tree.pos(), "intf.expected.here"); 826 // return errType is necessary since otherwise there might 827 // be undetected cycles which cause attribution to loop 828 return types.createErrorType(t); 829 } else if (checkExtensible && 830 classExpected && 831 (t.tsym.flags() & INTERFACE) != 0) { 832 log.error(tree.pos(), "no.intf.expected.here"); 833 return types.createErrorType(t); 834 } 835 if (checkExtensible && 836 ((t.tsym.flags() & FINAL) != 0)) { 837 log.error(tree.pos(), 838 "cant.inherit.from.final", t.tsym); 839 } 840 chk.checkNonCyclic(tree.pos(), t); 841 return t; 842 } 843 844 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 845 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 846 id.type = env.info.scope.owner.enclClass().type; 847 id.sym = env.info.scope.owner.enclClass(); 848 return id.type; 849 } 850 851 public void visitClassDef(JCClassDecl tree) { 852 // Local and anonymous classes have not been entered yet, so we need to 853 // do it now. 854 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) { 855 enter.classEnter(tree, env); 856 } else { 857 // If this class declaration is part of a class level annotation, 858 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in 859 // order to simplify later steps and allow for sensible error 860 // messages. 861 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree)) 862 enter.classEnter(tree, env); 863 } 864 865 ClassSymbol c = tree.sym; 866 if (c == null) { 867 // exit in case something drastic went wrong during enter. 868 result = null; 869 } else { 870 // make sure class has been completed: 871 c.complete(); 872 873 // If this class appears as an anonymous class 874 // in a superclass constructor call where 875 // no explicit outer instance is given, 876 // disable implicit outer instance from being passed. 877 // (This would be an illegal access to "this before super"). 878 if (env.info.isSelfCall && 879 env.tree.hasTag(NEWCLASS) && 880 ((JCNewClass) env.tree).encl == null) 881 { 882 c.flags_field |= NOOUTERTHIS; 883 } 884 attribClass(tree.pos(), c); 885 result = tree.type = c.type; 886 } 887 } 888 889 public void visitMethodDef(JCMethodDecl tree) { 890 MethodSymbol m = tree.sym; 891 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 892 893 Lint lint = env.info.lint.augment(m); 894 Lint prevLint = chk.setLint(lint); 895 MethodSymbol prevMethod = chk.setMethod(m); 896 try { 897 deferredLintHandler.flush(tree.pos()); 898 chk.checkDeprecatedAnnotation(tree.pos(), m); 899 900 901 // Create a new environment with local scope 902 // for attributing the method. 903 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 904 localEnv.info.lint = lint; 905 906 attribStats(tree.typarams, localEnv); 907 908 // If we override any other methods, check that we do so properly. 909 // JLS ??? 910 if (m.isStatic()) { 911 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 912 } else { 913 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 914 } 915 chk.checkOverride(env, tree, m); 916 917 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 918 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); 919 } 920 921 // Enter all type parameters into the local method scope. 922 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 923 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 924 925 ClassSymbol owner = env.enclClass.sym; 926 if ((owner.flags() & ANNOTATION) != 0 && 927 tree.params.nonEmpty()) 928 log.error(tree.params.head.pos(), 929 "intf.annotation.members.cant.have.params"); 930 931 // Attribute all value parameters. 932 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 933 attribStat(l.head, localEnv); 934 } 935 936 chk.checkVarargsMethodDecl(localEnv, tree); 937 938 // Check that type parameters are well-formed. 939 chk.validate(tree.typarams, localEnv); 940 941 // Check that result type is well-formed. 942 if (tree.restype != null && !tree.restype.type.hasTag(VOID)) 943 chk.validate(tree.restype, localEnv); 944 945 // Check that receiver type is well-formed. 946 if (tree.recvparam != null) { 947 // Use a new environment to check the receiver parameter. 948 // Otherwise I get "might not have been initialized" errors. 949 // Is there a better way? 950 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env); 951 attribType(tree.recvparam, newEnv); 952 chk.validate(tree.recvparam, newEnv); 953 } 954 955 // annotation method checks 956 if ((owner.flags() & ANNOTATION) != 0) { 957 // annotation method cannot have throws clause 958 if (tree.thrown.nonEmpty()) { 959 log.error(tree.thrown.head.pos(), 960 "throws.not.allowed.in.intf.annotation"); 961 } 962 // annotation method cannot declare type-parameters 963 if (tree.typarams.nonEmpty()) { 964 log.error(tree.typarams.head.pos(), 965 "intf.annotation.members.cant.have.type.params"); 966 } 967 // validate annotation method's return type (could be an annotation type) 968 chk.validateAnnotationType(tree.restype); 969 // ensure that annotation method does not clash with members of Object/Annotation 970 chk.validateAnnotationMethod(tree.pos(), m); 971 } 972 973 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 974 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 975 976 if (tree.body == null) { 977 // Empty bodies are only allowed for 978 // abstract, native, or interface methods, or for methods 979 // in a retrofit signature class. 980 if (tree.defaultValue != null) { 981 if ((owner.flags() & ANNOTATION) == 0) 982 log.error(tree.pos(), 983 "default.allowed.in.intf.annotation.member"); 984 } 985 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 && 986 !relax) 987 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 988 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) { 989 if ((owner.flags() & INTERFACE) != 0) { 990 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 991 } else { 992 log.error(tree.pos(), "abstract.meth.cant.have.body"); 993 } 994 } else if ((tree.mods.flags & NATIVE) != 0) { 995 log.error(tree.pos(), "native.meth.cant.have.body"); 996 } else { 997 // Add an implicit super() call unless an explicit call to 998 // super(...) or this(...) is given 999 // or we are compiling class java.lang.Object. 1000 if (tree.name == names.init && owner.type != syms.objectType) { 1001 JCBlock body = tree.body; 1002 if (body.stats.isEmpty() || 1003 !TreeInfo.isSelfCall(body.stats.head)) { 1004 body.stats = body.stats. 1005 prepend(typeEnter.SuperCall(make.at(body.pos), 1006 List.<Type>nil(), 1007 List.<JCVariableDecl>nil(), 1008 false)); 1009 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 1010 (tree.mods.flags & GENERATEDCONSTR) == 0 && 1011 TreeInfo.isSuperCall(body.stats.head)) { 1012 // enum constructors are not allowed to call super 1013 // directly, so make sure there aren't any super calls 1014 // in enum constructors, except in the compiler 1015 // generated one. 1016 log.error(tree.body.stats.head.pos(), 1017 "call.to.super.not.allowed.in.enum.ctor", 1018 env.enclClass.sym); 1019 } 1020 } 1021 1022 // Attribute all type annotations in the body 1023 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null); 1024 annotate.flush(); 1025 1026 // Attribute method body. 1027 attribStat(tree.body, localEnv); 1028 } 1029 1030 localEnv.info.scope.leave(); 1031 result = tree.type = m.type; 1032 } finally { 1033 chk.setLint(prevLint); 1034 chk.setMethod(prevMethod); 1035 } 1036 } 1037 1038 public void visitVarDef(JCVariableDecl tree) { 1039 // Local variables have not been entered yet, so we need to do it now: 1040 if (env.info.scope.owner.kind == MTH) { 1041 if (tree.sym != null) { 1042 // parameters have already been entered 1043 env.info.scope.enter(tree.sym); 1044 } else { 1045 try { 1046 annotate.blockAnnotations(); 1047 memberEnter.memberEnter(tree, env); 1048 } finally { 1049 annotate.unblockAnnotations(); 1050 } 1051 } 1052 } else { 1053 if (tree.init != null) { 1054 // Field initializer expression need to be entered. 1055 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos()); 1056 annotate.flush(); 1057 } 1058 } 1059 1060 VarSymbol v = tree.sym; 1061 Lint lint = env.info.lint.augment(v); 1062 Lint prevLint = chk.setLint(lint); 1063 1064 // Check that the variable's declared type is well-formed. 1065 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) && 1066 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT && 1067 (tree.sym.flags() & PARAMETER) != 0; 1068 chk.validate(tree.vartype, env, !isImplicitLambdaParameter); 1069 1070 try { 1071 v.getConstValue(); // ensure compile-time constant initializer is evaluated 1072 deferredLintHandler.flush(tree.pos()); 1073 chk.checkDeprecatedAnnotation(tree.pos(), v); 1074 1075 if (tree.init != null) { 1076 if ((v.flags_field & FINAL) == 0 || 1077 !memberEnter.needsLazyConstValue(tree.init)) { 1078 // Not a compile-time constant 1079 // Attribute initializer in a new environment 1080 // with the declared variable as owner. 1081 // Check that initializer conforms to variable's declared type. 1082 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1083 initEnv.info.lint = lint; 1084 // In order to catch self-references, we set the variable's 1085 // declaration position to maximal possible value, effectively 1086 // marking the variable as undefined. 1087 initEnv.info.enclVar = v; 1088 attribExpr(tree.init, initEnv, v.type); 1089 } 1090 } 1091 result = tree.type = v.type; 1092 } 1093 finally { 1094 chk.setLint(prevLint); 1095 } 1096 } 1097 1098 public void visitSkip(JCSkip tree) { 1099 result = null; 1100 } 1101 1102 public void visitBlock(JCBlock tree) { 1103 if (env.info.scope.owner.kind == TYP) { 1104 // Block is a static or instance initializer; 1105 // let the owner of the environment be a freshly 1106 // created BLOCK-method. 1107 Symbol fakeOwner = 1108 new MethodSymbol(tree.flags | BLOCK | 1109 env.info.scope.owner.flags() & STRICTFP, names.empty, null, 1110 env.info.scope.owner); 1111 final Env<AttrContext> localEnv = 1112 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner))); 1113 1114 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 1115 // Attribute all type annotations in the block 1116 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null); 1117 annotate.flush(); 1118 attribStats(tree.stats, localEnv); 1119 1120 { 1121 // Store init and clinit type annotations with the ClassSymbol 1122 // to allow output in Gen.normalizeDefs. 1123 ClassSymbol cs = (ClassSymbol)env.info.scope.owner; 1124 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes(); 1125 if ((tree.flags & STATIC) != 0) { 1126 cs.appendClassInitTypeAttributes(tas); 1127 } else { 1128 cs.appendInitTypeAttributes(tas); 1129 } 1130 } 1131 } else { 1132 // Create a new local environment with a local scope. 1133 Env<AttrContext> localEnv = 1134 env.dup(tree, env.info.dup(env.info.scope.dup())); 1135 try { 1136 attribStats(tree.stats, localEnv); 1137 } finally { 1138 localEnv.info.scope.leave(); 1139 } 1140 } 1141 result = null; 1142 } 1143 1144 public void visitDoLoop(JCDoWhileLoop tree) { 1145 attribStat(tree.body, env.dup(tree)); 1146 attribExpr(tree.cond, env, syms.booleanType); 1147 result = null; 1148 } 1149 1150 public void visitWhileLoop(JCWhileLoop tree) { 1151 attribExpr(tree.cond, env, syms.booleanType); 1152 attribStat(tree.body, env.dup(tree)); 1153 result = null; 1154 } 1155 1156 public void visitForLoop(JCForLoop tree) { 1157 Env<AttrContext> loopEnv = 1158 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1159 try { 1160 attribStats(tree.init, loopEnv); 1161 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 1162 loopEnv.tree = tree; // before, we were not in loop! 1163 attribStats(tree.step, loopEnv); 1164 attribStat(tree.body, loopEnv); 1165 result = null; 1166 } 1167 finally { 1168 loopEnv.info.scope.leave(); 1169 } 1170 } 1171 1172 public void visitForeachLoop(JCEnhancedForLoop tree) { 1173 Env<AttrContext> loopEnv = 1174 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1175 try { 1176 //the Formal Parameter of a for-each loop is not in the scope when 1177 //attributing the for-each expression; we mimick this by attributing 1178 //the for-each expression first (against original scope). 1179 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); 1180 attribStat(tree.var, loopEnv); 1181 chk.checkNonVoid(tree.pos(), exprType); 1182 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1183 if (elemtype == null) { 1184 // or perhaps expr implements Iterable<T>? 1185 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1186 if (base == null) { 1187 log.error(tree.expr.pos(), 1188 "foreach.not.applicable.to.type", 1189 exprType, 1190 diags.fragment("type.req.array.or.iterable")); 1191 elemtype = types.createErrorType(exprType); 1192 } else { 1193 List<Type> iterableParams = base.allparams(); 1194 elemtype = iterableParams.isEmpty() 1195 ? syms.objectType 1196 : types.wildUpperBound(iterableParams.head); 1197 } 1198 } 1199 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1200 loopEnv.tree = tree; // before, we were not in loop! 1201 attribStat(tree.body, loopEnv); 1202 result = null; 1203 } 1204 finally { 1205 loopEnv.info.scope.leave(); 1206 } 1207 } 1208 1209 public void visitLabelled(JCLabeledStatement tree) { 1210 // Check that label is not used in an enclosing statement 1211 Env<AttrContext> env1 = env; 1212 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1213 if (env1.tree.hasTag(LABELLED) && 1214 ((JCLabeledStatement) env1.tree).label == tree.label) { 1215 log.error(tree.pos(), "label.already.in.use", 1216 tree.label); 1217 break; 1218 } 1219 env1 = env1.next; 1220 } 1221 1222 attribStat(tree.body, env.dup(tree)); 1223 result = null; 1224 } 1225 1226 public void visitSwitch(JCSwitch tree) { 1227 Type seltype = attribExpr(tree.selector, env); 1228 1229 Env<AttrContext> switchEnv = 1230 env.dup(tree, env.info.dup(env.info.scope.dup())); 1231 1232 try { 1233 1234 boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0; 1235 boolean stringSwitch = false; 1236 if (types.isSameType(seltype, syms.stringType)) { 1237 if (allowStringsInSwitch) { 1238 stringSwitch = true; 1239 } else { 1240 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 1241 } 1242 } 1243 if (!enumSwitch && !stringSwitch) 1244 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 1245 1246 // Attribute all cases and 1247 // check that there are no duplicate case labels or default clauses. 1248 Set<Object> labels = new HashSet<>(); // The set of case labels. 1249 boolean hasDefault = false; // Is there a default label? 1250 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 1251 JCCase c = l.head; 1252 if (c.pat != null) { 1253 if (enumSwitch) { 1254 Symbol sym = enumConstant(c.pat, seltype); 1255 if (sym == null) { 1256 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); 1257 } else if (!labels.add(sym)) { 1258 log.error(c.pos(), "duplicate.case.label"); 1259 } 1260 } else { 1261 Type pattype = attribExpr(c.pat, switchEnv, seltype); 1262 if (!pattype.hasTag(ERROR)) { 1263 if (pattype.constValue() == null) { 1264 log.error(c.pat.pos(), 1265 (stringSwitch ? "string.const.req" : "const.expr.req")); 1266 } else if (!labels.add(pattype.constValue())) { 1267 log.error(c.pos(), "duplicate.case.label"); 1268 } 1269 } 1270 } 1271 } else if (hasDefault) { 1272 log.error(c.pos(), "duplicate.default.label"); 1273 } else { 1274 hasDefault = true; 1275 } 1276 Env<AttrContext> caseEnv = 1277 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 1278 try { 1279 attribStats(c.stats, caseEnv); 1280 } finally { 1281 caseEnv.info.scope.leave(); 1282 addVars(c.stats, switchEnv.info.scope); 1283 } 1284 } 1285 1286 result = null; 1287 } 1288 finally { 1289 switchEnv.info.scope.leave(); 1290 } 1291 } 1292 // where 1293 /** Add any variables defined in stats to the switch scope. */ 1294 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) { 1295 for (;stats.nonEmpty(); stats = stats.tail) { 1296 JCTree stat = stats.head; 1297 if (stat.hasTag(VARDEF)) 1298 switchScope.enter(((JCVariableDecl) stat).sym); 1299 } 1300 } 1301 // where 1302 /** Return the selected enumeration constant symbol, or null. */ 1303 private Symbol enumConstant(JCTree tree, Type enumType) { 1304 if (tree.hasTag(IDENT)) { 1305 JCIdent ident = (JCIdent)tree; 1306 Name name = ident.name; 1307 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) { 1308 if (sym.kind == VAR) { 1309 Symbol s = ident.sym = sym; 1310 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1311 ident.type = s.type; 1312 return ((s.flags_field & Flags.ENUM) == 0) 1313 ? null : s; 1314 } 1315 } 1316 } 1317 return null; 1318 } 1319 1320 public void visitSynchronized(JCSynchronized tree) { 1321 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 1322 attribStat(tree.body, env); 1323 result = null; 1324 } 1325 1326 public void visitTry(JCTry tree) { 1327 // Create a new local environment with a local 1328 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 1329 try { 1330 boolean isTryWithResource = tree.resources.nonEmpty(); 1331 // Create a nested environment for attributing the try block if needed 1332 Env<AttrContext> tryEnv = isTryWithResource ? 1333 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : 1334 localEnv; 1335 try { 1336 // Attribute resource declarations 1337 for (JCTree resource : tree.resources) { 1338 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { 1339 @Override 1340 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1341 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details)); 1342 } 1343 }; 1344 ResultInfo twrResult = 1345 new ResultInfo(KindSelector.VAR, 1346 syms.autoCloseableType, 1347 twrContext); 1348 if (resource.hasTag(VARDEF)) { 1349 attribStat(resource, tryEnv); 1350 twrResult.check(resource, resource.type); 1351 1352 //check that resource type cannot throw InterruptedException 1353 checkAutoCloseable(resource.pos(), localEnv, resource.type); 1354 1355 VarSymbol var = ((JCVariableDecl) resource).sym; 1356 var.setData(ElementKind.RESOURCE_VARIABLE); 1357 } else { 1358 attribTree(resource, tryEnv, twrResult); 1359 } 1360 } 1361 // Attribute body 1362 attribStat(tree.body, tryEnv); 1363 } finally { 1364 if (isTryWithResource) 1365 tryEnv.info.scope.leave(); 1366 } 1367 1368 // Attribute catch clauses 1369 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 1370 JCCatch c = l.head; 1371 Env<AttrContext> catchEnv = 1372 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); 1373 try { 1374 Type ctype = attribStat(c.param, catchEnv); 1375 if (TreeInfo.isMultiCatch(c)) { 1376 //multi-catch parameter is implicitly marked as final 1377 c.param.sym.flags_field |= FINAL | UNION; 1378 } 1379 if (c.param.sym.kind == VAR) { 1380 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1381 } 1382 chk.checkType(c.param.vartype.pos(), 1383 chk.checkClassType(c.param.vartype.pos(), ctype), 1384 syms.throwableType); 1385 attribStat(c.body, catchEnv); 1386 } finally { 1387 catchEnv.info.scope.leave(); 1388 } 1389 } 1390 1391 // Attribute finalizer 1392 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); 1393 result = null; 1394 } 1395 finally { 1396 localEnv.info.scope.leave(); 1397 } 1398 } 1399 1400 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) { 1401 if (!resource.isErroneous() && 1402 types.asSuper(resource, syms.autoCloseableType.tsym) != null && 1403 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself 1404 Symbol close = syms.noSymbol; 1405 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); 1406 try { 1407 close = rs.resolveQualifiedMethod(pos, 1408 env, 1409 resource, 1410 names.close, 1411 List.<Type>nil(), 1412 List.<Type>nil()); 1413 } 1414 finally { 1415 log.popDiagnosticHandler(discardHandler); 1416 } 1417 if (close.kind == MTH && 1418 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && 1419 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && 1420 env.info.lint.isEnabled(LintCategory.TRY)) { 1421 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource); 1422 } 1423 } 1424 } 1425 1426 public void visitConditional(JCConditional tree) { 1427 Type condtype = attribExpr(tree.cond, env, syms.booleanType); 1428 1429 tree.polyKind = (!allowPoly || 1430 pt().hasTag(NONE) && pt() != Type.recoveryType || 1431 isBooleanOrNumeric(env, tree)) ? 1432 PolyKind.STANDALONE : PolyKind.POLY; 1433 1434 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { 1435 //cannot get here (i.e. it means we are returning from void method - which is already an error) 1436 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void")); 1437 result = tree.type = types.createErrorType(resultInfo.pt); 1438 return; 1439 } 1440 1441 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? 1442 unknownExprInfo : 1443 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) { 1444 //this will use enclosing check context to check compatibility of 1445 //subexpression against target type; if we are in a method check context, 1446 //depending on whether boxing is allowed, we could have incompatibilities 1447 @Override 1448 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1449 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details)); 1450 } 1451 }); 1452 1453 Type truetype = attribTree(tree.truepart, env, condInfo); 1454 Type falsetype = attribTree(tree.falsepart, env, condInfo); 1455 1456 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt(); 1457 if (condtype.constValue() != null && 1458 truetype.constValue() != null && 1459 falsetype.constValue() != null && 1460 !owntype.hasTag(NONE)) { 1461 //constant folding 1462 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); 1463 } 1464 result = check(tree, owntype, KindSelector.VAL, resultInfo); 1465 } 1466 //where 1467 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) { 1468 switch (tree.getTag()) { 1469 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || 1470 ((JCLiteral)tree).typetag == BOOLEAN || 1471 ((JCLiteral)tree).typetag == BOT; 1472 case LAMBDA: case REFERENCE: return false; 1473 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); 1474 case CONDEXPR: 1475 JCConditional condTree = (JCConditional)tree; 1476 return isBooleanOrNumeric(env, condTree.truepart) && 1477 isBooleanOrNumeric(env, condTree.falsepart); 1478 case APPLY: 1479 JCMethodInvocation speculativeMethodTree = 1480 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo); 1481 Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth); 1482 Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ? 1483 env.enclClass.type : 1484 ((JCFieldAccess)speculativeMethodTree.meth).selected.type; 1485 Type owntype = types.memberType(receiverType, msym).getReturnType(); 1486 return primitiveOrBoxed(owntype); 1487 case NEWCLASS: 1488 JCExpression className = 1489 removeClassParams.translate(((JCNewClass)tree).clazz); 1490 JCExpression speculativeNewClassTree = 1491 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo); 1492 return primitiveOrBoxed(speculativeNewClassTree.type); 1493 default: 1494 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type; 1495 return primitiveOrBoxed(speculativeType); 1496 } 1497 } 1498 //where 1499 boolean primitiveOrBoxed(Type t) { 1500 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive()); 1501 } 1502 1503 TreeTranslator removeClassParams = new TreeTranslator() { 1504 @Override 1505 public void visitTypeApply(JCTypeApply tree) { 1506 result = translate(tree.clazz); 1507 } 1508 }; 1509 1510 /** Compute the type of a conditional expression, after 1511 * checking that it exists. See JLS 15.25. Does not take into 1512 * account the special case where condition and both arms 1513 * are constants. 1514 * 1515 * @param pos The source position to be used for error 1516 * diagnostics. 1517 * @param thentype The type of the expression's then-part. 1518 * @param elsetype The type of the expression's else-part. 1519 */ 1520 Type condType(DiagnosticPosition pos, 1521 Type thentype, Type elsetype) { 1522 // If same type, that is the result 1523 if (types.isSameType(thentype, elsetype)) 1524 return thentype.baseType(); 1525 1526 Type thenUnboxed = (thentype.isPrimitive()) 1527 ? thentype : types.unboxedType(thentype); 1528 Type elseUnboxed = (elsetype.isPrimitive()) 1529 ? elsetype : types.unboxedType(elsetype); 1530 1531 // Otherwise, if both arms can be converted to a numeric 1532 // type, return the least numeric type that fits both arms 1533 // (i.e. return larger of the two, or return int if one 1534 // arm is short, the other is char). 1535 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1536 // If one arm has an integer subrange type (i.e., byte, 1537 // short, or char), and the other is an integer constant 1538 // that fits into the subrange, return the subrange type. 1539 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && 1540 elseUnboxed.hasTag(INT) && 1541 types.isAssignable(elseUnboxed, thenUnboxed)) { 1542 return thenUnboxed.baseType(); 1543 } 1544 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && 1545 thenUnboxed.hasTag(INT) && 1546 types.isAssignable(thenUnboxed, elseUnboxed)) { 1547 return elseUnboxed.baseType(); 1548 } 1549 1550 for (TypeTag tag : primitiveTags) { 1551 Type candidate = syms.typeOfTag[tag.ordinal()]; 1552 if (types.isSubtype(thenUnboxed, candidate) && 1553 types.isSubtype(elseUnboxed, candidate)) { 1554 return candidate; 1555 } 1556 } 1557 } 1558 1559 // Those were all the cases that could result in a primitive 1560 if (thentype.isPrimitive()) 1561 thentype = types.boxedClass(thentype).type; 1562 if (elsetype.isPrimitive()) 1563 elsetype = types.boxedClass(elsetype).type; 1564 1565 if (types.isSubtype(thentype, elsetype)) 1566 return elsetype.baseType(); 1567 if (types.isSubtype(elsetype, thentype)) 1568 return thentype.baseType(); 1569 1570 if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) { 1571 log.error(pos, "neither.conditional.subtype", 1572 thentype, elsetype); 1573 return thentype.baseType(); 1574 } 1575 1576 // both are known to be reference types. The result is 1577 // lub(thentype,elsetype). This cannot fail, as it will 1578 // always be possible to infer "Object" if nothing better. 1579 return types.lub(thentype.baseType(), elsetype.baseType()); 1580 } 1581 1582 final static TypeTag[] primitiveTags = new TypeTag[]{ 1583 BYTE, 1584 CHAR, 1585 SHORT, 1586 INT, 1587 LONG, 1588 FLOAT, 1589 DOUBLE, 1590 BOOLEAN, 1591 }; 1592 1593 public void visitIf(JCIf tree) { 1594 attribExpr(tree.cond, env, syms.booleanType); 1595 attribStat(tree.thenpart, env); 1596 if (tree.elsepart != null) 1597 attribStat(tree.elsepart, env); 1598 chk.checkEmptyIf(tree); 1599 result = null; 1600 } 1601 1602 public void visitExec(JCExpressionStatement tree) { 1603 //a fresh environment is required for 292 inference to work properly --- 1604 //see Infer.instantiatePolymorphicSignatureInstance() 1605 Env<AttrContext> localEnv = env.dup(tree); 1606 attribExpr(tree.expr, localEnv); 1607 result = null; 1608 } 1609 1610 public void visitBreak(JCBreak tree) { 1611 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1612 result = null; 1613 } 1614 1615 public void visitContinue(JCContinue tree) { 1616 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1617 result = null; 1618 } 1619 //where 1620 /** Return the target of a break or continue statement, if it exists, 1621 * report an error if not. 1622 * Note: The target of a labelled break or continue is the 1623 * (non-labelled) statement tree referred to by the label, 1624 * not the tree representing the labelled statement itself. 1625 * 1626 * @param pos The position to be used for error diagnostics 1627 * @param tag The tag of the jump statement. This is either 1628 * Tree.BREAK or Tree.CONTINUE. 1629 * @param label The label of the jump statement, or null if no 1630 * label is given. 1631 * @param env The environment current at the jump statement. 1632 */ 1633 private JCTree findJumpTarget(DiagnosticPosition pos, 1634 JCTree.Tag tag, 1635 Name label, 1636 Env<AttrContext> env) { 1637 // Search environments outwards from the point of jump. 1638 Env<AttrContext> env1 = env; 1639 LOOP: 1640 while (env1 != null) { 1641 switch (env1.tree.getTag()) { 1642 case LABELLED: 1643 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1644 if (label == labelled.label) { 1645 // If jump is a continue, check that target is a loop. 1646 if (tag == CONTINUE) { 1647 if (!labelled.body.hasTag(DOLOOP) && 1648 !labelled.body.hasTag(WHILELOOP) && 1649 !labelled.body.hasTag(FORLOOP) && 1650 !labelled.body.hasTag(FOREACHLOOP)) 1651 log.error(pos, "not.loop.label", label); 1652 // Found labelled statement target, now go inwards 1653 // to next non-labelled tree. 1654 return TreeInfo.referencedStatement(labelled); 1655 } else { 1656 return labelled; 1657 } 1658 } 1659 break; 1660 case DOLOOP: 1661 case WHILELOOP: 1662 case FORLOOP: 1663 case FOREACHLOOP: 1664 if (label == null) return env1.tree; 1665 break; 1666 case SWITCH: 1667 if (label == null && tag == BREAK) return env1.tree; 1668 break; 1669 case LAMBDA: 1670 case METHODDEF: 1671 case CLASSDEF: 1672 break LOOP; 1673 default: 1674 } 1675 env1 = env1.next; 1676 } 1677 if (label != null) 1678 log.error(pos, "undef.label", label); 1679 else if (tag == CONTINUE) 1680 log.error(pos, "cont.outside.loop"); 1681 else 1682 log.error(pos, "break.outside.switch.loop"); 1683 return null; 1684 } 1685 1686 public void visitReturn(JCReturn tree) { 1687 // Check that there is an enclosing method which is 1688 // nested within than the enclosing class. 1689 if (env.info.returnResult == null) { 1690 log.error(tree.pos(), "ret.outside.meth"); 1691 } else { 1692 // Attribute return expression, if it exists, and check that 1693 // it conforms to result type of enclosing method. 1694 if (tree.expr != null) { 1695 if (env.info.returnResult.pt.hasTag(VOID)) { 1696 env.info.returnResult.checkContext.report(tree.expr.pos(), 1697 diags.fragment("unexpected.ret.val")); 1698 } 1699 attribTree(tree.expr, env, env.info.returnResult); 1700 } else if (!env.info.returnResult.pt.hasTag(VOID) && 1701 !env.info.returnResult.pt.hasTag(NONE)) { 1702 env.info.returnResult.checkContext.report(tree.pos(), 1703 diags.fragment("missing.ret.val")); 1704 } 1705 } 1706 result = null; 1707 } 1708 1709 public void visitThrow(JCThrow tree) { 1710 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType); 1711 if (allowPoly) { 1712 chk.checkType(tree, owntype, syms.throwableType); 1713 } 1714 result = null; 1715 } 1716 1717 public void visitAssert(JCAssert tree) { 1718 attribExpr(tree.cond, env, syms.booleanType); 1719 if (tree.detail != null) { 1720 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1721 } 1722 result = null; 1723 } 1724 1725 /** Visitor method for method invocations. 1726 * NOTE: The method part of an application will have in its type field 1727 * the return type of the method, not the method's type itself! 1728 */ 1729 public void visitApply(JCMethodInvocation tree) { 1730 // The local environment of a method application is 1731 // a new environment nested in the current one. 1732 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1733 1734 // The types of the actual method arguments. 1735 List<Type> argtypes; 1736 1737 // The types of the actual method type arguments. 1738 List<Type> typeargtypes = null; 1739 1740 Name methName = TreeInfo.name(tree.meth); 1741 1742 boolean isConstructorCall = 1743 methName == names._this || methName == names._super; 1744 1745 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 1746 if (isConstructorCall) { 1747 // We are seeing a ...this(...) or ...super(...) call. 1748 // Check that this is the first statement in a constructor. 1749 if (checkFirstConstructorStat(tree, env)) { 1750 1751 // Record the fact 1752 // that this is a constructor call (using isSelfCall). 1753 localEnv.info.isSelfCall = true; 1754 1755 // Attribute arguments, yielding list of argument types. 1756 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf); 1757 argtypes = argtypesBuf.toList(); 1758 typeargtypes = attribTypes(tree.typeargs, localEnv); 1759 1760 // Variable `site' points to the class in which the called 1761 // constructor is defined. 1762 Type site = env.enclClass.sym.type; 1763 if (methName == names._super) { 1764 if (site == syms.objectType) { 1765 log.error(tree.meth.pos(), "no.superclass", site); 1766 site = types.createErrorType(syms.objectType); 1767 } else { 1768 site = types.supertype(site); 1769 } 1770 } 1771 1772 if (site.hasTag(CLASS)) { 1773 Type encl = site.getEnclosingType(); 1774 while (encl != null && encl.hasTag(TYPEVAR)) 1775 encl = encl.getUpperBound(); 1776 if (encl.hasTag(CLASS)) { 1777 // we are calling a nested class 1778 1779 if (tree.meth.hasTag(SELECT)) { 1780 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1781 1782 // We are seeing a prefixed call, of the form 1783 // <expr>.super(...). 1784 // Check that the prefix expression conforms 1785 // to the outer instance type of the class. 1786 chk.checkRefType(qualifier.pos(), 1787 attribExpr(qualifier, localEnv, 1788 encl)); 1789 } else if (methName == names._super) { 1790 // qualifier omitted; check for existence 1791 // of an appropriate implicit qualifier. 1792 rs.resolveImplicitThis(tree.meth.pos(), 1793 localEnv, site, true); 1794 } 1795 } else if (tree.meth.hasTag(SELECT)) { 1796 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1797 site.tsym); 1798 } 1799 1800 // if we're calling a java.lang.Enum constructor, 1801 // prefix the implicit String and int parameters 1802 if (site.tsym == syms.enumSym) 1803 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1804 1805 // Resolve the called constructor under the assumption 1806 // that we are referring to a superclass instance of the 1807 // current instance (JLS ???). 1808 boolean selectSuperPrev = localEnv.info.selectSuper; 1809 localEnv.info.selectSuper = true; 1810 localEnv.info.pendingResolutionPhase = null; 1811 Symbol sym = rs.resolveConstructor( 1812 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1813 localEnv.info.selectSuper = selectSuperPrev; 1814 1815 // Set method symbol to resolved constructor... 1816 TreeInfo.setSymbol(tree.meth, sym); 1817 1818 // ...and check that it is legal in the current context. 1819 // (this will also set the tree's type) 1820 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1821 checkId(tree.meth, site, sym, localEnv, 1822 new ResultInfo(kind, mpt)); 1823 } 1824 // Otherwise, `site' is an error type and we do nothing 1825 } 1826 result = tree.type = syms.voidType; 1827 } else { 1828 // Otherwise, we are seeing a regular method call. 1829 // Attribute the arguments, yielding list of argument types, ... 1830 KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 1831 argtypes = argtypesBuf.toList(); 1832 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1833 1834 // ... and attribute the method using as a prototype a methodtype 1835 // whose formal argument types is exactly the list of actual 1836 // arguments (this will also set the method symbol). 1837 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1838 localEnv.info.pendingResolutionPhase = null; 1839 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext)); 1840 1841 // Compute the result type. 1842 Type restype = mtype.getReturnType(); 1843 if (restype.hasTag(WILDCARD)) 1844 throw new AssertionError(mtype); 1845 1846 Type qualifier = (tree.meth.hasTag(SELECT)) 1847 ? ((JCFieldAccess) tree.meth).selected.type 1848 : env.enclClass.sym.type; 1849 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype); 1850 1851 chk.checkRefTypes(tree.typeargs, typeargtypes); 1852 1853 // Check that value of resulting type is admissible in the 1854 // current context. Also, capture the return type 1855 result = check(tree, capture(restype), KindSelector.VAL, resultInfo); 1856 } 1857 chk.validate(tree.typeargs, localEnv); 1858 } 1859 //where 1860 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) { 1861 if (methodName == names.clone && types.isArray(qualifierType)) { 1862 // as a special case, array.clone() has a result that is 1863 // the same as static type of the array being cloned 1864 return qualifierType; 1865 } else if (methodName == names.getClass && argtypes.isEmpty()) { 1866 // as a special case, x.getClass() has type Class<? extends |X|> 1867 return new ClassType(restype.getEnclosingType(), 1868 List.<Type>of(new WildcardType(types.erasure(qualifierType), 1869 BoundKind.EXTENDS, 1870 syms.boundClass)), 1871 restype.tsym, 1872 restype.getMetadata()); 1873 } else { 1874 return restype; 1875 } 1876 } 1877 1878 /** Check that given application node appears as first statement 1879 * in a constructor call. 1880 * @param tree The application node 1881 * @param env The environment current at the application. 1882 */ 1883 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1884 JCMethodDecl enclMethod = env.enclMethod; 1885 if (enclMethod != null && enclMethod.name == names.init) { 1886 JCBlock body = enclMethod.body; 1887 if (body.stats.head.hasTag(EXEC) && 1888 ((JCExpressionStatement) body.stats.head).expr == tree) 1889 return true; 1890 } 1891 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1892 TreeInfo.name(tree.meth)); 1893 return false; 1894 } 1895 1896 /** Obtain a method type with given argument types. 1897 */ 1898 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) { 1899 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass); 1900 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1901 } 1902 1903 public void visitNewClass(final JCNewClass tree) { 1904 Type owntype = types.createErrorType(tree.type); 1905 1906 // The local environment of a class creation is 1907 // a new environment nested in the current one. 1908 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1909 1910 // The anonymous inner class definition of the new expression, 1911 // if one is defined by it. 1912 JCClassDecl cdef = tree.def; 1913 1914 // If enclosing class is given, attribute it, and 1915 // complete class name to be fully qualified 1916 JCExpression clazz = tree.clazz; // Class field following new 1917 JCExpression clazzid; // Identifier in class field 1918 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid 1919 annoclazzid = null; 1920 1921 if (clazz.hasTag(TYPEAPPLY)) { 1922 clazzid = ((JCTypeApply) clazz).clazz; 1923 if (clazzid.hasTag(ANNOTATED_TYPE)) { 1924 annoclazzid = (JCAnnotatedType) clazzid; 1925 clazzid = annoclazzid.underlyingType; 1926 } 1927 } else { 1928 if (clazz.hasTag(ANNOTATED_TYPE)) { 1929 annoclazzid = (JCAnnotatedType) clazz; 1930 clazzid = annoclazzid.underlyingType; 1931 } else { 1932 clazzid = clazz; 1933 } 1934 } 1935 1936 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1937 1938 if (tree.encl != null) { 1939 // We are seeing a qualified new, of the form 1940 // <expr>.new C <...> (...) ... 1941 // In this case, we let clazz stand for the name of the 1942 // allocated class C prefixed with the type of the qualifier 1943 // expression, so that we can 1944 // resolve it with standard techniques later. I.e., if 1945 // <expr> has type T, then <expr>.new C <...> (...) 1946 // yields a clazz T.C. 1947 Type encltype = chk.checkRefType(tree.encl.pos(), 1948 attribExpr(tree.encl, env)); 1949 // TODO 308: in <expr>.new C, do we also want to add the type annotations 1950 // from expr to the combined type, or not? Yes, do this. 1951 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 1952 ((JCIdent) clazzid).name); 1953 1954 EndPosTable endPosTable = this.env.toplevel.endPositions; 1955 endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable)); 1956 if (clazz.hasTag(ANNOTATED_TYPE)) { 1957 JCAnnotatedType annoType = (JCAnnotatedType) clazz; 1958 List<JCAnnotation> annos = annoType.annotations; 1959 1960 if (annoType.underlyingType.hasTag(TYPEAPPLY)) { 1961 clazzid1 = make.at(tree.pos). 1962 TypeApply(clazzid1, 1963 ((JCTypeApply) clazz).arguments); 1964 } 1965 1966 clazzid1 = make.at(tree.pos). 1967 AnnotatedType(annos, clazzid1); 1968 } else if (clazz.hasTag(TYPEAPPLY)) { 1969 clazzid1 = make.at(tree.pos). 1970 TypeApply(clazzid1, 1971 ((JCTypeApply) clazz).arguments); 1972 } 1973 1974 clazz = clazzid1; 1975 } 1976 1977 // Attribute clazz expression and store 1978 // symbol + type back into the attributed tree. 1979 Type clazztype; 1980 1981 try { 1982 env.info.isNewClass = true; 1983 clazztype = TreeInfo.isEnumInit(env.tree) ? 1984 attribIdentAsEnumType(env, (JCIdent)clazz) : 1985 attribType(clazz, env); 1986 } finally { 1987 env.info.isNewClass = false; 1988 } 1989 1990 clazztype = chk.checkDiamond(tree, clazztype); 1991 chk.validate(clazz, localEnv); 1992 if (tree.encl != null) { 1993 // We have to work in this case to store 1994 // symbol + type back into the attributed tree. 1995 tree.clazz.type = clazztype; 1996 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 1997 clazzid.type = ((JCIdent) clazzid).sym.type; 1998 if (annoclazzid != null) { 1999 annoclazzid.type = clazzid.type; 2000 } 2001 if (!clazztype.isErroneous()) { 2002 if (cdef != null && clazztype.tsym.isInterface()) { 2003 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 2004 } else if (clazztype.tsym.isStatic()) { 2005 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 2006 } 2007 } 2008 } else if (!clazztype.tsym.isInterface() && 2009 clazztype.getEnclosingType().hasTag(CLASS)) { 2010 // Check for the existence of an apropos outer instance 2011 rs.resolveImplicitThis(tree.pos(), env, clazztype); 2012 } 2013 2014 // Attribute constructor arguments. 2015 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 2016 final KindSelector pkind = 2017 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 2018 List<Type> argtypes = argtypesBuf.toList(); 2019 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 2020 2021 // If we have made no mistakes in the class type... 2022 if (clazztype.hasTag(CLASS)) { 2023 // Enums may not be instantiated except implicitly 2024 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 && 2025 (!env.tree.hasTag(VARDEF) || 2026 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 || 2027 ((JCVariableDecl) env.tree).init != tree)) 2028 log.error(tree.pos(), "enum.cant.be.instantiated"); 2029 2030 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) && 2031 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2032 boolean skipNonDiamondPath = false; 2033 // Check that class is not abstract 2034 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy 2035 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 2036 log.error(tree.pos(), "abstract.cant.be.instantiated", 2037 clazztype.tsym); 2038 skipNonDiamondPath = true; 2039 } else if (cdef != null && clazztype.tsym.isInterface()) { 2040 // Check that no constructor arguments are given to 2041 // anonymous classes implementing an interface 2042 if (!argtypes.isEmpty()) 2043 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 2044 2045 if (!typeargtypes.isEmpty()) 2046 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 2047 2048 // Error recovery: pretend no arguments were supplied. 2049 argtypes = List.nil(); 2050 typeargtypes = List.nil(); 2051 skipNonDiamondPath = true; 2052 } 2053 if (TreeInfo.isDiamond(tree)) { 2054 ClassType site = new ClassType(clazztype.getEnclosingType(), 2055 clazztype.tsym.type.getTypeArguments(), 2056 clazztype.tsym, 2057 clazztype.getMetadata()); 2058 2059 Env<AttrContext> diamondEnv = localEnv.dup(tree); 2060 diamondEnv.info.selectSuper = cdef != null; 2061 diamondEnv.info.pendingResolutionPhase = null; 2062 2063 //if the type of the instance creation expression is a class type 2064 //apply method resolution inference (JLS 15.12.2.7). The return type 2065 //of the resolved constructor will be a partially instantiated type 2066 Symbol constructor = rs.resolveDiamond(tree.pos(), 2067 diamondEnv, 2068 site, 2069 argtypes, 2070 typeargtypes); 2071 tree.constructor = constructor.baseSymbol(); 2072 2073 final TypeSymbol csym = clazztype.tsym; 2074 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) { 2075 @Override 2076 public void report(DiagnosticPosition _unused, JCDiagnostic details) { 2077 enclosingContext.report(tree.clazz, 2078 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details)); 2079 } 2080 }, CheckMode.NO_TREE_UPDATE); 2081 Type constructorType = tree.constructorType = types.createErrorType(clazztype); 2082 constructorType = checkId(tree, site, 2083 constructor, 2084 diamondEnv, 2085 diamondResult); 2086 2087 tree.clazz.type = types.createErrorType(clazztype); 2088 if (!constructorType.isErroneous()) { 2089 tree.clazz.type = clazz.type = constructorType.getReturnType(); 2090 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); 2091 } 2092 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); 2093 } 2094 2095 // Resolve the called constructor under the assumption 2096 // that we are referring to a superclass instance of the 2097 // current instance (JLS ???). 2098 else if (!skipNonDiamondPath) { 2099 //the following code alters some of the fields in the current 2100 //AttrContext - hence, the current context must be dup'ed in 2101 //order to avoid downstream failures 2102 Env<AttrContext> rsEnv = localEnv.dup(tree); 2103 rsEnv.info.selectSuper = cdef != null; 2104 rsEnv.info.pendingResolutionPhase = null; 2105 tree.constructor = rs.resolveConstructor( 2106 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); 2107 if (cdef == null) { //do not check twice! 2108 tree.constructorType = checkId(tree, 2109 clazztype, 2110 tree.constructor, 2111 rsEnv, 2112 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 2113 if (rsEnv.info.lastResolveVarargs()) 2114 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); 2115 } 2116 } 2117 2118 if (cdef != null) { 2119 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind); 2120 return; 2121 } 2122 2123 if (tree.constructor != null && tree.constructor.kind == MTH) 2124 owntype = clazztype; 2125 } 2126 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2127 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2128 if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) { 2129 //we need to wait for inference to finish and then replace inference vars in the constructor type 2130 inferenceContext.addFreeTypeListener(List.of(tree.constructorType), 2131 instantiatedContext -> { 2132 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2133 }); 2134 } 2135 chk.validate(tree.typeargs, localEnv); 2136 } 2137 2138 // where 2139 private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype, 2140 JCClassDecl cdef, Env<AttrContext> localEnv, 2141 List<Type> argtypes, List<Type> typeargtypes, 2142 KindSelector pkind) { 2143 // We are seeing an anonymous class instance creation. 2144 // In this case, the class instance creation 2145 // expression 2146 // 2147 // E.new <typeargs1>C<typargs2>(args) { ... } 2148 // 2149 // is represented internally as 2150 // 2151 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 2152 // 2153 // This expression is then *transformed* as follows: 2154 // 2155 // (1) add an extends or implements clause 2156 // (2) add a constructor. 2157 // 2158 // For instance, if C is a class, and ET is the type of E, 2159 // the expression 2160 // 2161 // E.new <typeargs1>C<typargs2>(args) { ... } 2162 // 2163 // is translated to (where X is a fresh name and typarams is the 2164 // parameter list of the super constructor): 2165 // 2166 // new <typeargs1>X(<*nullchk*>E, args) where 2167 // X extends C<typargs2> { 2168 // <typarams> X(ET e, args) { 2169 // e.<typeargs1>super(args) 2170 // } 2171 // ... 2172 // } 2173 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2174 final boolean isDiamond = TreeInfo.isDiamond(tree); 2175 if (isDiamond 2176 && ((tree.constructorType != null && inferenceContext.free(tree.constructorType)) 2177 || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) { 2178 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type), 2179 instantiatedContext -> { 2180 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2181 clazz.type = instantiatedContext.asInstType(clazz.type); 2182 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef, localEnv, argtypes, typeargtypes, pkind); 2183 }); 2184 } else { 2185 if (isDiamond && clazztype.hasTag(CLASS)) { 2186 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype); 2187 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) { 2188 // One or more types inferred in the previous steps is non-denotable. 2189 Fragment fragment = Diamond(clazztype.tsym); 2190 log.error(tree.clazz.pos(), 2191 Errors.CantApplyDiamond1( 2192 fragment, 2193 invalidDiamondArgs.size() > 1 ? 2194 DiamondInvalidArgs(invalidDiamondArgs, fragment) : 2195 DiamondInvalidArg(invalidDiamondArgs, fragment))); 2196 } 2197 // For <>(){}, inferred types must also be accessible. 2198 for (Type t : clazztype.getTypeArguments()) { 2199 rs.checkAccessibleType(env, t); 2200 } 2201 } 2202 2203 // If we already errored, be careful to avoid a further avalanche. ErrorType answers 2204 // false for isInterface call even when the original type is an interface. 2205 boolean implementing = clazztype.tsym.isInterface() || 2206 clazztype.isErroneous() && clazztype.getOriginalType().tsym.isInterface(); 2207 2208 if (implementing) { 2209 cdef.implementing = List.of(clazz); 2210 } else { 2211 cdef.extending = clazz; 2212 } 2213 2214 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2215 isSerializable(clazztype)) { 2216 localEnv.info.isSerializable = true; 2217 } 2218 2219 attribStat(cdef, localEnv); 2220 2221 List<Type> finalargtypes; 2222 // If an outer instance is given, 2223 // prefix it to the constructor arguments 2224 // and delete it from the new expression 2225 if (tree.encl != null && !clazztype.tsym.isInterface()) { 2226 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 2227 finalargtypes = argtypes.prepend(tree.encl.type); 2228 tree.encl = null; 2229 } else { 2230 finalargtypes = argtypes; 2231 } 2232 2233 // Reassign clazztype and recompute constructor. As this necessarily involves 2234 // another attribution pass for deferred types in the case of <>, replicate 2235 // them. Original arguments have right decorations already. 2236 if (isDiamond && pkind.contains(KindSelector.POLY)) { 2237 finalargtypes = finalargtypes.map(deferredAttr.deferredCopier); 2238 } 2239 2240 clazztype = cdef.sym.type; 2241 Symbol sym = tree.constructor = rs.resolveConstructor( 2242 tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes); 2243 Assert.check(!sym.kind.isResolutionError()); 2244 tree.constructor = sym; 2245 tree.constructorType = checkId(tree, 2246 clazztype, 2247 tree.constructor, 2248 localEnv, 2249 new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 2250 } 2251 Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ? 2252 clazztype : types.createErrorType(tree.type); 2253 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK)); 2254 chk.validate(tree.typeargs, localEnv); 2255 } 2256 2257 /** Make an attributed null check tree. 2258 */ 2259 public JCExpression makeNullCheck(JCExpression arg) { 2260 // optimization: X.this is never null; skip null check 2261 Name name = TreeInfo.name(arg); 2262 if (name == names._this || name == names._super) return arg; 2263 2264 JCTree.Tag optag = NULLCHK; 2265 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 2266 tree.operator = operators.resolveUnary(arg, optag, arg.type); 2267 tree.type = arg.type; 2268 return tree; 2269 } 2270 2271 public void visitNewArray(JCNewArray tree) { 2272 Type owntype = types.createErrorType(tree.type); 2273 Env<AttrContext> localEnv = env.dup(tree); 2274 Type elemtype; 2275 if (tree.elemtype != null) { 2276 elemtype = attribType(tree.elemtype, localEnv); 2277 chk.validate(tree.elemtype, localEnv); 2278 owntype = elemtype; 2279 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2280 attribExpr(l.head, localEnv, syms.intType); 2281 owntype = new ArrayType(owntype, syms.arrayClass); 2282 } 2283 } else { 2284 // we are seeing an untyped aggregate { ... } 2285 // this is allowed only if the prototype is an array 2286 if (pt().hasTag(ARRAY)) { 2287 elemtype = types.elemtype(pt()); 2288 } else { 2289 if (!pt().hasTag(ERROR)) { 2290 log.error(tree.pos(), "illegal.initializer.for.type", 2291 pt()); 2292 } 2293 elemtype = types.createErrorType(pt()); 2294 } 2295 } 2296 if (tree.elems != null) { 2297 attribExprs(tree.elems, localEnv, elemtype); 2298 owntype = new ArrayType(elemtype, syms.arrayClass); 2299 } 2300 if (!types.isReifiable(elemtype)) 2301 log.error(tree.pos(), "generic.array.creation"); 2302 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2303 } 2304 2305 /* 2306 * A lambda expression can only be attributed when a target-type is available. 2307 * In addition, if the target-type is that of a functional interface whose 2308 * descriptor contains inference variables in argument position the lambda expression 2309 * is 'stuck' (see DeferredAttr). 2310 */ 2311 @Override 2312 public void visitLambda(final JCLambda that) { 2313 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2314 if (pt().hasTag(NONE)) { 2315 //lambda only allowed in assignment or method invocation/cast context 2316 log.error(that.pos(), "unexpected.lambda"); 2317 } 2318 result = that.type = types.createErrorType(pt()); 2319 return; 2320 } 2321 //create an environment for attribution of the lambda expression 2322 final Env<AttrContext> localEnv = lambdaEnv(that, env); 2323 boolean needsRecovery = 2324 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; 2325 try { 2326 Type currentTarget = pt(); 2327 if (needsRecovery && isSerializable(currentTarget)) { 2328 localEnv.info.isSerializable = true; 2329 } 2330 List<Type> explicitParamTypes = null; 2331 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) { 2332 //attribute lambda parameters 2333 attribStats(that.params, localEnv); 2334 explicitParamTypes = TreeInfo.types(that.params); 2335 } 2336 2337 Type lambdaType; 2338 if (pt() != Type.recoveryType) { 2339 /* We need to adjust the target. If the target is an 2340 * intersection type, for example: SAM & I1 & I2 ... 2341 * the target will be updated to SAM 2342 */ 2343 currentTarget = targetChecker.visit(currentTarget, that); 2344 if (explicitParamTypes != null) { 2345 currentTarget = infer.instantiateFunctionalInterface(that, 2346 currentTarget, explicitParamTypes, resultInfo.checkContext); 2347 } 2348 currentTarget = types.removeWildcards(currentTarget); 2349 lambdaType = types.findDescriptorType(currentTarget); 2350 } else { 2351 currentTarget = Type.recoveryType; 2352 lambdaType = fallbackDescriptorType(that); 2353 } 2354 2355 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext); 2356 2357 if (lambdaType.hasTag(FORALL)) { 2358 //lambda expression target desc cannot be a generic method 2359 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", 2360 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym)); 2361 result = that.type = types.createErrorType(pt()); 2362 return; 2363 } 2364 2365 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) { 2366 //add param type info in the AST 2367 List<Type> actuals = lambdaType.getParameterTypes(); 2368 List<JCVariableDecl> params = that.params; 2369 2370 boolean arityMismatch = false; 2371 2372 while (params.nonEmpty()) { 2373 if (actuals.isEmpty()) { 2374 //not enough actuals to perform lambda parameter inference 2375 arityMismatch = true; 2376 } 2377 //reset previously set info 2378 Type argType = arityMismatch ? 2379 syms.errType : 2380 actuals.head; 2381 params.head.vartype = make.at(params.head).Type(argType); 2382 params.head.sym = null; 2383 actuals = actuals.isEmpty() ? 2384 actuals : 2385 actuals.tail; 2386 params = params.tail; 2387 } 2388 2389 //attribute lambda parameters 2390 attribStats(that.params, localEnv); 2391 2392 if (arityMismatch) { 2393 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda")); 2394 result = that.type = types.createErrorType(currentTarget); 2395 return; 2396 } 2397 } 2398 2399 //from this point on, no recovery is needed; if we are in assignment context 2400 //we will be able to attribute the whole lambda body, regardless of errors; 2401 //if we are in a 'check' method context, and the lambda is not compatible 2402 //with the target-type, it will be recovered anyway in Attr.checkId 2403 needsRecovery = false; 2404 2405 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? 2406 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : 2407 new FunctionalReturnContext(resultInfo.checkContext); 2408 2409 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ? 2410 recoveryInfo : 2411 new ResultInfo(KindSelector.VAL, 2412 lambdaType.getReturnType(), funcContext); 2413 localEnv.info.returnResult = bodyResultInfo; 2414 2415 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 2416 attribTree(that.getBody(), localEnv, bodyResultInfo); 2417 } else { 2418 JCBlock body = (JCBlock)that.body; 2419 attribStats(body.stats, localEnv); 2420 } 2421 2422 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2423 2424 boolean isSpeculativeRound = 2425 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2426 2427 preFlow(that); 2428 flow.analyzeLambda(env, that, make, isSpeculativeRound); 2429 2430 that.type = currentTarget; //avoids recovery at this stage 2431 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext); 2432 2433 if (!isSpeculativeRound) { 2434 //add thrown types as bounds to the thrown types free variables if needed: 2435 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) { 2436 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make); 2437 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes()); 2438 2439 chk.unhandled(inferredThrownTypes, thrownTypes); 2440 } 2441 2442 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget); 2443 } 2444 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2445 } catch (Types.FunctionDescriptorLookupError ex) { 2446 JCDiagnostic cause = ex.getDiagnostic(); 2447 resultInfo.checkContext.report(that, cause); 2448 result = that.type = types.createErrorType(pt()); 2449 return; 2450 } catch (Throwable t) { 2451 //when an unexpected exception happens, avoid attempts to attribute the same tree again 2452 //as that would likely cause the same exception again. 2453 needsRecovery = false; 2454 throw t; 2455 } finally { 2456 localEnv.info.scope.leave(); 2457 if (needsRecovery) { 2458 attribTree(that, env, recoveryInfo); 2459 } 2460 } 2461 } 2462 //where 2463 void preFlow(JCLambda tree) { 2464 new PostAttrAnalyzer() { 2465 @Override 2466 public void scan(JCTree tree) { 2467 if (tree == null || 2468 (tree.type != null && 2469 tree.type == Type.stuckType)) { 2470 //don't touch stuck expressions! 2471 return; 2472 } 2473 super.scan(tree); 2474 } 2475 }.scan(tree); 2476 } 2477 2478 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() { 2479 2480 @Override 2481 public Type visitClassType(ClassType t, DiagnosticPosition pos) { 2482 return t.isIntersection() ? 2483 visitIntersectionClassType((IntersectionClassType)t, pos) : t; 2484 } 2485 2486 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) { 2487 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict)); 2488 Type target = null; 2489 for (Type bound : ict.getExplicitComponents()) { 2490 TypeSymbol boundSym = bound.tsym; 2491 if (types.isFunctionalInterface(boundSym) && 2492 types.findDescriptorSymbol(boundSym) == desc) { 2493 target = bound; 2494 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) { 2495 //bound must be an interface 2496 reportIntersectionError(pos, "not.an.intf.component", boundSym); 2497 } 2498 } 2499 return target != null ? 2500 target : 2501 ict.getExplicitComponents().head; //error recovery 2502 } 2503 2504 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) { 2505 ListBuffer<Type> targs = new ListBuffer<>(); 2506 ListBuffer<Type> supertypes = new ListBuffer<>(); 2507 for (Type i : ict.interfaces_field) { 2508 if (i.isParameterized()) { 2509 targs.appendList(i.tsym.type.allparams()); 2510 } 2511 supertypes.append(i.tsym.type); 2512 } 2513 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList()); 2514 notionalIntf.allparams_field = targs.toList(); 2515 notionalIntf.tsym.flags_field |= INTERFACE; 2516 return notionalIntf.tsym; 2517 } 2518 2519 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) { 2520 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr", 2521 diags.fragment(key, args))); 2522 } 2523 }; 2524 2525 private Type fallbackDescriptorType(JCExpression tree) { 2526 switch (tree.getTag()) { 2527 case LAMBDA: 2528 JCLambda lambda = (JCLambda)tree; 2529 List<Type> argtypes = List.nil(); 2530 for (JCVariableDecl param : lambda.params) { 2531 argtypes = param.vartype != null ? 2532 argtypes.append(param.vartype.type) : 2533 argtypes.append(syms.errType); 2534 } 2535 return new MethodType(argtypes, Type.recoveryType, 2536 List.of(syms.throwableType), syms.methodClass); 2537 case REFERENCE: 2538 return new MethodType(List.<Type>nil(), Type.recoveryType, 2539 List.of(syms.throwableType), syms.methodClass); 2540 default: 2541 Assert.error("Cannot get here!"); 2542 } 2543 return null; 2544 } 2545 2546 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2547 final InferenceContext inferenceContext, final Type... ts) { 2548 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 2549 } 2550 2551 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2552 final InferenceContext inferenceContext, final List<Type> ts) { 2553 if (inferenceContext.free(ts)) { 2554 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { 2555 @Override 2556 public void typesInferred(InferenceContext inferenceContext) { 2557 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts)); 2558 } 2559 }); 2560 } else { 2561 for (Type t : ts) { 2562 rs.checkAccessibleType(env, t); 2563 } 2564 } 2565 } 2566 2567 /** 2568 * Lambda/method reference have a special check context that ensures 2569 * that i.e. a lambda return type is compatible with the expected 2570 * type according to both the inherited context and the assignment 2571 * context. 2572 */ 2573 class FunctionalReturnContext extends Check.NestedCheckContext { 2574 2575 FunctionalReturnContext(CheckContext enclosingContext) { 2576 super(enclosingContext); 2577 } 2578 2579 @Override 2580 public boolean compatible(Type found, Type req, Warner warn) { 2581 //return type must be compatible in both current context and assignment context 2582 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn); 2583 } 2584 2585 @Override 2586 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2587 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); 2588 } 2589 } 2590 2591 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 2592 2593 JCExpression expr; 2594 2595 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 2596 super(enclosingContext); 2597 this.expr = expr; 2598 } 2599 2600 @Override 2601 public boolean compatible(Type found, Type req, Warner warn) { 2602 //a void return is compatible with an expression statement lambda 2603 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) || 2604 super.compatible(found, req, warn); 2605 } 2606 } 2607 2608 /** 2609 * Lambda compatibility. Check that given return types, thrown types, parameter types 2610 * are compatible with the expected functional interface descriptor. This means that: 2611 * (i) parameter types must be identical to those of the target descriptor; (ii) return 2612 * types must be compatible with the return type of the expected descriptor. 2613 */ 2614 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) { 2615 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); 2616 2617 //return values have already been checked - but if lambda has no return 2618 //values, we must ensure that void/value compatibility is correct; 2619 //this amounts at checking that, if a lambda body can complete normally, 2620 //the descriptor's return type must be void 2621 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 2622 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 2623 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", 2624 diags.fragment("missing.ret.val", returnType))); 2625 } 2626 2627 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes()); 2628 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 2629 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); 2630 } 2631 } 2632 2633 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a 2634 * static field and that lambda has type annotations, these annotations will 2635 * also be stored at these fake clinit methods. 2636 * 2637 * LambdaToMethod also use fake clinit methods so they can be reused. 2638 * Also as LTM is a phase subsequent to attribution, the methods from 2639 * clinits can be safely removed by LTM to save memory. 2640 */ 2641 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>(); 2642 2643 public MethodSymbol removeClinit(ClassSymbol sym) { 2644 return clinits.remove(sym); 2645 } 2646 2647 /* This method returns an environment to be used to attribute a lambda 2648 * expression. 2649 * 2650 * The owner of this environment is a method symbol. If the current owner 2651 * is not a method, for example if the lambda is used to initialize 2652 * a field, then if the field is: 2653 * 2654 * - an instance field, we use the first constructor. 2655 * - a static field, we create a fake clinit method. 2656 */ 2657 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 2658 Env<AttrContext> lambdaEnv; 2659 Symbol owner = env.info.scope.owner; 2660 if (owner.kind == VAR && owner.owner.kind == TYP) { 2661 //field initializer 2662 ClassSymbol enclClass = owner.enclClass(); 2663 Symbol newScopeOwner = env.info.scope.owner; 2664 /* if the field isn't static, then we can get the first constructor 2665 * and use it as the owner of the environment. This is what 2666 * LTM code is doing to look for type annotations so we are fine. 2667 */ 2668 if ((owner.flags() & STATIC) == 0) { 2669 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) { 2670 newScopeOwner = s; 2671 break; 2672 } 2673 } else { 2674 /* if the field is static then we need to create a fake clinit 2675 * method, this method can later be reused by LTM. 2676 */ 2677 MethodSymbol clinit = clinits.get(enclClass); 2678 if (clinit == null) { 2679 Type clinitType = new MethodType(List.<Type>nil(), 2680 syms.voidType, List.<Type>nil(), syms.methodClass); 2681 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE, 2682 names.clinit, clinitType, enclClass); 2683 clinit.params = List.<VarSymbol>nil(); 2684 clinits.put(enclClass, clinit); 2685 } 2686 newScopeOwner = clinit; 2687 } 2688 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner))); 2689 } else { 2690 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 2691 } 2692 return lambdaEnv; 2693 } 2694 2695 @Override 2696 public void visitReference(final JCMemberReference that) { 2697 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2698 if (pt().hasTag(NONE)) { 2699 //method reference only allowed in assignment or method invocation/cast context 2700 log.error(that.pos(), "unexpected.mref"); 2701 } 2702 result = that.type = types.createErrorType(pt()); 2703 return; 2704 } 2705 final Env<AttrContext> localEnv = env.dup(that); 2706 try { 2707 //attribute member reference qualifier - if this is a constructor 2708 //reference, the expected kind must be a type 2709 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); 2710 2711 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 2712 exprType = chk.checkConstructorRefType(that.expr, exprType); 2713 if (!exprType.isErroneous() && 2714 exprType.isRaw() && 2715 that.typeargs != null) { 2716 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2717 diags.fragment("mref.infer.and.explicit.params")); 2718 exprType = types.createErrorType(exprType); 2719 } 2720 } 2721 2722 if (exprType.isErroneous()) { 2723 //if the qualifier expression contains problems, 2724 //give up attribution of method reference 2725 result = that.type = exprType; 2726 return; 2727 } 2728 2729 if (TreeInfo.isStaticSelector(that.expr, names)) { 2730 //if the qualifier is a type, validate it; raw warning check is 2731 //omitted as we don't know at this stage as to whether this is a 2732 //raw selector (because of inference) 2733 chk.validate(that.expr, env, false); 2734 } 2735 2736 //attrib type-arguments 2737 List<Type> typeargtypes = List.nil(); 2738 if (that.typeargs != null) { 2739 typeargtypes = attribTypes(that.typeargs, localEnv); 2740 } 2741 2742 Type desc; 2743 Type currentTarget = pt(); 2744 boolean isTargetSerializable = 2745 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2746 isSerializable(currentTarget); 2747 if (currentTarget != Type.recoveryType) { 2748 currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that)); 2749 desc = types.findDescriptorType(currentTarget); 2750 } else { 2751 currentTarget = Type.recoveryType; 2752 desc = fallbackDescriptorType(that); 2753 } 2754 2755 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext); 2756 List<Type> argtypes = desc.getParameterTypes(); 2757 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck; 2758 2759 if (resultInfo.checkContext.inferenceContext().free(argtypes)) { 2760 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); 2761 } 2762 2763 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null; 2764 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save(); 2765 try { 2766 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type, 2767 that.name, argtypes, typeargtypes, referenceCheck, 2768 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser); 2769 } finally { 2770 resultInfo.checkContext.inferenceContext().rollback(saved_undet); 2771 } 2772 2773 Symbol refSym = refResult.fst; 2774 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 2775 2776 /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing 2777 * JDK-8075541 2778 */ 2779 if (refSym.kind != MTH) { 2780 boolean targetError; 2781 switch (refSym.kind) { 2782 case ABSENT_MTH: 2783 case MISSING_ENCL: 2784 targetError = false; 2785 break; 2786 case WRONG_MTH: 2787 case WRONG_MTHS: 2788 case AMBIGUOUS: 2789 case HIDDEN: 2790 case STATICERR: 2791 targetError = true; 2792 break; 2793 default: 2794 Assert.error("unexpected result kind " + refSym.kind); 2795 targetError = false; 2796 } 2797 2798 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 2799 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 2800 2801 JCDiagnostic.DiagnosticType diagKind = targetError ? 2802 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; 2803 2804 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, 2805 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); 2806 2807 if (targetError && currentTarget == Type.recoveryType) { 2808 //a target error doesn't make sense during recovery stage 2809 //as we don't know what actual parameter types are 2810 result = that.type = currentTarget; 2811 return; 2812 } else { 2813 if (targetError) { 2814 resultInfo.checkContext.report(that, diag); 2815 } else { 2816 log.report(diag); 2817 } 2818 result = that.type = types.createErrorType(currentTarget); 2819 return; 2820 } 2821 } 2822 2823 that.sym = refSym.baseSymbol(); 2824 that.kind = lookupHelper.referenceKind(that.sym); 2825 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); 2826 2827 if (desc.getReturnType() == Type.recoveryType) { 2828 // stop here 2829 result = that.type = currentTarget; 2830 return; 2831 } 2832 2833 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 2834 2835 if (that.getMode() == ReferenceMode.INVOKE && 2836 TreeInfo.isStaticSelector(that.expr, names) && 2837 that.kind.isUnbound() && 2838 !desc.getParameterTypes().head.isParameterized()) { 2839 chk.checkRaw(that.expr, localEnv); 2840 } 2841 2842 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 2843 exprType.getTypeArguments().nonEmpty()) { 2844 //static ref with class type-args 2845 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2846 diags.fragment("static.mref.with.targs")); 2847 result = that.type = types.createErrorType(currentTarget); 2848 return; 2849 } 2850 2851 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { 2852 // Check that super-qualified symbols are not abstract (JLS) 2853 rs.checkNonAbstract(that.pos(), that.sym); 2854 } 2855 2856 if (isTargetSerializable) { 2857 chk.checkElemAccessFromSerializableLambda(that); 2858 } 2859 } 2860 2861 ResultInfo checkInfo = 2862 resultInfo.dup(newMethodTemplate( 2863 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 2864 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes), 2865 new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE); 2866 2867 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); 2868 2869 if (that.kind.isUnbound() && 2870 resultInfo.checkContext.inferenceContext().free(argtypes.head)) { 2871 //re-generate inference constraints for unbound receiver 2872 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) { 2873 //cannot happen as this has already been checked - we just need 2874 //to regenerate the inference constraints, as that has been lost 2875 //as a result of the call to inferenceContext.save() 2876 Assert.error("Can't get here"); 2877 } 2878 } 2879 2880 if (!refType.isErroneous()) { 2881 refType = types.createMethodTypeWithReturn(refType, 2882 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 2883 } 2884 2885 //go ahead with standard method reference compatibility check - note that param check 2886 //is a no-op (as this has been taken care during method applicability) 2887 boolean isSpeculativeRound = 2888 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2889 2890 that.type = currentTarget; //avoids recovery at this stage 2891 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 2892 if (!isSpeculativeRound) { 2893 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget); 2894 } 2895 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2896 } catch (Types.FunctionDescriptorLookupError ex) { 2897 JCDiagnostic cause = ex.getDiagnostic(); 2898 resultInfo.checkContext.report(that, cause); 2899 result = that.type = types.createErrorType(pt()); 2900 return; 2901 } 2902 } 2903 //where 2904 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { 2905 //if this is a constructor reference, the expected kind must be a type 2906 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? 2907 KindSelector.VAL_TYP : KindSelector.TYP, 2908 Type.noType); 2909 } 2910 2911 2912 @SuppressWarnings("fallthrough") 2913 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 2914 InferenceContext inferenceContext = checkContext.inferenceContext(); 2915 Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType()); 2916 2917 Type resType; 2918 switch (tree.getMode()) { 2919 case NEW: 2920 if (!tree.expr.type.isRaw()) { 2921 resType = tree.expr.type; 2922 break; 2923 } 2924 default: 2925 resType = refType.getReturnType(); 2926 } 2927 2928 Type incompatibleReturnType = resType; 2929 2930 if (returnType.hasTag(VOID)) { 2931 incompatibleReturnType = null; 2932 } 2933 2934 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { 2935 if (resType.isErroneous() || 2936 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) { 2937 incompatibleReturnType = null; 2938 } 2939 } 2940 2941 if (incompatibleReturnType != null) { 2942 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", 2943 diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); 2944 } else { 2945 if (inferenceContext.free(refType)) { 2946 // we need to wait for inference to finish and then replace inference vars in the referent type 2947 inferenceContext.addFreeTypeListener(List.of(refType), 2948 instantiatedContext -> { 2949 tree.referentType = instantiatedContext.asInstType(refType); 2950 }); 2951 } else { 2952 tree.referentType = refType; 2953 } 2954 } 2955 2956 if (!speculativeAttr) { 2957 List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes()); 2958 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { 2959 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); 2960 } 2961 } 2962 } 2963 2964 /** 2965 * Set functional type info on the underlying AST. Note: as the target descriptor 2966 * might contain inference variables, we might need to register an hook in the 2967 * current inference context. 2968 */ 2969 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr, 2970 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) { 2971 if (checkContext.inferenceContext().free(descriptorType)) { 2972 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() { 2973 public void typesInferred(InferenceContext inferenceContext) { 2974 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType), 2975 inferenceContext.asInstType(primaryTarget), checkContext); 2976 } 2977 }); 2978 } else { 2979 ListBuffer<Type> targets = new ListBuffer<>(); 2980 if (pt.hasTag(CLASS)) { 2981 if (pt.isCompound()) { 2982 targets.append(types.removeWildcards(primaryTarget)); //this goes first 2983 for (Type t : ((IntersectionClassType)pt()).interfaces_field) { 2984 if (t != primaryTarget) { 2985 targets.append(types.removeWildcards(t)); 2986 } 2987 } 2988 } else { 2989 targets.append(types.removeWildcards(primaryTarget)); 2990 } 2991 } 2992 fExpr.targets = targets.toList(); 2993 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2994 pt != Type.recoveryType) { 2995 //check that functional interface class is well-formed 2996 try { 2997 /* Types.makeFunctionalInterfaceClass() may throw an exception 2998 * when it's executed post-inference. See the listener code 2999 * above. 3000 */ 3001 ClassSymbol csym = types.makeFunctionalInterfaceClass(env, 3002 names.empty, List.of(fExpr.targets.head), ABSTRACT); 3003 if (csym != null) { 3004 chk.checkImplementations(env.tree, csym, csym); 3005 try { 3006 //perform an additional functional interface check on the synthetic class, 3007 //as there may be spurious errors for raw targets - because of existing issues 3008 //with membership and inheritance (see JDK-8074570). 3009 csym.flags_field |= INTERFACE; 3010 types.findDescriptorType(csym.type); 3011 } catch (FunctionDescriptorLookupError err) { 3012 resultInfo.checkContext.report(fExpr, 3013 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head))); 3014 } 3015 } 3016 } catch (Types.FunctionDescriptorLookupError ex) { 3017 JCDiagnostic cause = ex.getDiagnostic(); 3018 resultInfo.checkContext.report(env.tree, cause); 3019 } 3020 } 3021 } 3022 } 3023 3024 public void visitParens(JCParens tree) { 3025 Type owntype = attribTree(tree.expr, env, resultInfo); 3026 result = check(tree, owntype, pkind(), resultInfo); 3027 Symbol sym = TreeInfo.symbol(tree); 3028 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK)) 3029 log.error(tree.pos(), "illegal.start.of.type"); 3030 } 3031 3032 public void visitAssign(JCAssign tree) { 3033 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo); 3034 Type capturedType = capture(owntype); 3035 attribExpr(tree.rhs, env, owntype); 3036 result = check(tree, capturedType, KindSelector.VAL, resultInfo); 3037 } 3038 3039 public void visitAssignop(JCAssignOp tree) { 3040 // Attribute arguments. 3041 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo); 3042 Type operand = attribExpr(tree.rhs, env); 3043 // Find operator. 3044 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand); 3045 if (operator.kind == MTH && 3046 !owntype.isErroneous() && 3047 !operand.isErroneous()) { 3048 chk.checkDivZero(tree.rhs.pos(), operator, operand); 3049 chk.checkCastable(tree.rhs.pos(), 3050 operator.type.getReturnType(), 3051 owntype); 3052 } 3053 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3054 } 3055 3056 public void visitUnary(JCUnary tree) { 3057 // Attribute arguments. 3058 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 3059 ? attribTree(tree.arg, env, varAssignmentInfo) 3060 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 3061 3062 // Find operator. 3063 Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); 3064 Type owntype = types.createErrorType(tree.type); 3065 if (operator.kind == MTH && 3066 !argtype.isErroneous()) { 3067 owntype = (tree.getTag().isIncOrDecUnaryOp()) 3068 ? tree.arg.type 3069 : operator.type.getReturnType(); 3070 int opc = ((OperatorSymbol)operator).opcode; 3071 3072 // If the argument is constant, fold it. 3073 if (argtype.constValue() != null) { 3074 Type ctype = cfolder.fold1(opc, argtype); 3075 if (ctype != null) { 3076 owntype = cfolder.coerce(ctype, owntype); 3077 } 3078 } 3079 } 3080 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3081 } 3082 3083 public void visitBinary(JCBinary tree) { 3084 // Attribute arguments. 3085 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 3086 Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env)); 3087 // Find operator. 3088 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); 3089 Type owntype = types.createErrorType(tree.type); 3090 if (operator.kind == MTH && 3091 !left.isErroneous() && 3092 !right.isErroneous()) { 3093 owntype = operator.type.getReturnType(); 3094 int opc = ((OperatorSymbol)operator).opcode; 3095 // If both arguments are constants, fold them. 3096 if (left.constValue() != null && right.constValue() != null) { 3097 Type ctype = cfolder.fold2(opc, left, right); 3098 if (ctype != null) { 3099 owntype = cfolder.coerce(ctype, owntype); 3100 } 3101 } 3102 3103 // Check that argument types of a reference ==, != are 3104 // castable to each other, (JLS 15.21). Note: unboxing 3105 // comparisons will not have an acmp* opc at this point. 3106 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 3107 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 3108 log.error(tree.pos(), "incomparable.types", left, right); 3109 } 3110 } 3111 3112 chk.checkDivZero(tree.rhs.pos(), operator, right); 3113 } 3114 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3115 } 3116 3117 public void visitTypeCast(final JCTypeCast tree) { 3118 Type clazztype = attribType(tree.clazz, env); 3119 chk.validate(tree.clazz, env, false); 3120 //a fresh environment is required for 292 inference to work properly --- 3121 //see Infer.instantiatePolymorphicSignatureInstance() 3122 Env<AttrContext> localEnv = env.dup(tree); 3123 //should we propagate the target type? 3124 final ResultInfo castInfo; 3125 JCExpression expr = TreeInfo.skipParens(tree.expr); 3126 boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE)); 3127 if (isPoly) { 3128 //expression is a poly - we need to propagate target type info 3129 castInfo = new ResultInfo(KindSelector.VAL, clazztype, 3130 new Check.NestedCheckContext(resultInfo.checkContext) { 3131 @Override 3132 public boolean compatible(Type found, Type req, Warner warn) { 3133 return types.isCastable(found, req, warn); 3134 } 3135 }); 3136 } else { 3137 //standalone cast - target-type info is not propagated 3138 castInfo = unknownExprInfo; 3139 } 3140 Type exprtype = attribTree(tree.expr, localEnv, castInfo); 3141 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 3142 if (exprtype.constValue() != null) 3143 owntype = cfolder.coerce(exprtype, owntype); 3144 result = check(tree, capture(owntype), KindSelector.VAL, resultInfo); 3145 if (!isPoly) 3146 chk.checkRedundantCast(localEnv, tree); 3147 } 3148 3149 public void visitTypeTest(JCInstanceOf tree) { 3150 Type exprtype = chk.checkNullOrRefType( 3151 tree.expr.pos(), attribExpr(tree.expr, env)); 3152 Type clazztype = attribType(tree.clazz, env); 3153 if (!clazztype.hasTag(TYPEVAR)) { 3154 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype); 3155 } 3156 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) { 3157 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof"); 3158 clazztype = types.createErrorType(clazztype); 3159 } 3160 chk.validate(tree.clazz, env, false); 3161 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 3162 result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo); 3163 } 3164 3165 public void visitIndexed(JCArrayAccess tree) { 3166 Type owntype = types.createErrorType(tree.type); 3167 Type atype = attribExpr(tree.indexed, env); 3168 attribExpr(tree.index, env, syms.intType); 3169 if (types.isArray(atype)) 3170 owntype = types.elemtype(atype); 3171 else if (!atype.hasTag(ERROR)) 3172 log.error(tree.pos(), "array.req.but.found", atype); 3173 if (!pkind().contains(KindSelector.VAL)) 3174 owntype = capture(owntype); 3175 result = check(tree, owntype, KindSelector.VAR, resultInfo); 3176 } 3177 3178 public void visitIdent(JCIdent tree) { 3179 Symbol sym; 3180 3181 // Find symbol 3182 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { 3183 // If we are looking for a method, the prototype `pt' will be a 3184 // method type with the type of the call's arguments as parameters. 3185 env.info.pendingResolutionPhase = null; 3186 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); 3187 } else if (tree.sym != null && tree.sym.kind != VAR) { 3188 sym = tree.sym; 3189 } else { 3190 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); 3191 } 3192 tree.sym = sym; 3193 3194 // (1) Also find the environment current for the class where 3195 // sym is defined (`symEnv'). 3196 // Only for pre-tiger versions (1.4 and earlier): 3197 // (2) Also determine whether we access symbol out of an anonymous 3198 // class in a this or super call. This is illegal for instance 3199 // members since such classes don't carry a this$n link. 3200 // (`noOuterThisPath'). 3201 Env<AttrContext> symEnv = env; 3202 boolean noOuterThisPath = false; 3203 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 3204 sym.kind.matches(KindSelector.VAL_MTH) && 3205 sym.owner.kind == TYP && 3206 tree.name != names._this && tree.name != names._super) { 3207 3208 // Find environment in which identifier is defined. 3209 while (symEnv.outer != null && 3210 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 3211 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 3212 noOuterThisPath = false; 3213 symEnv = symEnv.outer; 3214 } 3215 } 3216 3217 // If symbol is a variable, ... 3218 if (sym.kind == VAR) { 3219 VarSymbol v = (VarSymbol)sym; 3220 3221 // ..., evaluate its initializer, if it has one, and check for 3222 // illegal forward reference. 3223 checkInit(tree, env, v, false); 3224 3225 // If we are expecting a variable (as opposed to a value), check 3226 // that the variable is assignable in the current environment. 3227 if (KindSelector.ASG.subset(pkind())) 3228 checkAssignable(tree.pos(), v, null, env); 3229 } 3230 3231 // In a constructor body, 3232 // if symbol is a field or instance method, check that it is 3233 // not accessed before the supertype constructor is called. 3234 if ((symEnv.info.isSelfCall || noOuterThisPath) && 3235 sym.kind.matches(KindSelector.VAL_MTH) && 3236 sym.owner.kind == TYP && 3237 (sym.flags() & STATIC) == 0) { 3238 chk.earlyRefError(tree.pos(), sym.kind == VAR ? 3239 sym : thisSym(tree.pos(), env)); 3240 } 3241 Env<AttrContext> env1 = env; 3242 if (sym.kind != ERR && sym.kind != TYP && 3243 sym.owner != null && sym.owner != env1.enclClass.sym) { 3244 // If the found symbol is inaccessible, then it is 3245 // accessed through an enclosing instance. Locate this 3246 // enclosing instance: 3247 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 3248 env1 = env1.outer; 3249 } 3250 3251 if (env.info.isSerializable) { 3252 chk.checkElemAccessFromSerializableLambda(tree); 3253 } 3254 3255 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); 3256 } 3257 3258 public void visitSelect(JCFieldAccess tree) { 3259 // Determine the expected kind of the qualifier expression. 3260 KindSelector skind = KindSelector.NIL; 3261 if (tree.name == names._this || tree.name == names._super || 3262 tree.name == names._class) 3263 { 3264 skind = KindSelector.TYP; 3265 } else { 3266 if (pkind().contains(KindSelector.PCK)) 3267 skind = KindSelector.of(skind, KindSelector.PCK); 3268 if (pkind().contains(KindSelector.TYP)) 3269 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK); 3270 if (pkind().contains(KindSelector.VAL_MTH)) 3271 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP); 3272 } 3273 3274 // Attribute the qualifier expression, and determine its symbol (if any). 3275 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly)); 3276 if (!pkind().contains(KindSelector.TYP_PCK)) 3277 site = capture(site); // Capture field access 3278 3279 // don't allow T.class T[].class, etc 3280 if (skind == KindSelector.TYP) { 3281 Type elt = site; 3282 while (elt.hasTag(ARRAY)) 3283 elt = ((ArrayType)elt).elemtype; 3284 if (elt.hasTag(TYPEVAR)) { 3285 log.error(tree.pos(), "type.var.cant.be.deref"); 3286 result = tree.type = types.createErrorType(tree.name, site.tsym, site); 3287 tree.sym = tree.type.tsym; 3288 return ; 3289 } 3290 } 3291 3292 // If qualifier symbol is a type or `super', assert `selectSuper' 3293 // for the selection. This is relevant for determining whether 3294 // protected symbols are accessible. 3295 Symbol sitesym = TreeInfo.symbol(tree.selected); 3296 boolean selectSuperPrev = env.info.selectSuper; 3297 env.info.selectSuper = 3298 sitesym != null && 3299 sitesym.name == names._super; 3300 3301 // Determine the symbol represented by the selection. 3302 env.info.pendingResolutionPhase = null; 3303 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); 3304 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) { 3305 log.error(tree.selected.pos(), "not.encl.class", site.tsym); 3306 sym = syms.errSymbol; 3307 } 3308 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) { 3309 site = capture(site); 3310 sym = selectSym(tree, sitesym, site, env, resultInfo); 3311 } 3312 boolean varArgs = env.info.lastResolveVarargs(); 3313 tree.sym = sym; 3314 3315 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { 3316 site = types.skipTypeVars(site, true); 3317 } 3318 3319 // If that symbol is a variable, ... 3320 if (sym.kind == VAR) { 3321 VarSymbol v = (VarSymbol)sym; 3322 3323 // ..., evaluate its initializer, if it has one, and check for 3324 // illegal forward reference. 3325 checkInit(tree, env, v, true); 3326 3327 // If we are expecting a variable (as opposed to a value), check 3328 // that the variable is assignable in the current environment. 3329 if (KindSelector.ASG.subset(pkind())) 3330 checkAssignable(tree.pos(), v, tree.selected, env); 3331 } 3332 3333 if (sitesym != null && 3334 sitesym.kind == VAR && 3335 ((VarSymbol)sitesym).isResourceVariable() && 3336 sym.kind == MTH && 3337 sym.name.equals(names.close) && 3338 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 3339 env.info.lint.isEnabled(LintCategory.TRY)) { 3340 log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); 3341 } 3342 3343 // Disallow selecting a type from an expression 3344 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) { 3345 tree.type = check(tree.selected, pt(), 3346 sitesym == null ? 3347 KindSelector.VAL : sitesym.kind.toSelector(), 3348 new ResultInfo(KindSelector.TYP_PCK, pt())); 3349 } 3350 3351 if (isType(sitesym)) { 3352 if (sym.name == names._this) { 3353 // If `C' is the currently compiled class, check that 3354 // C.this' does not appear in a call to a super(...) 3355 if (env.info.isSelfCall && 3356 site.tsym == env.enclClass.sym) { 3357 chk.earlyRefError(tree.pos(), sym); 3358 } 3359 } else { 3360 // Check if type-qualified fields or methods are static (JLS) 3361 if ((sym.flags() & STATIC) == 0 && 3362 !env.next.tree.hasTag(REFERENCE) && 3363 sym.name != names._super && 3364 (sym.kind == VAR || sym.kind == MTH)) { 3365 rs.accessBase(rs.new StaticError(sym), 3366 tree.pos(), site, sym.name, true); 3367 } 3368 } 3369 if (!allowStaticInterfaceMethods && sitesym.isInterface() && 3370 sym.isStatic() && sym.kind == MTH) { 3371 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName); 3372 } 3373 } else if (sym.kind != ERR && 3374 (sym.flags() & STATIC) != 0 && 3375 sym.name != names._class) { 3376 // If the qualified item is not a type and the selected item is static, report 3377 // a warning. Make allowance for the class of an array type e.g. Object[].class) 3378 chk.warnStatic(tree, "static.not.qualified.by.type", 3379 sym.kind.kindName(), sym.owner); 3380 } 3381 3382 // If we are selecting an instance member via a `super', ... 3383 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 3384 3385 // Check that super-qualified symbols are not abstract (JLS) 3386 rs.checkNonAbstract(tree.pos(), sym); 3387 3388 if (site.isRaw()) { 3389 // Determine argument types for site. 3390 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 3391 if (site1 != null) site = site1; 3392 } 3393 } 3394 3395 if (env.info.isSerializable) { 3396 chk.checkElemAccessFromSerializableLambda(tree); 3397 } 3398 3399 env.info.selectSuper = selectSuperPrev; 3400 result = checkId(tree, site, sym, env, resultInfo); 3401 } 3402 //where 3403 /** Determine symbol referenced by a Select expression, 3404 * 3405 * @param tree The select tree. 3406 * @param site The type of the selected expression, 3407 * @param env The current environment. 3408 * @param resultInfo The current result. 3409 */ 3410 private Symbol selectSym(JCFieldAccess tree, 3411 Symbol location, 3412 Type site, 3413 Env<AttrContext> env, 3414 ResultInfo resultInfo) { 3415 DiagnosticPosition pos = tree.pos(); 3416 Name name = tree.name; 3417 switch (site.getTag()) { 3418 case PACKAGE: 3419 return rs.accessBase( 3420 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), 3421 pos, location, site, name, true); 3422 case ARRAY: 3423 case CLASS: 3424 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 3425 return rs.resolveQualifiedMethod( 3426 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 3427 } else if (name == names._this || name == names._super) { 3428 return rs.resolveSelf(pos, env, site.tsym, name); 3429 } else if (name == names._class) { 3430 // In this case, we have already made sure in 3431 // visitSelect that qualifier expression is a type. 3432 Type t = syms.classType; 3433 List<Type> typeargs = List.of(types.erasure(site)); 3434 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 3435 return new VarSymbol( 3436 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3437 } else { 3438 // We are seeing a plain identifier as selector. 3439 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); 3440 sym = rs.accessBase(sym, pos, location, site, name, true); 3441 return sym; 3442 } 3443 case WILDCARD: 3444 throw new AssertionError(tree); 3445 case TYPEVAR: 3446 // Normally, site.getUpperBound() shouldn't be null. 3447 // It should only happen during memberEnter/attribBase 3448 // when determining the super type which *must* beac 3449 // done before attributing the type variables. In 3450 // other words, we are seeing this illegal program: 3451 // class B<T> extends A<T.foo> {} 3452 Symbol sym = (site.getUpperBound() != null) 3453 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 3454 : null; 3455 if (sym == null) { 3456 log.error(pos, "type.var.cant.be.deref"); 3457 return syms.errSymbol; 3458 } else { 3459 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 3460 rs.new AccessError(env, site, sym) : 3461 sym; 3462 rs.accessBase(sym2, pos, location, site, name, true); 3463 return sym; 3464 } 3465 case ERROR: 3466 // preserve identifier names through errors 3467 return types.createErrorType(name, site.tsym, site).tsym; 3468 default: 3469 // The qualifier expression is of a primitive type -- only 3470 // .class is allowed for these. 3471 if (name == names._class) { 3472 // In this case, we have already made sure in Select that 3473 // qualifier expression is a type. 3474 Type t = syms.classType; 3475 Type arg = types.boxedClass(site).type; 3476 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 3477 return new VarSymbol( 3478 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3479 } else { 3480 log.error(pos, "cant.deref", site); 3481 return syms.errSymbol; 3482 } 3483 } 3484 } 3485 3486 /** Determine type of identifier or select expression and check that 3487 * (1) the referenced symbol is not deprecated 3488 * (2) the symbol's type is safe (@see checkSafe) 3489 * (3) if symbol is a variable, check that its type and kind are 3490 * compatible with the prototype and protokind. 3491 * (4) if symbol is an instance field of a raw type, 3492 * which is being assigned to, issue an unchecked warning if its 3493 * type changes under erasure. 3494 * (5) if symbol is an instance method of a raw type, issue an 3495 * unchecked warning if its argument types change under erasure. 3496 * If checks succeed: 3497 * If symbol is a constant, return its constant type 3498 * else if symbol is a method, return its result type 3499 * otherwise return its type. 3500 * Otherwise return errType. 3501 * 3502 * @param tree The syntax tree representing the identifier 3503 * @param site If this is a select, the type of the selected 3504 * expression, otherwise the type of the current class. 3505 * @param sym The symbol representing the identifier. 3506 * @param env The current environment. 3507 * @param resultInfo The expected result 3508 */ 3509 Type checkId(JCTree tree, 3510 Type site, 3511 Symbol sym, 3512 Env<AttrContext> env, 3513 ResultInfo resultInfo) { 3514 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 3515 checkMethodId(tree, site, sym, env, resultInfo) : 3516 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3517 } 3518 3519 Type checkMethodId(JCTree tree, 3520 Type site, 3521 Symbol sym, 3522 Env<AttrContext> env, 3523 ResultInfo resultInfo) { 3524 boolean isPolymorhicSignature = 3525 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0; 3526 return isPolymorhicSignature ? 3527 checkSigPolyMethodId(tree, site, sym, env, resultInfo) : 3528 checkMethodIdInternal(tree, site, sym, env, resultInfo); 3529 } 3530 3531 Type checkSigPolyMethodId(JCTree tree, 3532 Type site, 3533 Symbol sym, 3534 Env<AttrContext> env, 3535 ResultInfo resultInfo) { 3536 //recover original symbol for signature polymorphic methods 3537 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); 3538 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; 3539 return sym.type; 3540 } 3541 3542 Type checkMethodIdInternal(JCTree tree, 3543 Type site, 3544 Symbol sym, 3545 Env<AttrContext> env, 3546 ResultInfo resultInfo) { 3547 if (resultInfo.pkind.contains(KindSelector.POLY)) { 3548 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); 3549 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); 3550 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3551 return owntype; 3552 } else { 3553 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3554 } 3555 } 3556 3557 Type checkIdInternal(JCTree tree, 3558 Type site, 3559 Symbol sym, 3560 Type pt, 3561 Env<AttrContext> env, 3562 ResultInfo resultInfo) { 3563 if (pt.isErroneous()) { 3564 return types.createErrorType(site); 3565 } 3566 Type owntype; // The computed type of this identifier occurrence. 3567 switch (sym.kind) { 3568 case TYP: 3569 // For types, the computed type equals the symbol's type, 3570 // except for two situations: 3571 owntype = sym.type; 3572 if (owntype.hasTag(CLASS)) { 3573 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 3574 Type ownOuter = owntype.getEnclosingType(); 3575 3576 // (a) If the symbol's type is parameterized, erase it 3577 // because no type parameters were given. 3578 // We recover generic outer type later in visitTypeApply. 3579 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 3580 owntype = types.erasure(owntype); 3581 } 3582 3583 // (b) If the symbol's type is an inner class, then 3584 // we have to interpret its outer type as a superclass 3585 // of the site type. Example: 3586 // 3587 // class Tree<A> { class Visitor { ... } } 3588 // class PointTree extends Tree<Point> { ... } 3589 // ...PointTree.Visitor... 3590 // 3591 // Then the type of the last expression above is 3592 // Tree<Point>.Visitor. 3593 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 3594 Type normOuter = site; 3595 if (normOuter.hasTag(CLASS)) { 3596 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 3597 } 3598 if (normOuter == null) // perhaps from an import 3599 normOuter = types.erasure(ownOuter); 3600 if (normOuter != ownOuter) 3601 owntype = new ClassType( 3602 normOuter, List.<Type>nil(), owntype.tsym, 3603 owntype.getMetadata()); 3604 } 3605 } 3606 break; 3607 case VAR: 3608 VarSymbol v = (VarSymbol)sym; 3609 // Test (4): if symbol is an instance field of a raw type, 3610 // which is being assigned to, issue an unchecked warning if 3611 // its type changes under erasure. 3612 if (KindSelector.ASG.subset(pkind()) && 3613 v.owner.kind == TYP && 3614 (v.flags() & STATIC) == 0 && 3615 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3616 Type s = types.asOuterSuper(site, v.owner); 3617 if (s != null && 3618 s.isRaw() && 3619 !types.isSameType(v.type, v.erasure(types))) { 3620 chk.warnUnchecked(tree.pos(), 3621 "unchecked.assign.to.var", 3622 v, s); 3623 } 3624 } 3625 // The computed type of a variable is the type of the 3626 // variable symbol, taken as a member of the site type. 3627 owntype = (sym.owner.kind == TYP && 3628 sym.name != names._this && sym.name != names._super) 3629 ? types.memberType(site, sym) 3630 : sym.type; 3631 3632 // If the variable is a constant, record constant value in 3633 // computed type. 3634 if (v.getConstValue() != null && isStaticReference(tree)) 3635 owntype = owntype.constType(v.getConstValue()); 3636 3637 if (resultInfo.pkind == KindSelector.VAL) { 3638 owntype = capture(owntype); // capture "names as expressions" 3639 } 3640 break; 3641 case MTH: { 3642 owntype = checkMethod(site, sym, 3643 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext), 3644 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 3645 resultInfo.pt.getTypeArguments()); 3646 break; 3647 } 3648 case PCK: case ERR: 3649 owntype = sym.type; 3650 break; 3651 default: 3652 throw new AssertionError("unexpected kind: " + sym.kind + 3653 " in tree " + tree); 3654 } 3655 3656 // Test (1): emit a `deprecation' warning if symbol is deprecated. 3657 // (for constructors, the error was given when the constructor was 3658 // resolved) 3659 3660 if (sym.name != names.init) { 3661 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 3662 chk.checkSunAPI(tree.pos(), sym); 3663 chk.checkProfile(tree.pos(), sym); 3664 } 3665 3666 // Test (3): if symbol is a variable, check that its type and 3667 // kind are compatible with the prototype and protokind. 3668 return check(tree, owntype, sym.kind.toSelector(), resultInfo); 3669 } 3670 3671 /** Check that variable is initialized and evaluate the variable's 3672 * initializer, if not yet done. Also check that variable is not 3673 * referenced before it is defined. 3674 * @param tree The tree making up the variable reference. 3675 * @param env The current environment. 3676 * @param v The variable's symbol. 3677 */ 3678 private void checkInit(JCTree tree, 3679 Env<AttrContext> env, 3680 VarSymbol v, 3681 boolean onlyWarning) { 3682// System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 3683// tree.pos + " " + v.pos + " " + 3684// Resolve.isStatic(env));//DEBUG 3685 3686 // A forward reference is diagnosed if the declaration position 3687 // of the variable is greater than the current tree position 3688 // and the tree and variable definition occur in the same class 3689 // definition. Note that writes don't count as references. 3690 // This check applies only to class and instance 3691 // variables. Local variables follow different scope rules, 3692 // and are subject to definite assignment checking. 3693 if ((env.info.enclVar == v || v.pos > tree.pos) && 3694 v.owner.kind == TYP && 3695 enclosingInitEnv(env) != null && 3696 v.owner == env.info.scope.owner.enclClass() && 3697 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 3698 (!env.tree.hasTag(ASSIGN) || 3699 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 3700 String suffix = (env.info.enclVar == v) ? 3701 "self.ref" : "forward.ref"; 3702 if (!onlyWarning || isStaticEnumField(v)) { 3703 log.error(tree.pos(), "illegal." + suffix); 3704 } else if (useBeforeDeclarationWarning) { 3705 log.warning(tree.pos(), suffix, v); 3706 } 3707 } 3708 3709 v.getConstValue(); // ensure initializer is evaluated 3710 3711 checkEnumInitializer(tree, env, v); 3712 } 3713 3714 /** 3715 * Returns the enclosing init environment associated with this env (if any). An init env 3716 * can be either a field declaration env or a static/instance initializer env. 3717 */ 3718 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) { 3719 while (true) { 3720 switch (env.tree.getTag()) { 3721 case VARDEF: 3722 JCVariableDecl vdecl = (JCVariableDecl)env.tree; 3723 if (vdecl.sym.owner.kind == TYP) { 3724 //field 3725 return env; 3726 } 3727 break; 3728 case BLOCK: 3729 if (env.next.tree.hasTag(CLASSDEF)) { 3730 //instance/static initializer 3731 return env; 3732 } 3733 break; 3734 case METHODDEF: 3735 case CLASSDEF: 3736 case TOPLEVEL: 3737 return null; 3738 } 3739 Assert.checkNonNull(env.next); 3740 env = env.next; 3741 } 3742 } 3743 3744 /** 3745 * Check for illegal references to static members of enum. In 3746 * an enum type, constructors and initializers may not 3747 * reference its static members unless they are constant. 3748 * 3749 * @param tree The tree making up the variable reference. 3750 * @param env The current environment. 3751 * @param v The variable's symbol. 3752 * @jls section 8.9 Enums 3753 */ 3754 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 3755 // JLS: 3756 // 3757 // "It is a compile-time error to reference a static field 3758 // of an enum type that is not a compile-time constant 3759 // (15.28) from constructors, instance initializer blocks, 3760 // or instance variable initializer expressions of that 3761 // type. It is a compile-time error for the constructors, 3762 // instance initializer blocks, or instance variable 3763 // initializer expressions of an enum constant e to refer 3764 // to itself or to an enum constant of the same type that 3765 // is declared to the right of e." 3766 if (isStaticEnumField(v)) { 3767 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 3768 3769 if (enclClass == null || enclClass.owner == null) 3770 return; 3771 3772 // See if the enclosing class is the enum (or a 3773 // subclass thereof) declaring v. If not, this 3774 // reference is OK. 3775 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 3776 return; 3777 3778 // If the reference isn't from an initializer, then 3779 // the reference is OK. 3780 if (!Resolve.isInitializer(env)) 3781 return; 3782 3783 log.error(tree.pos(), "illegal.enum.static.ref"); 3784 } 3785 } 3786 3787 /** Is the given symbol a static, non-constant field of an Enum? 3788 * Note: enum literals should not be regarded as such 3789 */ 3790 private boolean isStaticEnumField(VarSymbol v) { 3791 return Flags.isEnum(v.owner) && 3792 Flags.isStatic(v) && 3793 !Flags.isConstant(v) && 3794 v.name != names._class; 3795 } 3796 3797 Warner noteWarner = new Warner(); 3798 3799 /** 3800 * Check that method arguments conform to its instantiation. 3801 **/ 3802 public Type checkMethod(Type site, 3803 final Symbol sym, 3804 ResultInfo resultInfo, 3805 Env<AttrContext> env, 3806 final List<JCExpression> argtrees, 3807 List<Type> argtypes, 3808 List<Type> typeargtypes) { 3809 // Test (5): if symbol is an instance method of a raw type, issue 3810 // an unchecked warning if its argument types change under erasure. 3811 if ((sym.flags() & STATIC) == 0 && 3812 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3813 Type s = types.asOuterSuper(site, sym.owner); 3814 if (s != null && s.isRaw() && 3815 !types.isSameTypes(sym.type.getParameterTypes(), 3816 sym.erasure(types).getParameterTypes())) { 3817 chk.warnUnchecked(env.tree.pos(), 3818 "unchecked.call.mbr.of.raw.type", 3819 sym, s); 3820 } 3821 } 3822 3823 if (env.info.defaultSuperCallSite != null) { 3824 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 3825 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 3826 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 3827 List<MethodSymbol> icand_sup = 3828 types.interfaceCandidates(sup, (MethodSymbol)sym); 3829 if (icand_sup.nonEmpty() && 3830 icand_sup.head != sym && 3831 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 3832 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, 3833 diags.fragment("overridden.default", sym, sup)); 3834 break; 3835 } 3836 } 3837 env.info.defaultSuperCallSite = null; 3838 } 3839 3840 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { 3841 JCMethodInvocation app = (JCMethodInvocation)env.tree; 3842 if (app.meth.hasTag(SELECT) && 3843 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { 3844 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site); 3845 } 3846 } 3847 3848 // Compute the identifier's instantiated type. 3849 // For methods, we need to compute the instance type by 3850 // Resolve.instantiate from the symbol's type as well as 3851 // any type arguments and value arguments. 3852 noteWarner.clear(); 3853 try { 3854 Type owntype = rs.checkMethod( 3855 env, 3856 site, 3857 sym, 3858 resultInfo, 3859 argtypes, 3860 typeargtypes, 3861 noteWarner); 3862 3863 DeferredAttr.DeferredTypeMap checkDeferredMap = 3864 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase); 3865 3866 argtypes = argtypes.map(checkDeferredMap); 3867 3868 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 3869 chk.warnUnchecked(env.tree.pos(), 3870 "unchecked.meth.invocation.applied", 3871 kindName(sym), 3872 sym.name, 3873 rs.methodArguments(sym.type.getParameterTypes()), 3874 rs.methodArguments(argtypes.map(checkDeferredMap)), 3875 kindName(sym.location()), 3876 sym.location()); 3877 owntype = new MethodType(owntype.getParameterTypes(), 3878 types.erasure(owntype.getReturnType()), 3879 types.erasure(owntype.getThrownTypes()), 3880 syms.methodClass); 3881 } 3882 3883 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 3884 resultInfo.checkContext.inferenceContext()); 3885 } catch (Infer.InferenceException ex) { 3886 //invalid target type - propagate exception outwards or report error 3887 //depending on the current check context 3888 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 3889 return types.createErrorType(site); 3890 } catch (Resolve.InapplicableMethodException ex) { 3891 final JCDiagnostic diag = ex.getDiagnostic(); 3892 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) { 3893 @Override 3894 protected Pair<Symbol, JCDiagnostic> errCandidate() { 3895 return new Pair<>(sym, diag); 3896 } 3897 }; 3898 List<Type> argtypes2 = argtypes.map( 3899 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3900 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 3901 env.tree, sym, site, sym.name, argtypes2, typeargtypes); 3902 log.report(errDiag); 3903 return types.createErrorType(site); 3904 } 3905 } 3906 3907 public void visitLiteral(JCLiteral tree) { 3908 result = check(tree, litType(tree.typetag).constType(tree.value), 3909 KindSelector.VAL, resultInfo); 3910 } 3911 //where 3912 /** Return the type of a literal with given type tag. 3913 */ 3914 Type litType(TypeTag tag) { 3915 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 3916 } 3917 3918 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 3919 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo); 3920 } 3921 3922 public void visitTypeArray(JCArrayTypeTree tree) { 3923 Type etype = attribType(tree.elemtype, env); 3924 Type type = new ArrayType(etype, syms.arrayClass); 3925 result = check(tree, type, KindSelector.TYP, resultInfo); 3926 } 3927 3928 /** Visitor method for parameterized types. 3929 * Bound checking is left until later, since types are attributed 3930 * before supertype structure is completely known 3931 */ 3932 public void visitTypeApply(JCTypeApply tree) { 3933 Type owntype = types.createErrorType(tree.type); 3934 3935 // Attribute functor part of application and make sure it's a class. 3936 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 3937 3938 // Attribute type parameters 3939 List<Type> actuals = attribTypes(tree.arguments, env); 3940 3941 if (clazztype.hasTag(CLASS)) { 3942 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 3943 if (actuals.isEmpty()) //diamond 3944 actuals = formals; 3945 3946 if (actuals.length() == formals.length()) { 3947 List<Type> a = actuals; 3948 List<Type> f = formals; 3949 while (a.nonEmpty()) { 3950 a.head = a.head.withTypeVar(f.head); 3951 a = a.tail; 3952 f = f.tail; 3953 } 3954 // Compute the proper generic outer 3955 Type clazzOuter = clazztype.getEnclosingType(); 3956 if (clazzOuter.hasTag(CLASS)) { 3957 Type site; 3958 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 3959 if (clazz.hasTag(IDENT)) { 3960 site = env.enclClass.sym.type; 3961 } else if (clazz.hasTag(SELECT)) { 3962 site = ((JCFieldAccess) clazz).selected.type; 3963 } else throw new AssertionError(""+tree); 3964 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 3965 if (site.hasTag(CLASS)) 3966 site = types.asOuterSuper(site, clazzOuter.tsym); 3967 if (site == null) 3968 site = types.erasure(clazzOuter); 3969 clazzOuter = site; 3970 } 3971 } 3972 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym, 3973 clazztype.getMetadata()); 3974 } else { 3975 if (formals.length() != 0) { 3976 log.error(tree.pos(), "wrong.number.type.args", 3977 Integer.toString(formals.length())); 3978 } else { 3979 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 3980 } 3981 owntype = types.createErrorType(tree.type); 3982 } 3983 } 3984 result = check(tree, owntype, KindSelector.TYP, resultInfo); 3985 } 3986 3987 public void visitTypeUnion(JCTypeUnion tree) { 3988 ListBuffer<Type> multicatchTypes = new ListBuffer<>(); 3989 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 3990 for (JCExpression typeTree : tree.alternatives) { 3991 Type ctype = attribType(typeTree, env); 3992 ctype = chk.checkType(typeTree.pos(), 3993 chk.checkClassType(typeTree.pos(), ctype), 3994 syms.throwableType); 3995 if (!ctype.isErroneous()) { 3996 //check that alternatives of a union type are pairwise 3997 //unrelated w.r.t. subtyping 3998 if (chk.intersects(ctype, multicatchTypes.toList())) { 3999 for (Type t : multicatchTypes) { 4000 boolean sub = types.isSubtype(ctype, t); 4001 boolean sup = types.isSubtype(t, ctype); 4002 if (sub || sup) { 4003 //assume 'a' <: 'b' 4004 Type a = sub ? ctype : t; 4005 Type b = sub ? t : ctype; 4006 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); 4007 } 4008 } 4009 } 4010 multicatchTypes.append(ctype); 4011 if (all_multicatchTypes != null) 4012 all_multicatchTypes.append(ctype); 4013 } else { 4014 if (all_multicatchTypes == null) { 4015 all_multicatchTypes = new ListBuffer<>(); 4016 all_multicatchTypes.appendList(multicatchTypes); 4017 } 4018 all_multicatchTypes.append(ctype); 4019 } 4020 } 4021 Type t = check(tree, types.lub(multicatchTypes.toList()), 4022 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE)); 4023 if (t.hasTag(CLASS)) { 4024 List<Type> alternatives = 4025 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 4026 t = new UnionClassType((ClassType) t, alternatives); 4027 } 4028 tree.type = result = t; 4029 } 4030 4031 public void visitTypeIntersection(JCTypeIntersection tree) { 4032 attribTypes(tree.bounds, env); 4033 tree.type = result = checkIntersection(tree, tree.bounds); 4034 } 4035 4036 public void visitTypeParameter(JCTypeParameter tree) { 4037 TypeVar typeVar = (TypeVar) tree.type; 4038 4039 if (tree.annotations != null && tree.annotations.nonEmpty()) { 4040 annotate.annotateTypeParameterSecondStage(tree, tree.annotations); 4041 } 4042 4043 if (!typeVar.bound.isErroneous()) { 4044 //fixup type-parameter bound computed in 'attribTypeVariables' 4045 typeVar.bound = checkIntersection(tree, tree.bounds); 4046 } 4047 } 4048 4049 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 4050 Set<Type> boundSet = new HashSet<>(); 4051 if (bounds.nonEmpty()) { 4052 // accept class or interface or typevar as first bound. 4053 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 4054 boundSet.add(types.erasure(bounds.head.type)); 4055 if (bounds.head.type.isErroneous()) { 4056 return bounds.head.type; 4057 } 4058 else if (bounds.head.type.hasTag(TYPEVAR)) { 4059 // if first bound was a typevar, do not accept further bounds. 4060 if (bounds.tail.nonEmpty()) { 4061 log.error(bounds.tail.head.pos(), 4062 "type.var.may.not.be.followed.by.other.bounds"); 4063 return bounds.head.type; 4064 } 4065 } else { 4066 // if first bound was a class or interface, accept only interfaces 4067 // as further bounds. 4068 for (JCExpression bound : bounds.tail) { 4069 bound.type = checkBase(bound.type, bound, env, false, true, false); 4070 if (bound.type.isErroneous()) { 4071 bounds = List.of(bound); 4072 } 4073 else if (bound.type.hasTag(CLASS)) { 4074 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 4075 } 4076 } 4077 } 4078 } 4079 4080 if (bounds.length() == 0) { 4081 return syms.objectType; 4082 } else if (bounds.length() == 1) { 4083 return bounds.head.type; 4084 } else { 4085 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds)); 4086 // ... the variable's bound is a class type flagged COMPOUND 4087 // (see comment for TypeVar.bound). 4088 // In this case, generate a class tree that represents the 4089 // bound class, ... 4090 JCExpression extending; 4091 List<JCExpression> implementing; 4092 if (!bounds.head.type.isInterface()) { 4093 extending = bounds.head; 4094 implementing = bounds.tail; 4095 } else { 4096 extending = null; 4097 implementing = bounds; 4098 } 4099 JCClassDecl cd = make.at(tree).ClassDef( 4100 make.Modifiers(PUBLIC | ABSTRACT), 4101 names.empty, List.<JCTypeParameter>nil(), 4102 extending, implementing, List.<JCTree>nil()); 4103 4104 ClassSymbol c = (ClassSymbol)owntype.tsym; 4105 Assert.check((c.flags() & COMPOUND) != 0); 4106 cd.sym = c; 4107 c.sourcefile = env.toplevel.sourcefile; 4108 4109 // ... and attribute the bound class 4110 c.flags_field |= UNATTRIBUTED; 4111 Env<AttrContext> cenv = enter.classEnv(cd, env); 4112 typeEnvs.put(c, cenv); 4113 attribClass(c); 4114 return owntype; 4115 } 4116 } 4117 4118 public void visitWildcard(JCWildcard tree) { 4119 //- System.err.println("visitWildcard("+tree+");");//DEBUG 4120 Type type = (tree.kind.kind == BoundKind.UNBOUND) 4121 ? syms.objectType 4122 : attribType(tree.inner, env); 4123 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 4124 tree.kind.kind, 4125 syms.boundClass), 4126 KindSelector.TYP, resultInfo); 4127 } 4128 4129 public void visitAnnotation(JCAnnotation tree) { 4130 Assert.error("should be handled in annotate"); 4131 } 4132 4133 public void visitAnnotatedType(JCAnnotatedType tree) { 4134 attribAnnotationTypes(tree.annotations, env); 4135 Type underlyingType = attribType(tree.underlyingType, env); 4136 Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET); 4137 4138 if (!env.info.isNewClass) 4139 annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType); 4140 result = tree.type = annotatedType; 4141 } 4142 4143 public void visitErroneous(JCErroneous tree) { 4144 if (tree.errs != null) 4145 for (JCTree err : tree.errs) 4146 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt())); 4147 result = tree.type = syms.errType; 4148 } 4149 4150 /** Default visitor method for all other trees. 4151 */ 4152 public void visitTree(JCTree tree) { 4153 throw new AssertionError(); 4154 } 4155 4156 /** 4157 * Attribute an env for either a top level tree or class declaration. 4158 */ 4159 public void attrib(Env<AttrContext> env) { 4160 if (env.tree.hasTag(TOPLEVEL)) 4161 attribTopLevel(env); 4162 else 4163 attribClass(env.tree.pos(), env.enclClass.sym); 4164 } 4165 4166 /** 4167 * Attribute a top level tree. These trees are encountered when the 4168 * package declaration has annotations. 4169 */ 4170 public void attribTopLevel(Env<AttrContext> env) { 4171 JCCompilationUnit toplevel = env.toplevel; 4172 try { 4173 annotate.flush(); 4174 } catch (CompletionFailure ex) { 4175 chk.completionError(toplevel.pos(), ex); 4176 } 4177 } 4178 4179 /** Main method: attribute class definition associated with given class symbol. 4180 * reporting completion failures at the given position. 4181 * @param pos The source position at which completion errors are to be 4182 * reported. 4183 * @param c The class symbol whose definition will be attributed. 4184 */ 4185 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 4186 try { 4187 annotate.flush(); 4188 attribClass(c); 4189 } catch (CompletionFailure ex) { 4190 chk.completionError(pos, ex); 4191 } 4192 } 4193 4194 /** Attribute class definition associated with given class symbol. 4195 * @param c The class symbol whose definition will be attributed. 4196 */ 4197 void attribClass(ClassSymbol c) throws CompletionFailure { 4198 if (c.type.hasTag(ERROR)) return; 4199 4200 // Check for cycles in the inheritance graph, which can arise from 4201 // ill-formed class files. 4202 chk.checkNonCyclic(null, c.type); 4203 4204 Type st = types.supertype(c.type); 4205 if ((c.flags_field & Flags.COMPOUND) == 0) { 4206 // First, attribute superclass. 4207 if (st.hasTag(CLASS)) 4208 attribClass((ClassSymbol)st.tsym); 4209 4210 // Next attribute owner, if it is a class. 4211 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 4212 attribClass((ClassSymbol)c.owner); 4213 } 4214 4215 // The previous operations might have attributed the current class 4216 // if there was a cycle. So we test first whether the class is still 4217 // UNATTRIBUTED. 4218 if ((c.flags_field & UNATTRIBUTED) != 0) { 4219 c.flags_field &= ~UNATTRIBUTED; 4220 4221 // Get environment current at the point of class definition. 4222 Env<AttrContext> env = typeEnvs.get(c); 4223 4224 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized, 4225 // because the annotations were not available at the time the env was created. Therefore, 4226 // we look up the environment chain for the first enclosing environment for which the 4227 // lint value is set. Typically, this is the parent env, but might be further if there 4228 // are any envs created as a result of TypeParameter nodes. 4229 Env<AttrContext> lintEnv = env; 4230 while (lintEnv.info.lint == null) 4231 lintEnv = lintEnv.next; 4232 4233 // Having found the enclosing lint value, we can initialize the lint value for this class 4234 env.info.lint = lintEnv.info.lint.augment(c); 4235 4236 Lint prevLint = chk.setLint(env.info.lint); 4237 JavaFileObject prev = log.useSource(c.sourcefile); 4238 ResultInfo prevReturnRes = env.info.returnResult; 4239 4240 try { 4241 deferredLintHandler.flush(env.tree); 4242 env.info.returnResult = null; 4243 // java.lang.Enum may not be subclassed by a non-enum 4244 if (st.tsym == syms.enumSym && 4245 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 4246 log.error(env.tree.pos(), "enum.no.subclassing"); 4247 4248 // Enums may not be extended by source-level classes 4249 if (st.tsym != null && 4250 ((st.tsym.flags_field & Flags.ENUM) != 0) && 4251 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { 4252 log.error(env.tree.pos(), "enum.types.not.extensible"); 4253 } 4254 4255 if (isSerializable(c.type)) { 4256 env.info.isSerializable = true; 4257 } 4258 4259 attribClassBody(env, c); 4260 4261 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 4262 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); 4263 chk.checkFunctionalInterface((JCClassDecl) env.tree, c); 4264 } finally { 4265 env.info.returnResult = prevReturnRes; 4266 log.useSource(prev); 4267 chk.setLint(prevLint); 4268 } 4269 4270 } 4271 } 4272 4273 public void visitImport(JCImport tree) { 4274 // nothing to do 4275 } 4276 4277 /** Finish the attribution of a class. */ 4278 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 4279 JCClassDecl tree = (JCClassDecl)env.tree; 4280 Assert.check(c == tree.sym); 4281 4282 // Validate type parameters, supertype and interfaces. 4283 attribStats(tree.typarams, env); 4284 if (!c.isAnonymous()) { 4285 //already checked if anonymous 4286 chk.validate(tree.typarams, env); 4287 chk.validate(tree.extending, env); 4288 chk.validate(tree.implementing, env); 4289 } 4290 4291 c.markAbstractIfNeeded(types); 4292 4293 // If this is a non-abstract class, check that it has no abstract 4294 // methods or unimplemented methods of an implemented interface. 4295 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 4296 if (!relax) 4297 chk.checkAllDefined(tree.pos(), c); 4298 } 4299 4300 if ((c.flags() & ANNOTATION) != 0) { 4301 if (tree.implementing.nonEmpty()) 4302 log.error(tree.implementing.head.pos(), 4303 "cant.extend.intf.annotation"); 4304 if (tree.typarams.nonEmpty()) 4305 log.error(tree.typarams.head.pos(), 4306 "intf.annotation.cant.have.type.params"); 4307 4308 // If this annotation type has a @Repeatable, validate 4309 Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable(); 4310 // If this annotation type has a @Repeatable, validate 4311 if (repeatable != null) { 4312 // get diagnostic position for error reporting 4313 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); 4314 Assert.checkNonNull(cbPos); 4315 4316 chk.validateRepeatable(c, repeatable, cbPos); 4317 } 4318 } else { 4319 // Check that all extended classes and interfaces 4320 // are compatible (i.e. no two define methods with same arguments 4321 // yet different return types). (JLS 8.4.6.3) 4322 chk.checkCompatibleSupertypes(tree.pos(), c.type); 4323 if (allowDefaultMethods) { 4324 chk.checkDefaultMethodClashes(tree.pos(), c.type); 4325 } 4326 } 4327 4328 // Check that class does not import the same parameterized interface 4329 // with two different argument lists. 4330 chk.checkClassBounds(tree.pos(), c.type); 4331 4332 tree.type = c.type; 4333 4334 for (List<JCTypeParameter> l = tree.typarams; 4335 l.nonEmpty(); l = l.tail) { 4336 Assert.checkNonNull(env.info.scope.findFirst(l.head.name)); 4337 } 4338 4339 // Check that a generic class doesn't extend Throwable 4340 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 4341 log.error(tree.extending.pos(), "generic.throwable"); 4342 4343 // Check that all methods which implement some 4344 // method conform to the method they implement. 4345 chk.checkImplementations(tree); 4346 4347 //check that a resource implementing AutoCloseable cannot throw InterruptedException 4348 checkAutoCloseable(tree.pos(), env, c.type); 4349 4350 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 4351 // Attribute declaration 4352 attribStat(l.head, env); 4353 // Check that declarations in inner classes are not static (JLS 8.1.2) 4354 // Make an exception for static constants. 4355 if (c.owner.kind != PCK && 4356 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 4357 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 4358 Symbol sym = null; 4359 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 4360 if (sym == null || 4361 sym.kind != VAR || 4362 ((VarSymbol) sym).getConstValue() == null) 4363 log.error(l.head.pos(), "icls.cant.have.static.decl", c); 4364 } 4365 } 4366 4367 // Check for cycles among non-initial constructors. 4368 chk.checkCyclicConstructors(tree); 4369 4370 // Check for cycles among annotation elements. 4371 chk.checkNonCyclicElements(tree); 4372 4373 // Check for proper use of serialVersionUID 4374 if (env.info.lint.isEnabled(LintCategory.SERIAL) && 4375 isSerializable(c.type) && 4376 (c.flags() & Flags.ENUM) == 0 && 4377 checkForSerial(c)) { 4378 checkSerialVersionUID(tree, c); 4379 } 4380 if (allowTypeAnnos) { 4381 // Correctly organize the postions of the type annotations 4382 typeAnnotations.organizeTypeAnnotationsBodies(tree); 4383 4384 // Check type annotations applicability rules 4385 validateTypeAnnotations(tree, false); 4386 } 4387 } 4388 // where 4389 boolean checkForSerial(ClassSymbol c) { 4390 if ((c.flags() & ABSTRACT) == 0) { 4391 return true; 4392 } else { 4393 return c.members().anyMatch(anyNonAbstractOrDefaultMethod); 4394 } 4395 } 4396 4397 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() { 4398 @Override 4399 public boolean accepts(Symbol s) { 4400 return s.kind == MTH && 4401 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT; 4402 } 4403 }; 4404 4405 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 4406 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 4407 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 4408 if (types.isSameType(al.head.annotationType.type, t)) 4409 return al.head.pos(); 4410 } 4411 4412 return null; 4413 } 4414 4415 /** check if a type is a subtype of Serializable, if that is available. */ 4416 boolean isSerializable(Type t) { 4417 try { 4418 syms.serializableType.complete(); 4419 } 4420 catch (CompletionFailure e) { 4421 return false; 4422 } 4423 return types.isSubtype(t, syms.serializableType); 4424 } 4425 4426 /** Check that an appropriate serialVersionUID member is defined. */ 4427 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 4428 4429 // check for presence of serialVersionUID 4430 VarSymbol svuid = null; 4431 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { 4432 if (sym.kind == VAR) { 4433 svuid = (VarSymbol)sym; 4434 break; 4435 } 4436 } 4437 4438 if (svuid == null) { 4439 log.warning(LintCategory.SERIAL, 4440 tree.pos(), "missing.SVUID", c); 4441 return; 4442 } 4443 4444 // check that it is static final 4445 if ((svuid.flags() & (STATIC | FINAL)) != 4446 (STATIC | FINAL)) 4447 log.warning(LintCategory.SERIAL, 4448 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 4449 4450 // check that it is long 4451 else if (!svuid.type.hasTag(LONG)) 4452 log.warning(LintCategory.SERIAL, 4453 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 4454 4455 // check constant 4456 else if (svuid.getConstValue() == null) 4457 log.warning(LintCategory.SERIAL, 4458 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 4459 } 4460 4461 private Type capture(Type type) { 4462 return types.capture(type); 4463 } 4464 4465 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { 4466 tree.accept(new TypeAnnotationsValidator(sigOnly)); 4467 } 4468 //where 4469 private final class TypeAnnotationsValidator extends TreeScanner { 4470 4471 private final boolean sigOnly; 4472 public TypeAnnotationsValidator(boolean sigOnly) { 4473 this.sigOnly = sigOnly; 4474 } 4475 4476 public void visitAnnotation(JCAnnotation tree) { 4477 chk.validateTypeAnnotation(tree, false); 4478 super.visitAnnotation(tree); 4479 } 4480 public void visitAnnotatedType(JCAnnotatedType tree) { 4481 if (!tree.underlyingType.type.isErroneous()) { 4482 super.visitAnnotatedType(tree); 4483 } 4484 } 4485 public void visitTypeParameter(JCTypeParameter tree) { 4486 chk.validateTypeAnnotations(tree.annotations, true); 4487 scan(tree.bounds); 4488 // Don't call super. 4489 // This is needed because above we call validateTypeAnnotation with 4490 // false, which would forbid annotations on type parameters. 4491 // super.visitTypeParameter(tree); 4492 } 4493 public void visitMethodDef(JCMethodDecl tree) { 4494 if (tree.recvparam != null && 4495 !tree.recvparam.vartype.type.isErroneous()) { 4496 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, 4497 tree.recvparam.vartype.type.tsym); 4498 } 4499 if (tree.restype != null && tree.restype.type != null) { 4500 validateAnnotatedType(tree.restype, tree.restype.type); 4501 } 4502 if (sigOnly) { 4503 scan(tree.mods); 4504 scan(tree.restype); 4505 scan(tree.typarams); 4506 scan(tree.recvparam); 4507 scan(tree.params); 4508 scan(tree.thrown); 4509 } else { 4510 scan(tree.defaultValue); 4511 scan(tree.body); 4512 } 4513 } 4514 public void visitVarDef(final JCVariableDecl tree) { 4515 //System.err.println("validateTypeAnnotations.visitVarDef " + tree); 4516 if (tree.sym != null && tree.sym.type != null) 4517 validateAnnotatedType(tree.vartype, tree.sym.type); 4518 scan(tree.mods); 4519 scan(tree.vartype); 4520 if (!sigOnly) { 4521 scan(tree.init); 4522 } 4523 } 4524 public void visitTypeCast(JCTypeCast tree) { 4525 if (tree.clazz != null && tree.clazz.type != null) 4526 validateAnnotatedType(tree.clazz, tree.clazz.type); 4527 super.visitTypeCast(tree); 4528 } 4529 public void visitTypeTest(JCInstanceOf tree) { 4530 if (tree.clazz != null && tree.clazz.type != null) 4531 validateAnnotatedType(tree.clazz, tree.clazz.type); 4532 super.visitTypeTest(tree); 4533 } 4534 public void visitNewClass(JCNewClass tree) { 4535 if (tree.clazz != null && tree.clazz.type != null) { 4536 if (tree.clazz.hasTag(ANNOTATED_TYPE)) { 4537 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations, 4538 tree.clazz.type.tsym); 4539 } 4540 if (tree.def != null) { 4541 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym); 4542 } 4543 4544 validateAnnotatedType(tree.clazz, tree.clazz.type); 4545 } 4546 super.visitNewClass(tree); 4547 } 4548 public void visitNewArray(JCNewArray tree) { 4549 if (tree.elemtype != null && tree.elemtype.type != null) { 4550 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) { 4551 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations, 4552 tree.elemtype.type.tsym); 4553 } 4554 validateAnnotatedType(tree.elemtype, tree.elemtype.type); 4555 } 4556 super.visitNewArray(tree); 4557 } 4558 public void visitClassDef(JCClassDecl tree) { 4559 //System.err.println("validateTypeAnnotations.visitClassDef " + tree); 4560 if (sigOnly) { 4561 scan(tree.mods); 4562 scan(tree.typarams); 4563 scan(tree.extending); 4564 scan(tree.implementing); 4565 } 4566 for (JCTree member : tree.defs) { 4567 if (member.hasTag(Tag.CLASSDEF)) { 4568 continue; 4569 } 4570 scan(member); 4571 } 4572 } 4573 public void visitBlock(JCBlock tree) { 4574 if (!sigOnly) { 4575 scan(tree.stats); 4576 } 4577 } 4578 4579 /* I would want to model this after 4580 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) 4581 * and override visitSelect and visitTypeApply. 4582 * However, we only set the annotated type in the top-level type 4583 * of the symbol. 4584 * Therefore, we need to override each individual location where a type 4585 * can occur. 4586 */ 4587 private void validateAnnotatedType(final JCTree errtree, final Type type) { 4588 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type); 4589 4590 if (type.isPrimitiveOrVoid()) { 4591 return; 4592 } 4593 4594 JCTree enclTr = errtree; 4595 Type enclTy = type; 4596 4597 boolean repeat = true; 4598 while (repeat) { 4599 if (enclTr.hasTag(TYPEAPPLY)) { 4600 List<Type> tyargs = enclTy.getTypeArguments(); 4601 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments(); 4602 if (trargs.length() > 0) { 4603 // Nothing to do for diamonds 4604 if (tyargs.length() == trargs.length()) { 4605 for (int i = 0; i < tyargs.length(); ++i) { 4606 validateAnnotatedType(trargs.get(i), tyargs.get(i)); 4607 } 4608 } 4609 // If the lengths don't match, it's either a diamond 4610 // or some nested type that redundantly provides 4611 // type arguments in the tree. 4612 } 4613 4614 // Look at the clazz part of a generic type 4615 enclTr = ((JCTree.JCTypeApply)enclTr).clazz; 4616 } 4617 4618 if (enclTr.hasTag(SELECT)) { 4619 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression(); 4620 if (enclTy != null && 4621 !enclTy.hasTag(NONE)) { 4622 enclTy = enclTy.getEnclosingType(); 4623 } 4624 } else if (enclTr.hasTag(ANNOTATED_TYPE)) { 4625 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; 4626 if (enclTy == null || enclTy.hasTag(NONE)) { 4627 if (at.getAnnotations().size() == 1) { 4628 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute); 4629 } else { 4630 ListBuffer<Attribute.Compound> comps = new ListBuffer<>(); 4631 for (JCAnnotation an : at.getAnnotations()) { 4632 comps.add(an.attribute); 4633 } 4634 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList()); 4635 } 4636 repeat = false; 4637 } 4638 enclTr = at.underlyingType; 4639 // enclTy doesn't need to be changed 4640 } else if (enclTr.hasTag(IDENT)) { 4641 repeat = false; 4642 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) { 4643 JCWildcard wc = (JCWildcard) enclTr; 4644 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) { 4645 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound()); 4646 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) { 4647 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound()); 4648 } else { 4649 // Nothing to do for UNBOUND 4650 } 4651 repeat = false; 4652 } else if (enclTr.hasTag(TYPEARRAY)) { 4653 JCArrayTypeTree art = (JCArrayTypeTree) enclTr; 4654 validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType()); 4655 repeat = false; 4656 } else if (enclTr.hasTag(TYPEUNION)) { 4657 JCTypeUnion ut = (JCTypeUnion) enclTr; 4658 for (JCTree t : ut.getTypeAlternatives()) { 4659 validateAnnotatedType(t, t.type); 4660 } 4661 repeat = false; 4662 } else if (enclTr.hasTag(TYPEINTERSECTION)) { 4663 JCTypeIntersection it = (JCTypeIntersection) enclTr; 4664 for (JCTree t : it.getBounds()) { 4665 validateAnnotatedType(t, t.type); 4666 } 4667 repeat = false; 4668 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE || 4669 enclTr.getKind() == JCTree.Kind.ERRONEOUS) { 4670 repeat = false; 4671 } else { 4672 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() + 4673 " within: "+ errtree + " with kind: " + errtree.getKind()); 4674 } 4675 } 4676 } 4677 4678 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations, 4679 Symbol sym) { 4680 // Ensure that no declaration annotations are present. 4681 // Note that a tree type might be an AnnotatedType with 4682 // empty annotations, if only declaration annotations were given. 4683 // This method will raise an error for such a type. 4684 for (JCAnnotation ai : annotations) { 4685 if (!ai.type.isErroneous() && 4686 typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) { 4687 log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type)); 4688 } 4689 } 4690 } 4691 } 4692 4693 // <editor-fold desc="post-attribution visitor"> 4694 4695 /** 4696 * Handle missing types/symbols in an AST. This routine is useful when 4697 * the compiler has encountered some errors (which might have ended up 4698 * terminating attribution abruptly); if the compiler is used in fail-over 4699 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 4700 * prevents NPE to be progagated during subsequent compilation steps. 4701 */ 4702 public void postAttr(JCTree tree) { 4703 new PostAttrAnalyzer().scan(tree); 4704 } 4705 4706 class PostAttrAnalyzer extends TreeScanner { 4707 4708 private void initTypeIfNeeded(JCTree that) { 4709 if (that.type == null) { 4710 if (that.hasTag(METHODDEF)) { 4711 that.type = dummyMethodType((JCMethodDecl)that); 4712 } else { 4713 that.type = syms.unknownType; 4714 } 4715 } 4716 } 4717 4718 /* Construct a dummy method type. If we have a method declaration, 4719 * and the declared return type is void, then use that return type 4720 * instead of UNKNOWN to avoid spurious error messages in lambda 4721 * bodies (see:JDK-8041704). 4722 */ 4723 private Type dummyMethodType(JCMethodDecl md) { 4724 Type restype = syms.unknownType; 4725 if (md != null && md.restype.hasTag(TYPEIDENT)) { 4726 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; 4727 if (prim.typetag == VOID) 4728 restype = syms.voidType; 4729 } 4730 return new MethodType(List.<Type>nil(), restype, 4731 List.<Type>nil(), syms.methodClass); 4732 } 4733 private Type dummyMethodType() { 4734 return dummyMethodType(null); 4735 } 4736 4737 @Override 4738 public void scan(JCTree tree) { 4739 if (tree == null) return; 4740 if (tree instanceof JCExpression) { 4741 initTypeIfNeeded(tree); 4742 } 4743 super.scan(tree); 4744 } 4745 4746 @Override 4747 public void visitIdent(JCIdent that) { 4748 if (that.sym == null) { 4749 that.sym = syms.unknownSymbol; 4750 } 4751 } 4752 4753 @Override 4754 public void visitSelect(JCFieldAccess that) { 4755 if (that.sym == null) { 4756 that.sym = syms.unknownSymbol; 4757 } 4758 super.visitSelect(that); 4759 } 4760 4761 @Override 4762 public void visitClassDef(JCClassDecl that) { 4763 initTypeIfNeeded(that); 4764 if (that.sym == null) { 4765 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 4766 } 4767 super.visitClassDef(that); 4768 } 4769 4770 @Override 4771 public void visitMethodDef(JCMethodDecl that) { 4772 initTypeIfNeeded(that); 4773 if (that.sym == null) { 4774 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 4775 } 4776 super.visitMethodDef(that); 4777 } 4778 4779 @Override 4780 public void visitVarDef(JCVariableDecl that) { 4781 initTypeIfNeeded(that); 4782 if (that.sym == null) { 4783 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 4784 that.sym.adr = 0; 4785 } 4786 super.visitVarDef(that); 4787 } 4788 4789 @Override 4790 public void visitNewClass(JCNewClass that) { 4791 if (that.constructor == null) { 4792 that.constructor = new MethodSymbol(0, names.init, 4793 dummyMethodType(), syms.noSymbol); 4794 } 4795 if (that.constructorType == null) { 4796 that.constructorType = syms.unknownType; 4797 } 4798 super.visitNewClass(that); 4799 } 4800 4801 @Override 4802 public void visitAssignop(JCAssignOp that) { 4803 if (that.operator == null) { 4804 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4805 -1, syms.noSymbol); 4806 } 4807 super.visitAssignop(that); 4808 } 4809 4810 @Override 4811 public void visitBinary(JCBinary that) { 4812 if (that.operator == null) { 4813 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4814 -1, syms.noSymbol); 4815 } 4816 super.visitBinary(that); 4817 } 4818 4819 @Override 4820 public void visitUnary(JCUnary that) { 4821 if (that.operator == null) { 4822 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4823 -1, syms.noSymbol); 4824 } 4825 super.visitUnary(that); 4826 } 4827 4828 @Override 4829 public void visitLambda(JCLambda that) { 4830 super.visitLambda(that); 4831 if (that.targets == null) { 4832 that.targets = List.nil(); 4833 } 4834 } 4835 4836 @Override 4837 public void visitReference(JCMemberReference that) { 4838 super.visitReference(that); 4839 if (that.sym == null) { 4840 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(), 4841 syms.noSymbol); 4842 } 4843 if (that.targets == null) { 4844 that.targets = List.nil(); 4845 } 4846 } 4847 } 4848 // </editor-fold> 4849} 4850