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