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