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