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