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