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