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