Attr.java revision 2854:42098d16d8f9
1/* 2 * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package com.sun.tools.javac.comp; 27 28import java.util.*; 29 30import javax.lang.model.element.ElementKind; 31import javax.tools.JavaFileObject; 32 33import com.sun.source.tree.IdentifierTree; 34import com.sun.source.tree.MemberReferenceTree.ReferenceMode; 35import com.sun.source.tree.MemberSelectTree; 36import com.sun.source.tree.TreeVisitor; 37import com.sun.source.util.SimpleTreeVisitor; 38import com.sun.tools.javac.code.*; 39import com.sun.tools.javac.code.Lint.LintCategory; 40import com.sun.tools.javac.code.Scope.WriteableScope; 41import com.sun.tools.javac.code.Symbol.*; 42import com.sun.tools.javac.code.Type.*; 43import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError; 44import com.sun.tools.javac.comp.Check.CheckContext; 45import com.sun.tools.javac.comp.DeferredAttr.AttrMode; 46import com.sun.tools.javac.comp.Infer.InferenceContext; 47import com.sun.tools.javac.comp.Infer.FreeTypeListener; 48import com.sun.tools.javac.jvm.*; 49import com.sun.tools.javac.resources.CompilerProperties.Fragments; 50import com.sun.tools.javac.tree.*; 51import com.sun.tools.javac.tree.JCTree.*; 52import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 53import com.sun.tools.javac.util.*; 54import com.sun.tools.javac.util.DefinedBy.Api; 55import com.sun.tools.javac.util.Dependencies.AttributionKind; 56import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 57import com.sun.tools.javac.util.List; 58import static com.sun.tools.javac.code.Flags.*; 59import static com.sun.tools.javac.code.Flags.ANNOTATION; 60import static com.sun.tools.javac.code.Flags.BLOCK; 61import static com.sun.tools.javac.code.Kinds.*; 62import static com.sun.tools.javac.code.Kinds.Kind.*; 63import static com.sun.tools.javac.code.TypeTag.*; 64import static com.sun.tools.javac.code.TypeTag.WILDCARD; 65import static com.sun.tools.javac.tree.JCTree.Tag.*; 66 67/** This is the main context-dependent analysis phase in GJC. It 68 * encompasses name resolution, type checking and constant folding as 69 * subtasks. Some subtasks involve auxiliary classes. 70 * @see Check 71 * @see Resolve 72 * @see ConstFold 73 * @see Infer 74 * 75 * <p><b>This is NOT part of any supported API. 76 * If you write code that depends on this, you do so at your own risk. 77 * This code and its internal interfaces are subject to change or 78 * deletion without notice.</b> 79 */ 80public class Attr extends JCTree.Visitor { 81 protected static final Context.Key<Attr> attrKey = new Context.Key<>(); 82 83 final Names names; 84 final Log log; 85 final Symtab syms; 86 final Resolve rs; 87 final Operators operators; 88 final Infer infer; 89 final Analyzer analyzer; 90 final DeferredAttr deferredAttr; 91 final Check chk; 92 final Flow flow; 93 final MemberEnter memberEnter; 94 final TypeEnter typeEnter; 95 final TreeMaker make; 96 final ConstFold cfolder; 97 final Enter enter; 98 final Target target; 99 final Types types; 100 final JCDiagnostic.Factory diags; 101 final Annotate annotate; 102 final TypeAnnotations typeAnnotations; 103 final DeferredLintHandler deferredLintHandler; 104 final TypeEnvs typeEnvs; 105 final Dependencies dependencies; 106 107 public static Attr instance(Context context) { 108 Attr instance = context.get(attrKey); 109 if (instance == null) 110 instance = new Attr(context); 111 return instance; 112 } 113 114 protected Attr(Context context) { 115 context.put(attrKey, this); 116 117 names = Names.instance(context); 118 log = Log.instance(context); 119 syms = Symtab.instance(context); 120 rs = Resolve.instance(context); 121 operators = Operators.instance(context); 122 chk = Check.instance(context); 123 flow = Flow.instance(context); 124 memberEnter = MemberEnter.instance(context); 125 typeEnter = TypeEnter.instance(context); 126 make = TreeMaker.instance(context); 127 enter = Enter.instance(context); 128 infer = Infer.instance(context); 129 analyzer = Analyzer.instance(context); 130 deferredAttr = DeferredAttr.instance(context); 131 cfolder = ConstFold.instance(context); 132 target = Target.instance(context); 133 types = Types.instance(context); 134 diags = JCDiagnostic.Factory.instance(context); 135 annotate = Annotate.instance(context); 136 typeAnnotations = TypeAnnotations.instance(context); 137 deferredLintHandler = DeferredLintHandler.instance(context); 138 typeEnvs = TypeEnvs.instance(context); 139 dependencies = Dependencies.instance(context); 140 141 Options options = Options.instance(context); 142 143 Source source = Source.instance(context); 144 allowStringsInSwitch = source.allowStringsInSwitch(); 145 allowPoly = source.allowPoly(); 146 allowTypeAnnos = source.allowTypeAnnotations(); 147 allowLambda = source.allowLambda(); 148 allowDefaultMethods = source.allowDefaultMethods(); 149 allowStaticInterfaceMethods = source.allowStaticInterfaceMethods(); 150 sourceName = source.name; 151 relax = (options.isSet("-retrofit") || 152 options.isSet("-relax")); 153 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); 154 155 statInfo = new ResultInfo(KindSelector.NIL, Type.noType); 156 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType); 157 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType); 158 unknownAnyPolyInfo = new ResultInfo(KindSelector.VAL, Infer.anyPoly); 159 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType); 160 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType); 161 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); 162 163 noCheckTree = make.at(-1).Skip(); 164 } 165 166 /** Switch: relax some constraints for retrofit mode. 167 */ 168 boolean relax; 169 170 /** Switch: support target-typing inference 171 */ 172 boolean allowPoly; 173 174 /** Switch: support type annotations. 175 */ 176 boolean allowTypeAnnos; 177 178 /** Switch: support lambda expressions ? 179 */ 180 boolean allowLambda; 181 182 /** Switch: support default methods ? 183 */ 184 boolean allowDefaultMethods; 185 186 /** Switch: static interface methods enabled? 187 */ 188 boolean allowStaticInterfaceMethods; 189 190 /** 191 * Switch: warn about use of variable before declaration? 192 * RFE: 6425594 193 */ 194 boolean useBeforeDeclarationWarning; 195 196 /** 197 * Switch: allow strings in switch? 198 */ 199 boolean allowStringsInSwitch; 200 201 /** 202 * Switch: name of source level; used for error reporting. 203 */ 204 String sourceName; 205 206 /** Check kind and type of given tree against protokind and prototype. 207 * If check succeeds, store type in tree and return it. 208 * If check fails, store errType in tree and return it. 209 * No checks are performed if the prototype is a method type. 210 * It is not necessary in this case since we know that kind and type 211 * are correct. 212 * 213 * @param tree The tree whose kind and type is checked 214 * @param found The computed type of the tree 215 * @param ownkind The computed kind of the tree 216 * @param resultInfo The expected result of the tree 217 */ 218 Type check(final JCTree tree, 219 final Type found, 220 final KindSelector ownkind, 221 final ResultInfo resultInfo) { 222 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 223 Type owntype; 224 boolean shouldCheck = !found.hasTag(ERROR) && 225 !resultInfo.pt.hasTag(METHOD) && 226 !resultInfo.pt.hasTag(FORALL); 227 if (shouldCheck && !ownkind.subset(resultInfo.pkind)) { 228 log.error(tree.pos(), "unexpected.type", 229 resultInfo.pkind.kindNames(), 230 ownkind.kindNames()); 231 owntype = types.createErrorType(found); 232 } else if (allowPoly && inferenceContext.free(found)) { 233 //delay the check if there are inference variables in the found type 234 //this means we are dealing with a partially inferred poly expression 235 owntype = shouldCheck ? resultInfo.pt : found; 236 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), 237 instantiatedContext -> { 238 ResultInfo pendingResult = 239 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); 240 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); 241 }); 242 } else { 243 owntype = shouldCheck ? 244 resultInfo.check(tree, found) : 245 found; 246 } 247 if (tree != noCheckTree) { 248 tree.type = owntype; 249 } 250 return owntype; 251 } 252 253 /** Is given blank final variable assignable, i.e. in a scope where it 254 * may be assigned to even though it is final? 255 * @param v The blank final variable. 256 * @param env The current environment. 257 */ 258 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 259 Symbol owner = env.info.scope.owner; 260 // owner refers to the innermost variable, method or 261 // initializer block declaration at this point. 262 return 263 v.owner == owner 264 || 265 ((owner.name == names.init || // i.e. we are in a constructor 266 owner.kind == VAR || // i.e. we are in a variable initializer 267 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 268 && 269 v.owner == owner.owner 270 && 271 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 272 } 273 274 /** Check that variable can be assigned to. 275 * @param pos The current source code position. 276 * @param v The assigned varaible 277 * @param base If the variable is referred to in a Select, the part 278 * to the left of the `.', null otherwise. 279 * @param env The current environment. 280 */ 281 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 282 if ((v.flags() & FINAL) != 0 && 283 ((v.flags() & HASINIT) != 0 284 || 285 !((base == null || 286 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) && 287 isAssignableAsBlankFinal(v, env)))) { 288 if (v.isResourceVariable()) { //TWR resource 289 log.error(pos, "try.resource.may.not.be.assigned", v); 290 } else { 291 log.error(pos, "cant.assign.val.to.final.var", v); 292 } 293 } 294 } 295 296 /** Does tree represent a static reference to an identifier? 297 * It is assumed that tree is either a SELECT or an IDENT. 298 * We have to weed out selects from non-type names here. 299 * @param tree The candidate tree. 300 */ 301 boolean isStaticReference(JCTree tree) { 302 if (tree.hasTag(SELECT)) { 303 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 304 if (lsym == null || lsym.kind != TYP) { 305 return false; 306 } 307 } 308 return true; 309 } 310 311 /** Is this symbol a type? 312 */ 313 static boolean isType(Symbol sym) { 314 return sym != null && sym.kind == TYP; 315 } 316 317 /** The current `this' symbol. 318 * @param env The current environment. 319 */ 320 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 321 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 322 } 323 324 /** Attribute a parsed identifier. 325 * @param tree Parsed identifier name 326 * @param topLevel The toplevel to use 327 */ 328 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 329 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 330 localEnv.enclClass = make.ClassDef(make.Modifiers(0), 331 syms.errSymbol.name, 332 null, null, null, null); 333 localEnv.enclClass.sym = syms.errSymbol; 334 return tree.accept(identAttributer, localEnv); 335 } 336 // where 337 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 338 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 339 @Override @DefinedBy(Api.COMPILER_TREE) 340 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 341 Symbol site = visit(node.getExpression(), env); 342 if (site.kind == ERR || site.kind == ABSENT_TYP) 343 return site; 344 Name name = (Name)node.getIdentifier(); 345 if (site.kind == PCK) { 346 env.toplevel.packge = (PackageSymbol)site; 347 return rs.findIdentInPackage(env, (TypeSymbol)site, name, 348 KindSelector.TYP_PCK); 349 } else { 350 env.enclClass.sym = (ClassSymbol)site; 351 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 352 } 353 } 354 355 @Override @DefinedBy(Api.COMPILER_TREE) 356 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 357 return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK); 358 } 359 } 360 361 public Type coerce(Type etype, Type ttype) { 362 return cfolder.coerce(etype, ttype); 363 } 364 365 public Type attribType(JCTree node, TypeSymbol sym) { 366 Env<AttrContext> env = typeEnvs.get(sym); 367 Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 368 return attribTree(node, localEnv, unknownTypeInfo); 369 } 370 371 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) { 372 // Attribute qualifying package or class. 373 JCFieldAccess s = (JCFieldAccess)tree.qualid; 374 return attribTree(s.selected, env, 375 new ResultInfo(tree.staticImport ? 376 KindSelector.TYP : KindSelector.TYP_PCK, 377 Type.noType)); 378 } 379 380 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 381 breakTree = tree; 382 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 383 try { 384 attribExpr(expr, env); 385 } catch (BreakAttr b) { 386 return b.env; 387 } catch (AssertionError ae) { 388 if (ae.getCause() instanceof BreakAttr) { 389 return ((BreakAttr)(ae.getCause())).env; 390 } else { 391 throw ae; 392 } 393 } finally { 394 breakTree = null; 395 log.useSource(prev); 396 } 397 return env; 398 } 399 400 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 401 breakTree = tree; 402 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 403 try { 404 attribStat(stmt, env); 405 } catch (BreakAttr b) { 406 return b.env; 407 } catch (AssertionError ae) { 408 if (ae.getCause() instanceof BreakAttr) { 409 return ((BreakAttr)(ae.getCause())).env; 410 } else { 411 throw ae; 412 } 413 } finally { 414 breakTree = null; 415 log.useSource(prev); 416 } 417 return env; 418 } 419 420 private JCTree breakTree = null; 421 422 private static class BreakAttr extends RuntimeException { 423 static final long serialVersionUID = -6924771130405446405L; 424 private Env<AttrContext> env; 425 private BreakAttr(Env<AttrContext> env) { 426 this.env = env; 427 } 428 } 429 430 class ResultInfo { 431 final KindSelector pkind; 432 final Type pt; 433 final CheckContext checkContext; 434 435 ResultInfo(KindSelector pkind, Type pt) { 436 this(pkind, pt, chk.basicHandler); 437 } 438 439 protected ResultInfo(KindSelector pkind, 440 Type pt, CheckContext checkContext) { 441 this.pkind = pkind; 442 this.pt = pt; 443 this.checkContext = checkContext; 444 } 445 446 protected Type check(final DiagnosticPosition pos, final Type found) { 447 return chk.checkType(pos, found, pt, checkContext); 448 } 449 450 protected ResultInfo dup(Type newPt) { 451 return new ResultInfo(pkind, newPt, checkContext); 452 } 453 454 protected ResultInfo dup(CheckContext newContext) { 455 return new ResultInfo(pkind, pt, newContext); 456 } 457 458 protected ResultInfo dup(Type newPt, CheckContext newContext) { 459 return new ResultInfo(pkind, newPt, newContext); 460 } 461 462 @Override 463 public String toString() { 464 if (pt != null) { 465 return pt.toString(); 466 } else { 467 return ""; 468 } 469 } 470 } 471 472 class RecoveryInfo extends ResultInfo { 473 474 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { 475 super(KindSelector.VAL, Type.recoveryType, 476 new Check.NestedCheckContext(chk.basicHandler) { 477 @Override 478 public DeferredAttr.DeferredAttrContext deferredAttrContext() { 479 return deferredAttrContext; 480 } 481 @Override 482 public boolean compatible(Type found, Type req, Warner warn) { 483 return true; 484 } 485 @Override 486 public void report(DiagnosticPosition pos, JCDiagnostic details) { 487 chk.basicHandler.report(pos, details); 488 } 489 }); 490 } 491 } 492 493 final ResultInfo statInfo; 494 final ResultInfo varAssignmentInfo; 495 final ResultInfo unknownAnyPolyInfo; 496 final ResultInfo unknownExprInfo; 497 final ResultInfo unknownTypeInfo; 498 final ResultInfo unknownTypeExprInfo; 499 final ResultInfo recoveryInfo; 500 501 Type pt() { 502 return resultInfo.pt; 503 } 504 505 KindSelector pkind() { 506 return resultInfo.pkind; 507 } 508 509/* ************************************************************************ 510 * Visitor methods 511 *************************************************************************/ 512 513 /** Visitor argument: the current environment. 514 */ 515 Env<AttrContext> env; 516 517 /** Visitor argument: the currently expected attribution result. 518 */ 519 ResultInfo resultInfo; 520 521 /** Visitor result: the computed type. 522 */ 523 Type result; 524 525 /** Synthetic tree to be used during 'fake' checks. 526 */ 527 JCTree noCheckTree; 528 529 /** Visitor method: attribute a tree, catching any completion failure 530 * exceptions. Return the tree's type. 531 * 532 * @param tree The tree to be visited. 533 * @param env The environment visitor argument. 534 * @param resultInfo The result info visitor argument. 535 */ 536 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 537 Env<AttrContext> prevEnv = this.env; 538 ResultInfo prevResult = this.resultInfo; 539 try { 540 this.env = env; 541 this.resultInfo = resultInfo; 542 tree.accept(this); 543 if (tree == breakTree && 544 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 545 throw new BreakAttr(copyEnv(env)); 546 } 547 return result; 548 } catch (CompletionFailure ex) { 549 tree.type = syms.errType; 550 return chk.completionError(tree.pos(), ex); 551 } finally { 552 this.env = prevEnv; 553 this.resultInfo = prevResult; 554 } 555 } 556 557 Env<AttrContext> copyEnv(Env<AttrContext> env) { 558 Env<AttrContext> newEnv = 559 env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); 560 if (newEnv.outer != null) { 561 newEnv.outer = copyEnv(newEnv.outer); 562 } 563 return newEnv; 564 } 565 566 WriteableScope copyScope(WriteableScope sc) { 567 WriteableScope newScope = WriteableScope.create(sc.owner); 568 List<Symbol> elemsList = List.nil(); 569 for (Symbol sym : sc.getSymbols()) { 570 elemsList = elemsList.prepend(sym); 571 } 572 for (Symbol s : elemsList) { 573 newScope.enter(s); 574 } 575 return newScope; 576 } 577 578 /** Derived visitor method: attribute an expression tree. 579 */ 580 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 581 return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); 582 } 583 584 /** Derived visitor method: attribute an expression tree with 585 * no constraints on the computed type. 586 */ 587 public Type attribExpr(JCTree tree, Env<AttrContext> env) { 588 return attribTree(tree, env, unknownExprInfo); 589 } 590 591 /** Derived visitor method: attribute a type tree. 592 */ 593 public Type attribType(JCTree tree, Env<AttrContext> env) { 594 Type result = attribType(tree, env, Type.noType); 595 return result; 596 } 597 598 /** Derived visitor method: attribute a type tree. 599 */ 600 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 601 Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt)); 602 return result; 603 } 604 605 /** Derived visitor method: attribute a statement or definition tree. 606 */ 607 public Type attribStat(JCTree tree, Env<AttrContext> env) { 608 Env<AttrContext> analyzeEnv = 609 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner))); 610 try { 611 return attribTree(tree, env, statInfo); 612 } finally { 613 analyzer.analyzeIfNeeded(tree, analyzeEnv); 614 } 615 } 616 617 /** Attribute a list of expressions, returning a list of types. 618 */ 619 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 620 ListBuffer<Type> ts = new ListBuffer<>(); 621 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 622 ts.append(attribExpr(l.head, env, pt)); 623 return ts.toList(); 624 } 625 626 /** Attribute a list of statements, returning nothing. 627 */ 628 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 629 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 630 attribStat(l.head, env); 631 } 632 633 /** Attribute the arguments in a method call, returning the method kind. 634 */ 635 KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) { 636 KindSelector kind = initialKind; 637 for (JCExpression arg : trees) { 638 Type argtype; 639 if (allowPoly && deferredAttr.isDeferred(env, arg)) { 640 argtype = deferredAttr.new DeferredType(arg, env); 641 kind = KindSelector.of(KindSelector.POLY, kind); 642 } else { 643 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo)); 644 } 645 argtypes.append(argtype); 646 } 647 return kind; 648 } 649 650 /** Attribute a type argument list, returning a list of types. 651 * Caller is responsible for calling checkRefTypes. 652 */ 653 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 654 ListBuffer<Type> argtypes = new ListBuffer<>(); 655 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 656 argtypes.append(attribType(l.head, env)); 657 return argtypes.toList(); 658 } 659 660 /** Attribute a type argument list, returning a list of types. 661 * Check that all the types are references. 662 */ 663 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 664 List<Type> types = attribAnyTypes(trees, env); 665 return chk.checkRefTypes(trees, types); 666 } 667 668 /** 669 * Attribute type variables (of generic classes or methods). 670 * Compound types are attributed later in attribBounds. 671 * @param typarams the type variables to enter 672 * @param env the current environment 673 */ 674 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) { 675 for (JCTypeParameter tvar : typarams) { 676 dependencies.push(AttributionKind.TVAR, tvar); 677 TypeVar a = (TypeVar)tvar.type; 678 a.tsym.flags_field |= UNATTRIBUTED; 679 a.bound = Type.noType; 680 if (!tvar.bounds.isEmpty()) { 681 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 682 for (JCExpression bound : tvar.bounds.tail) 683 bounds = bounds.prepend(attribType(bound, env)); 684 types.setBounds(a, bounds.reverse()); 685 } else { 686 // if no bounds are given, assume a single bound of 687 // java.lang.Object. 688 types.setBounds(a, List.of(syms.objectType)); 689 } 690 a.tsym.flags_field &= ~UNATTRIBUTED; 691 dependencies.pop(); 692 } 693 for (JCTypeParameter tvar : typarams) { 694 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 695 } 696 } 697 698 /** 699 * Attribute the type references in a list of annotations. 700 */ 701 void attribAnnotationTypes(List<JCAnnotation> annotations, 702 Env<AttrContext> env) { 703 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 704 JCAnnotation a = al.head; 705 attribType(a.annotationType, env); 706 } 707 } 708 709 /** 710 * Attribute a "lazy constant value". 711 * @param env The env for the const value 712 * @param initializer The initializer for the const value 713 * @param type The expected type, or null 714 * @see VarSymbol#setLazyConstValue 715 */ 716 public Object attribLazyConstantValue(Env<AttrContext> env, 717 JCVariableDecl variable, 718 Type type) { 719 720 DiagnosticPosition prevLintPos 721 = deferredLintHandler.setPos(variable.pos()); 722 723 try { 724 Type itype = attribExpr(variable.init, env, type); 725 if (itype.constValue() != null) { 726 return coerce(itype, type).constValue(); 727 } else { 728 return null; 729 } 730 } finally { 731 deferredLintHandler.setPos(prevLintPos); 732 } 733 } 734 735 /** Attribute type reference in an `extends' or `implements' clause. 736 * Supertypes of anonymous inner classes are usually already attributed. 737 * 738 * @param tree The tree making up the type reference. 739 * @param env The environment current at the reference. 740 * @param classExpected true if only a class is expected here. 741 * @param interfaceExpected true if only an interface is expected here. 742 */ 743 Type attribBase(JCTree tree, 744 Env<AttrContext> env, 745 boolean classExpected, 746 boolean interfaceExpected, 747 boolean checkExtensible) { 748 Type t = tree.type != null ? 749 tree.type : 750 attribType(tree, env); 751 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 752 } 753 Type checkBase(Type t, 754 JCTree tree, 755 Env<AttrContext> env, 756 boolean classExpected, 757 boolean interfaceExpected, 758 boolean checkExtensible) { 759 if (t.tsym.isAnonymous()) { 760 log.error(tree.pos(), "cant.inherit.from.anon"); 761 return types.createErrorType(t); 762 } 763 if (t.isErroneous()) 764 return t; 765 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 766 // check that type variable is already visible 767 if (t.getUpperBound() == null) { 768 log.error(tree.pos(), "illegal.forward.ref"); 769 return types.createErrorType(t); 770 } 771 } else { 772 t = chk.checkClassType(tree.pos(), t, checkExtensible); 773 } 774 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 775 log.error(tree.pos(), "intf.expected.here"); 776 // return errType is necessary since otherwise there might 777 // be undetected cycles which cause attribution to loop 778 return types.createErrorType(t); 779 } else if (checkExtensible && 780 classExpected && 781 (t.tsym.flags() & INTERFACE) != 0) { 782 log.error(tree.pos(), "no.intf.expected.here"); 783 return types.createErrorType(t); 784 } 785 if (checkExtensible && 786 ((t.tsym.flags() & FINAL) != 0)) { 787 log.error(tree.pos(), 788 "cant.inherit.from.final", t.tsym); 789 } 790 chk.checkNonCyclic(tree.pos(), t); 791 return t; 792 } 793 794 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 795 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 796 id.type = env.info.scope.owner.enclClass().type; 797 id.sym = env.info.scope.owner.enclClass(); 798 return id.type; 799 } 800 801 public void visitClassDef(JCClassDecl tree) { 802 // Local and anonymous classes have not been entered yet, so we need to 803 // do it now. 804 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) { 805 enter.classEnter(tree, env); 806 } else { 807 // If this class declaration is part of a class level annotation, 808 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in 809 // order to simplify later steps and allow for sensible error 810 // messages. 811 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree)) 812 enter.classEnter(tree, env); 813 } 814 815 ClassSymbol c = tree.sym; 816 if (c == null) { 817 // exit in case something drastic went wrong during enter. 818 result = null; 819 } else { 820 // make sure class has been completed: 821 c.complete(); 822 823 // If this class appears as an anonymous class 824 // in a superclass constructor call where 825 // no explicit outer instance is given, 826 // disable implicit outer instance from being passed. 827 // (This would be an illegal access to "this before super"). 828 if (env.info.isSelfCall && 829 env.tree.hasTag(NEWCLASS) && 830 ((JCNewClass) env.tree).encl == null) 831 { 832 c.flags_field |= NOOUTERTHIS; 833 } 834 attribClass(tree.pos(), c); 835 result = tree.type = c.type; 836 } 837 } 838 839 public void visitMethodDef(JCMethodDecl tree) { 840 MethodSymbol m = tree.sym; 841 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 842 843 Lint lint = env.info.lint.augment(m); 844 Lint prevLint = chk.setLint(lint); 845 MethodSymbol prevMethod = chk.setMethod(m); 846 try { 847 deferredLintHandler.flush(tree.pos()); 848 chk.checkDeprecatedAnnotation(tree.pos(), m); 849 850 851 // Create a new environment with local scope 852 // for attributing the method. 853 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 854 localEnv.info.lint = lint; 855 856 attribStats(tree.typarams, localEnv); 857 858 // If we override any other methods, check that we do so properly. 859 // JLS ??? 860 if (m.isStatic()) { 861 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 862 } else { 863 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 864 } 865 chk.checkOverride(tree, m); 866 867 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 868 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); 869 } 870 871 // Enter all type parameters into the local method scope. 872 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 873 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 874 875 ClassSymbol owner = env.enclClass.sym; 876 if ((owner.flags() & ANNOTATION) != 0 && 877 tree.params.nonEmpty()) 878 log.error(tree.params.head.pos(), 879 "intf.annotation.members.cant.have.params"); 880 881 // Attribute all value parameters. 882 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 883 attribStat(l.head, localEnv); 884 } 885 886 chk.checkVarargsMethodDecl(localEnv, tree); 887 888 // Check that type parameters are well-formed. 889 chk.validate(tree.typarams, localEnv); 890 891 // Check that result type is well-formed. 892 if (tree.restype != null && !tree.restype.type.hasTag(VOID)) 893 chk.validate(tree.restype, localEnv); 894 895 // Check that receiver type is well-formed. 896 if (tree.recvparam != null) { 897 // Use a new environment to check the receiver parameter. 898 // Otherwise I get "might not have been initialized" errors. 899 // Is there a better way? 900 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env); 901 attribType(tree.recvparam, newEnv); 902 chk.validate(tree.recvparam, newEnv); 903 } 904 905 // annotation method checks 906 if ((owner.flags() & ANNOTATION) != 0) { 907 // annotation method cannot have throws clause 908 if (tree.thrown.nonEmpty()) { 909 log.error(tree.thrown.head.pos(), 910 "throws.not.allowed.in.intf.annotation"); 911 } 912 // annotation method cannot declare type-parameters 913 if (tree.typarams.nonEmpty()) { 914 log.error(tree.typarams.head.pos(), 915 "intf.annotation.members.cant.have.type.params"); 916 } 917 // validate annotation method's return type (could be an annotation type) 918 chk.validateAnnotationType(tree.restype); 919 // ensure that annotation method does not clash with members of Object/Annotation 920 chk.validateAnnotationMethod(tree.pos(), m); 921 } 922 923 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 924 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 925 926 if (tree.body == null) { 927 // Empty bodies are only allowed for 928 // abstract, native, or interface methods, or for methods 929 // in a retrofit signature class. 930 if (tree.defaultValue != null) { 931 if ((owner.flags() & ANNOTATION) == 0) 932 log.error(tree.pos(), 933 "default.allowed.in.intf.annotation.member"); 934 } 935 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 && 936 !relax) 937 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 938 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) { 939 if ((owner.flags() & INTERFACE) != 0) { 940 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 941 } else { 942 log.error(tree.pos(), "abstract.meth.cant.have.body"); 943 } 944 } else if ((tree.mods.flags & NATIVE) != 0) { 945 log.error(tree.pos(), "native.meth.cant.have.body"); 946 } else { 947 // Add an implicit super() call unless an explicit call to 948 // super(...) or this(...) is given 949 // or we are compiling class java.lang.Object. 950 if (tree.name == names.init && owner.type != syms.objectType) { 951 JCBlock body = tree.body; 952 if (body.stats.isEmpty() || 953 !TreeInfo.isSelfCall(body.stats.head)) { 954 body.stats = body.stats. 955 prepend(typeEnter.SuperCall(make.at(body.pos), 956 List.<Type>nil(), 957 List.<JCVariableDecl>nil(), 958 false)); 959 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 960 (tree.mods.flags & GENERATEDCONSTR) == 0 && 961 TreeInfo.isSuperCall(body.stats.head)) { 962 // enum constructors are not allowed to call super 963 // directly, so make sure there aren't any super calls 964 // in enum constructors, except in the compiler 965 // generated one. 966 log.error(tree.body.stats.head.pos(), 967 "call.to.super.not.allowed.in.enum.ctor", 968 env.enclClass.sym); 969 } 970 } 971 972 // Attribute all type annotations in the body 973 annotate.annotateTypeLater(tree.body, localEnv, m, null); 974 annotate.flush(); 975 976 // Attribute method body. 977 attribStat(tree.body, localEnv); 978 } 979 980 localEnv.info.scope.leave(); 981 result = tree.type = m.type; 982 } finally { 983 chk.setLint(prevLint); 984 chk.setMethod(prevMethod); 985 } 986 } 987 988 public void visitVarDef(JCVariableDecl tree) { 989 // Local variables have not been entered yet, so we need to do it now: 990 if (env.info.scope.owner.kind == MTH) { 991 if (tree.sym != null) { 992 // parameters have already been entered 993 env.info.scope.enter(tree.sym); 994 } else { 995 try { 996 annotate.enterStart(); 997 memberEnter.memberEnter(tree, env); 998 } finally { 999 annotate.enterDone(); 1000 } 1001 } 1002 } else { 1003 if (tree.init != null) { 1004 // Field initializer expression need to be entered. 1005 annotate.annotateTypeLater(tree.init, env, tree.sym, tree.pos()); 1006 annotate.flush(); 1007 } 1008 } 1009 1010 VarSymbol v = tree.sym; 1011 Lint lint = env.info.lint.augment(v); 1012 Lint prevLint = chk.setLint(lint); 1013 1014 // Check that the variable's declared type is well-formed. 1015 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) && 1016 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT && 1017 (tree.sym.flags() & PARAMETER) != 0; 1018 chk.validate(tree.vartype, env, !isImplicitLambdaParameter); 1019 1020 try { 1021 v.getConstValue(); // ensure compile-time constant initializer is evaluated 1022 deferredLintHandler.flush(tree.pos()); 1023 chk.checkDeprecatedAnnotation(tree.pos(), v); 1024 1025 if (tree.init != null) { 1026 if ((v.flags_field & FINAL) == 0 || 1027 !memberEnter.needsLazyConstValue(tree.init)) { 1028 // Not a compile-time constant 1029 // Attribute initializer in a new environment 1030 // with the declared variable as owner. 1031 // Check that initializer conforms to variable's declared type. 1032 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1033 initEnv.info.lint = lint; 1034 // In order to catch self-references, we set the variable's 1035 // declaration position to maximal possible value, effectively 1036 // marking the variable as undefined. 1037 initEnv.info.enclVar = v; 1038 attribExpr(tree.init, initEnv, v.type); 1039 } 1040 } 1041 result = tree.type = v.type; 1042 } 1043 finally { 1044 chk.setLint(prevLint); 1045 } 1046 } 1047 1048 public void visitSkip(JCSkip tree) { 1049 result = null; 1050 } 1051 1052 public void visitBlock(JCBlock tree) { 1053 if (env.info.scope.owner.kind == TYP) { 1054 // Block is a static or instance initializer; 1055 // let the owner of the environment be a freshly 1056 // created BLOCK-method. 1057 Symbol fakeOwner = 1058 new MethodSymbol(tree.flags | BLOCK | 1059 env.info.scope.owner.flags() & STRICTFP, names.empty, null, 1060 env.info.scope.owner); 1061 final Env<AttrContext> localEnv = 1062 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner))); 1063 1064 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 1065 // Attribute all type annotations in the block 1066 annotate.annotateTypeLater(tree, localEnv, localEnv.info.scope.owner, null); 1067 annotate.flush(); 1068 attribStats(tree.stats, localEnv); 1069 1070 { 1071 // Store init and clinit type annotations with the ClassSymbol 1072 // to allow output in Gen.normalizeDefs. 1073 ClassSymbol cs = (ClassSymbol)env.info.scope.owner; 1074 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes(); 1075 if ((tree.flags & STATIC) != 0) { 1076 cs.appendClassInitTypeAttributes(tas); 1077 } else { 1078 cs.appendInitTypeAttributes(tas); 1079 } 1080 } 1081 } else { 1082 // Create a new local environment with a local scope. 1083 Env<AttrContext> localEnv = 1084 env.dup(tree, env.info.dup(env.info.scope.dup())); 1085 try { 1086 attribStats(tree.stats, localEnv); 1087 } finally { 1088 localEnv.info.scope.leave(); 1089 } 1090 } 1091 result = null; 1092 } 1093 1094 public void visitDoLoop(JCDoWhileLoop tree) { 1095 attribStat(tree.body, env.dup(tree)); 1096 attribExpr(tree.cond, env, syms.booleanType); 1097 result = null; 1098 } 1099 1100 public void visitWhileLoop(JCWhileLoop tree) { 1101 attribExpr(tree.cond, env, syms.booleanType); 1102 attribStat(tree.body, env.dup(tree)); 1103 result = null; 1104 } 1105 1106 public void visitForLoop(JCForLoop tree) { 1107 Env<AttrContext> loopEnv = 1108 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1109 try { 1110 attribStats(tree.init, loopEnv); 1111 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 1112 loopEnv.tree = tree; // before, we were not in loop! 1113 attribStats(tree.step, loopEnv); 1114 attribStat(tree.body, loopEnv); 1115 result = null; 1116 } 1117 finally { 1118 loopEnv.info.scope.leave(); 1119 } 1120 } 1121 1122 public void visitForeachLoop(JCEnhancedForLoop tree) { 1123 Env<AttrContext> loopEnv = 1124 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1125 try { 1126 //the Formal Parameter of a for-each loop is not in the scope when 1127 //attributing the for-each expression; we mimick this by attributing 1128 //the for-each expression first (against original scope). 1129 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); 1130 attribStat(tree.var, loopEnv); 1131 chk.checkNonVoid(tree.pos(), exprType); 1132 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1133 if (elemtype == null) { 1134 // or perhaps expr implements Iterable<T>? 1135 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1136 if (base == null) { 1137 log.error(tree.expr.pos(), 1138 "foreach.not.applicable.to.type", 1139 exprType, 1140 diags.fragment("type.req.array.or.iterable")); 1141 elemtype = types.createErrorType(exprType); 1142 } else { 1143 List<Type> iterableParams = base.allparams(); 1144 elemtype = iterableParams.isEmpty() 1145 ? syms.objectType 1146 : types.wildUpperBound(iterableParams.head); 1147 } 1148 } 1149 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1150 loopEnv.tree = tree; // before, we were not in loop! 1151 attribStat(tree.body, loopEnv); 1152 result = null; 1153 } 1154 finally { 1155 loopEnv.info.scope.leave(); 1156 } 1157 } 1158 1159 public void visitLabelled(JCLabeledStatement tree) { 1160 // Check that label is not used in an enclosing statement 1161 Env<AttrContext> env1 = env; 1162 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1163 if (env1.tree.hasTag(LABELLED) && 1164 ((JCLabeledStatement) env1.tree).label == tree.label) { 1165 log.error(tree.pos(), "label.already.in.use", 1166 tree.label); 1167 break; 1168 } 1169 env1 = env1.next; 1170 } 1171 1172 attribStat(tree.body, env.dup(tree)); 1173 result = null; 1174 } 1175 1176 public void visitSwitch(JCSwitch tree) { 1177 Type seltype = attribExpr(tree.selector, env); 1178 1179 Env<AttrContext> switchEnv = 1180 env.dup(tree, env.info.dup(env.info.scope.dup())); 1181 1182 try { 1183 1184 boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0; 1185 boolean stringSwitch = false; 1186 if (types.isSameType(seltype, syms.stringType)) { 1187 if (allowStringsInSwitch) { 1188 stringSwitch = true; 1189 } else { 1190 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 1191 } 1192 } 1193 if (!enumSwitch && !stringSwitch) 1194 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 1195 1196 // Attribute all cases and 1197 // check that there are no duplicate case labels or default clauses. 1198 Set<Object> labels = new HashSet<>(); // The set of case labels. 1199 boolean hasDefault = false; // Is there a default label? 1200 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 1201 JCCase c = l.head; 1202 if (c.pat != null) { 1203 if (enumSwitch) { 1204 Symbol sym = enumConstant(c.pat, seltype); 1205 if (sym == null) { 1206 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); 1207 } else if (!labels.add(sym)) { 1208 log.error(c.pos(), "duplicate.case.label"); 1209 } 1210 } else { 1211 Type pattype = attribExpr(c.pat, switchEnv, seltype); 1212 if (!pattype.hasTag(ERROR)) { 1213 if (pattype.constValue() == null) { 1214 log.error(c.pat.pos(), 1215 (stringSwitch ? "string.const.req" : "const.expr.req")); 1216 } else if (!labels.add(pattype.constValue())) { 1217 log.error(c.pos(), "duplicate.case.label"); 1218 } 1219 } 1220 } 1221 } else if (hasDefault) { 1222 log.error(c.pos(), "duplicate.default.label"); 1223 } else { 1224 hasDefault = true; 1225 } 1226 Env<AttrContext> caseEnv = 1227 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 1228 try { 1229 attribStats(c.stats, caseEnv); 1230 } finally { 1231 caseEnv.info.scope.leave(); 1232 addVars(c.stats, switchEnv.info.scope); 1233 } 1234 } 1235 1236 result = null; 1237 } 1238 finally { 1239 switchEnv.info.scope.leave(); 1240 } 1241 } 1242 // where 1243 /** Add any variables defined in stats to the switch scope. */ 1244 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) { 1245 for (;stats.nonEmpty(); stats = stats.tail) { 1246 JCTree stat = stats.head; 1247 if (stat.hasTag(VARDEF)) 1248 switchScope.enter(((JCVariableDecl) stat).sym); 1249 } 1250 } 1251 // where 1252 /** Return the selected enumeration constant symbol, or null. */ 1253 private Symbol enumConstant(JCTree tree, Type enumType) { 1254 if (tree.hasTag(IDENT)) { 1255 JCIdent ident = (JCIdent)tree; 1256 Name name = ident.name; 1257 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) { 1258 if (sym.kind == VAR) { 1259 Symbol s = ident.sym = sym; 1260 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1261 ident.type = s.type; 1262 return ((s.flags_field & Flags.ENUM) == 0) 1263 ? null : s; 1264 } 1265 } 1266 } 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 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 = operators.resolveUnary(arg, optag, arg.type); 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.isIntersection() ? 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 = types.makeIntersectionType(supertypes.toList()); 2388 notionalIntf.allparams_field = targs.toList(); 2389 notionalIntf.tsym.flags_field |= INTERFACE; 2390 return notionalIntf.tsym; 2391 } 2392 2393 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) { 2394 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr", 2395 diags.fragment(key, args))); 2396 } 2397 }; 2398 2399 private Type fallbackDescriptorType(JCExpression tree) { 2400 switch (tree.getTag()) { 2401 case LAMBDA: 2402 JCLambda lambda = (JCLambda)tree; 2403 List<Type> argtypes = List.nil(); 2404 for (JCVariableDecl param : lambda.params) { 2405 argtypes = param.vartype != null ? 2406 argtypes.append(param.vartype.type) : 2407 argtypes.append(syms.errType); 2408 } 2409 return new MethodType(argtypes, Type.recoveryType, 2410 List.of(syms.throwableType), syms.methodClass); 2411 case REFERENCE: 2412 return new MethodType(List.<Type>nil(), Type.recoveryType, 2413 List.of(syms.throwableType), syms.methodClass); 2414 default: 2415 Assert.error("Cannot get here!"); 2416 } 2417 return null; 2418 } 2419 2420 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2421 final InferenceContext inferenceContext, final Type... ts) { 2422 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 2423 } 2424 2425 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2426 final InferenceContext inferenceContext, final List<Type> ts) { 2427 if (inferenceContext.free(ts)) { 2428 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { 2429 @Override 2430 public void typesInferred(InferenceContext inferenceContext) { 2431 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts)); 2432 } 2433 }); 2434 } else { 2435 for (Type t : ts) { 2436 rs.checkAccessibleType(env, t); 2437 } 2438 } 2439 } 2440 2441 /** 2442 * Lambda/method reference have a special check context that ensures 2443 * that i.e. a lambda return type is compatible with the expected 2444 * type according to both the inherited context and the assignment 2445 * context. 2446 */ 2447 class FunctionalReturnContext extends Check.NestedCheckContext { 2448 2449 FunctionalReturnContext(CheckContext enclosingContext) { 2450 super(enclosingContext); 2451 } 2452 2453 @Override 2454 public boolean compatible(Type found, Type req, Warner warn) { 2455 //return type must be compatible in both current context and assignment context 2456 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn); 2457 } 2458 2459 @Override 2460 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2461 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); 2462 } 2463 } 2464 2465 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 2466 2467 JCExpression expr; 2468 2469 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 2470 super(enclosingContext); 2471 this.expr = expr; 2472 } 2473 2474 @Override 2475 public boolean compatible(Type found, Type req, Warner warn) { 2476 //a void return is compatible with an expression statement lambda 2477 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) || 2478 super.compatible(found, req, warn); 2479 } 2480 } 2481 2482 /** 2483 * Lambda compatibility. Check that given return types, thrown types, parameter types 2484 * are compatible with the expected functional interface descriptor. This means that: 2485 * (i) parameter types must be identical to those of the target descriptor; (ii) return 2486 * types must be compatible with the return type of the expected descriptor. 2487 */ 2488 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) { 2489 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); 2490 2491 //return values have already been checked - but if lambda has no return 2492 //values, we must ensure that void/value compatibility is correct; 2493 //this amounts at checking that, if a lambda body can complete normally, 2494 //the descriptor's return type must be void 2495 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 2496 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 2497 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", 2498 diags.fragment("missing.ret.val", returnType))); 2499 } 2500 2501 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes()); 2502 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 2503 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); 2504 } 2505 } 2506 2507 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a 2508 * static field and that lambda has type annotations, these annotations will 2509 * also be stored at these fake clinit methods. 2510 * 2511 * LambdaToMethod also use fake clinit methods so they can be reused. 2512 * Also as LTM is a phase subsequent to attribution, the methods from 2513 * clinits can be safely removed by LTM to save memory. 2514 */ 2515 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>(); 2516 2517 public MethodSymbol removeClinit(ClassSymbol sym) { 2518 return clinits.remove(sym); 2519 } 2520 2521 /* This method returns an environment to be used to attribute a lambda 2522 * expression. 2523 * 2524 * The owner of this environment is a method symbol. If the current owner 2525 * is not a method, for example if the lambda is used to initialize 2526 * a field, then if the field is: 2527 * 2528 * - an instance field, we use the first constructor. 2529 * - a static field, we create a fake clinit method. 2530 */ 2531 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 2532 Env<AttrContext> lambdaEnv; 2533 Symbol owner = env.info.scope.owner; 2534 if (owner.kind == VAR && owner.owner.kind == TYP) { 2535 //field initializer 2536 ClassSymbol enclClass = owner.enclClass(); 2537 Symbol newScopeOwner = env.info.scope.owner; 2538 /* if the field isn't static, then we can get the first constructor 2539 * and use it as the owner of the environment. This is what 2540 * LTM code is doing to look for type annotations so we are fine. 2541 */ 2542 if ((owner.flags() & STATIC) == 0) { 2543 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) { 2544 newScopeOwner = s; 2545 break; 2546 } 2547 } else { 2548 /* if the field is static then we need to create a fake clinit 2549 * method, this method can later be reused by LTM. 2550 */ 2551 MethodSymbol clinit = clinits.get(enclClass); 2552 if (clinit == null) { 2553 Type clinitType = new MethodType(List.<Type>nil(), 2554 syms.voidType, List.<Type>nil(), syms.methodClass); 2555 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE, 2556 names.clinit, clinitType, enclClass); 2557 clinit.params = List.<VarSymbol>nil(); 2558 clinits.put(enclClass, clinit); 2559 } 2560 newScopeOwner = clinit; 2561 } 2562 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner))); 2563 } else { 2564 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 2565 } 2566 return lambdaEnv; 2567 } 2568 2569 @Override 2570 public void visitReference(final JCMemberReference that) { 2571 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2572 if (pt().hasTag(NONE)) { 2573 //method reference only allowed in assignment or method invocation/cast context 2574 log.error(that.pos(), "unexpected.mref"); 2575 } 2576 result = that.type = types.createErrorType(pt()); 2577 return; 2578 } 2579 final Env<AttrContext> localEnv = env.dup(that); 2580 try { 2581 //attribute member reference qualifier - if this is a constructor 2582 //reference, the expected kind must be a type 2583 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); 2584 2585 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 2586 exprType = chk.checkConstructorRefType(that.expr, exprType); 2587 if (!exprType.isErroneous() && 2588 exprType.isRaw() && 2589 that.typeargs != null) { 2590 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2591 diags.fragment("mref.infer.and.explicit.params")); 2592 exprType = types.createErrorType(exprType); 2593 } 2594 } 2595 2596 if (exprType.isErroneous()) { 2597 //if the qualifier expression contains problems, 2598 //give up attribution of method reference 2599 result = that.type = exprType; 2600 return; 2601 } 2602 2603 if (TreeInfo.isStaticSelector(that.expr, names)) { 2604 //if the qualifier is a type, validate it; raw warning check is 2605 //omitted as we don't know at this stage as to whether this is a 2606 //raw selector (because of inference) 2607 chk.validate(that.expr, env, false); 2608 } 2609 2610 //attrib type-arguments 2611 List<Type> typeargtypes = List.nil(); 2612 if (that.typeargs != null) { 2613 typeargtypes = attribTypes(that.typeargs, localEnv); 2614 } 2615 2616 Type desc; 2617 Type currentTarget = pt(); 2618 boolean isTargetSerializable = 2619 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2620 isSerializable(currentTarget); 2621 if (currentTarget != Type.recoveryType) { 2622 currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that)); 2623 desc = types.findDescriptorType(currentTarget); 2624 } else { 2625 currentTarget = Type.recoveryType; 2626 desc = fallbackDescriptorType(that); 2627 } 2628 2629 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext); 2630 List<Type> argtypes = desc.getParameterTypes(); 2631 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck; 2632 2633 if (resultInfo.checkContext.inferenceContext().free(argtypes)) { 2634 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); 2635 } 2636 2637 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null; 2638 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save(); 2639 try { 2640 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type, 2641 that.name, argtypes, typeargtypes, referenceCheck, 2642 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser); 2643 } finally { 2644 resultInfo.checkContext.inferenceContext().rollback(saved_undet); 2645 } 2646 2647 Symbol refSym = refResult.fst; 2648 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 2649 2650 if (refSym.kind != MTH) { 2651 boolean targetError; 2652 switch (refSym.kind) { 2653 case ABSENT_MTH: 2654 targetError = false; 2655 break; 2656 case WRONG_MTH: 2657 case WRONG_MTHS: 2658 case AMBIGUOUS: 2659 case HIDDEN: 2660 case MISSING_ENCL: 2661 case STATICERR: 2662 targetError = true; 2663 break; 2664 default: 2665 Assert.error("unexpected result kind " + refSym.kind); 2666 targetError = false; 2667 } 2668 2669 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 2670 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 2671 2672 JCDiagnostic.DiagnosticType diagKind = targetError ? 2673 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; 2674 2675 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, 2676 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); 2677 2678 if (targetError && currentTarget == Type.recoveryType) { 2679 //a target error doesn't make sense during recovery stage 2680 //as we don't know what actual parameter types are 2681 result = that.type = currentTarget; 2682 return; 2683 } else { 2684 if (targetError) { 2685 resultInfo.checkContext.report(that, diag); 2686 } else { 2687 log.report(diag); 2688 } 2689 result = that.type = types.createErrorType(currentTarget); 2690 return; 2691 } 2692 } 2693 2694 that.sym = refSym.baseSymbol(); 2695 that.kind = lookupHelper.referenceKind(that.sym); 2696 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); 2697 2698 if (desc.getReturnType() == Type.recoveryType) { 2699 // stop here 2700 result = that.type = currentTarget; 2701 return; 2702 } 2703 2704 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 2705 2706 if (that.getMode() == ReferenceMode.INVOKE && 2707 TreeInfo.isStaticSelector(that.expr, names) && 2708 that.kind.isUnbound() && 2709 !desc.getParameterTypes().head.isParameterized()) { 2710 chk.checkRaw(that.expr, localEnv); 2711 } 2712 2713 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 2714 exprType.getTypeArguments().nonEmpty()) { 2715 //static ref with class type-args 2716 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2717 diags.fragment("static.mref.with.targs")); 2718 result = that.type = types.createErrorType(currentTarget); 2719 return; 2720 } 2721 2722 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { 2723 // Check that super-qualified symbols are not abstract (JLS) 2724 rs.checkNonAbstract(that.pos(), that.sym); 2725 } 2726 2727 if (isTargetSerializable) { 2728 chk.checkElemAccessFromSerializableLambda(that); 2729 } 2730 } 2731 2732 ResultInfo checkInfo = 2733 resultInfo.dup(newMethodTemplate( 2734 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 2735 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes), 2736 new FunctionalReturnContext(resultInfo.checkContext)); 2737 2738 Type refType = checkId(noCheckTree, lookupHelper.site, refSym, localEnv, checkInfo); 2739 2740 if (that.kind.isUnbound() && 2741 resultInfo.checkContext.inferenceContext().free(argtypes.head)) { 2742 //re-generate inference constraints for unbound receiver 2743 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) { 2744 //cannot happen as this has already been checked - we just need 2745 //to regenerate the inference constraints, as that has been lost 2746 //as a result of the call to inferenceContext.save() 2747 Assert.error("Can't get here"); 2748 } 2749 } 2750 2751 if (!refType.isErroneous()) { 2752 refType = types.createMethodTypeWithReturn(refType, 2753 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 2754 } 2755 2756 //go ahead with standard method reference compatibility check - note that param check 2757 //is a no-op (as this has been taken care during method applicability) 2758 boolean isSpeculativeRound = 2759 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2760 2761 that.type = currentTarget; //avoids recovery at this stage 2762 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 2763 if (!isSpeculativeRound) { 2764 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget); 2765 } 2766 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2767 } catch (Types.FunctionDescriptorLookupError ex) { 2768 JCDiagnostic cause = ex.getDiagnostic(); 2769 resultInfo.checkContext.report(that, cause); 2770 result = that.type = types.createErrorType(pt()); 2771 return; 2772 } 2773 } 2774 //where 2775 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { 2776 //if this is a constructor reference, the expected kind must be a type 2777 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? 2778 KindSelector.VAL_TYP : KindSelector.TYP, 2779 Type.noType); 2780 } 2781 2782 2783 @SuppressWarnings("fallthrough") 2784 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 2785 InferenceContext inferenceContext = checkContext.inferenceContext(); 2786 Type returnType = 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 } else { 2816 if (inferenceContext.free(refType)) { 2817 // we need to wait for inference to finish and then replace inference vars in the referent type 2818 inferenceContext.addFreeTypeListener(List.of(refType), 2819 instantiatedContext -> { 2820 tree.referentType = instantiatedContext.asInstType(refType); 2821 }); 2822 } else { 2823 tree.referentType = refType; 2824 } 2825 } 2826 2827 if (!speculativeAttr) { 2828 List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes()); 2829 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { 2830 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); 2831 } 2832 } 2833 } 2834 2835 /** 2836 * Set functional type info on the underlying AST. Note: as the target descriptor 2837 * might contain inference variables, we might need to register an hook in the 2838 * current inference context. 2839 */ 2840 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr, 2841 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) { 2842 if (checkContext.inferenceContext().free(descriptorType)) { 2843 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() { 2844 public void typesInferred(InferenceContext inferenceContext) { 2845 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType), 2846 inferenceContext.asInstType(primaryTarget), checkContext); 2847 } 2848 }); 2849 } else { 2850 ListBuffer<Type> targets = new ListBuffer<>(); 2851 if (pt.hasTag(CLASS)) { 2852 if (pt.isCompound()) { 2853 targets.append(types.removeWildcards(primaryTarget)); //this goes first 2854 for (Type t : ((IntersectionClassType)pt()).interfaces_field) { 2855 if (t != primaryTarget) { 2856 targets.append(types.removeWildcards(t)); 2857 } 2858 } 2859 } else { 2860 targets.append(types.removeWildcards(primaryTarget)); 2861 } 2862 } 2863 fExpr.targets = targets.toList(); 2864 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2865 pt != Type.recoveryType) { 2866 //check that functional interface class is well-formed 2867 try { 2868 /* Types.makeFunctionalInterfaceClass() may throw an exception 2869 * when it's executed post-inference. See the listener code 2870 * above. 2871 */ 2872 ClassSymbol csym = types.makeFunctionalInterfaceClass(env, 2873 names.empty, List.of(fExpr.targets.head), ABSTRACT); 2874 if (csym != null) { 2875 chk.checkImplementations(env.tree, csym, csym); 2876 try { 2877 //perform an additional functional interface check on the synthetic class, 2878 //as there may be spurious errors for raw targets - because of existing issues 2879 //with membership and inheritance (see JDK-8074570). 2880 csym.flags_field |= INTERFACE; 2881 types.findDescriptorType(csym.type); 2882 } catch (FunctionDescriptorLookupError err) { 2883 resultInfo.checkContext.report(fExpr, 2884 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head))); 2885 } 2886 } 2887 } catch (Types.FunctionDescriptorLookupError ex) { 2888 JCDiagnostic cause = ex.getDiagnostic(); 2889 resultInfo.checkContext.report(env.tree, cause); 2890 } 2891 } 2892 } 2893 } 2894 2895 public void visitParens(JCParens tree) { 2896 Type owntype = attribTree(tree.expr, env, resultInfo); 2897 result = check(tree, owntype, pkind(), resultInfo); 2898 Symbol sym = TreeInfo.symbol(tree); 2899 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK)) 2900 log.error(tree.pos(), "illegal.start.of.type"); 2901 } 2902 2903 public void visitAssign(JCAssign tree) { 2904 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo); 2905 Type capturedType = capture(owntype); 2906 attribExpr(tree.rhs, env, owntype); 2907 result = check(tree, capturedType, KindSelector.VAL, resultInfo); 2908 } 2909 2910 public void visitAssignop(JCAssignOp tree) { 2911 // Attribute arguments. 2912 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo); 2913 Type operand = attribExpr(tree.rhs, env); 2914 // Find operator. 2915 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand); 2916 if (operator.kind == MTH && 2917 !owntype.isErroneous() && 2918 !operand.isErroneous()) { 2919 chk.checkDivZero(tree.rhs.pos(), operator, operand); 2920 chk.checkCastable(tree.rhs.pos(), 2921 operator.type.getReturnType(), 2922 owntype); 2923 } 2924 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2925 } 2926 2927 public void visitUnary(JCUnary tree) { 2928 // Attribute arguments. 2929 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 2930 ? attribTree(tree.arg, env, varAssignmentInfo) 2931 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 2932 2933 // Find operator. 2934 Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); 2935 Type owntype = types.createErrorType(tree.type); 2936 if (operator.kind == MTH && 2937 !argtype.isErroneous()) { 2938 owntype = (tree.getTag().isIncOrDecUnaryOp()) 2939 ? tree.arg.type 2940 : operator.type.getReturnType(); 2941 int opc = ((OperatorSymbol)operator).opcode; 2942 2943 // If the argument is constant, fold it. 2944 if (argtype.constValue() != null) { 2945 Type ctype = cfolder.fold1(opc, argtype); 2946 if (ctype != null) { 2947 owntype = cfolder.coerce(ctype, owntype); 2948 } 2949 } 2950 } 2951 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2952 } 2953 2954 public void visitBinary(JCBinary tree) { 2955 // Attribute arguments. 2956 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 2957 Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env)); 2958 // Find operator. 2959 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); 2960 Type owntype = types.createErrorType(tree.type); 2961 if (operator.kind == MTH && 2962 !left.isErroneous() && 2963 !right.isErroneous()) { 2964 owntype = operator.type.getReturnType(); 2965 int opc = ((OperatorSymbol)operator).opcode; 2966 // If both arguments are constants, fold them. 2967 if (left.constValue() != null && right.constValue() != null) { 2968 Type ctype = cfolder.fold2(opc, left, right); 2969 if (ctype != null) { 2970 owntype = cfolder.coerce(ctype, owntype); 2971 } 2972 } 2973 2974 // Check that argument types of a reference ==, != are 2975 // castable to each other, (JLS 15.21). Note: unboxing 2976 // comparisons will not have an acmp* opc at this point. 2977 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 2978 if (!types.isCastable(left, right, 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 site = types.skipTypeVars(site, true); 3188 } 3189 3190 // If that symbol is a variable, ... 3191 if (sym.kind == VAR) { 3192 VarSymbol v = (VarSymbol)sym; 3193 3194 // ..., evaluate its initializer, if it has one, and check for 3195 // illegal forward reference. 3196 checkInit(tree, env, v, true); 3197 3198 // If we are expecting a variable (as opposed to a value), check 3199 // that the variable is assignable in the current environment. 3200 if (KindSelector.ASG.subset(pkind())) 3201 checkAssignable(tree.pos(), v, tree.selected, env); 3202 } 3203 3204 if (sitesym != null && 3205 sitesym.kind == VAR && 3206 ((VarSymbol)sitesym).isResourceVariable() && 3207 sym.kind == MTH && 3208 sym.name.equals(names.close) && 3209 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 3210 env.info.lint.isEnabled(LintCategory.TRY)) { 3211 log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); 3212 } 3213 3214 // Disallow selecting a type from an expression 3215 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) { 3216 tree.type = check(tree.selected, pt(), 3217 sitesym == null ? 3218 KindSelector.VAL : sitesym.kind.toSelector(), 3219 new ResultInfo(KindSelector.TYP_PCK, pt())); 3220 } 3221 3222 if (isType(sitesym)) { 3223 if (sym.name == names._this) { 3224 // If `C' is the currently compiled class, check that 3225 // C.this' does not appear in a call to a super(...) 3226 if (env.info.isSelfCall && 3227 site.tsym == env.enclClass.sym) { 3228 chk.earlyRefError(tree.pos(), sym); 3229 } 3230 } else { 3231 // Check if type-qualified fields or methods are static (JLS) 3232 if ((sym.flags() & STATIC) == 0 && 3233 !env.next.tree.hasTag(REFERENCE) && 3234 sym.name != names._super && 3235 (sym.kind == VAR || sym.kind == MTH)) { 3236 rs.accessBase(rs.new StaticError(sym), 3237 tree.pos(), site, sym.name, true); 3238 } 3239 } 3240 if (!allowStaticInterfaceMethods && sitesym.isInterface() && 3241 sym.isStatic() && sym.kind == MTH) { 3242 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName); 3243 } 3244 } else if (sym.kind != ERR && 3245 (sym.flags() & STATIC) != 0 && 3246 sym.name != names._class) { 3247 // If the qualified item is not a type and the selected item is static, report 3248 // a warning. Make allowance for the class of an array type e.g. Object[].class) 3249 chk.warnStatic(tree, "static.not.qualified.by.type", 3250 sym.kind.kindName(), sym.owner); 3251 } 3252 3253 // If we are selecting an instance member via a `super', ... 3254 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 3255 3256 // Check that super-qualified symbols are not abstract (JLS) 3257 rs.checkNonAbstract(tree.pos(), sym); 3258 3259 if (site.isRaw()) { 3260 // Determine argument types for site. 3261 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 3262 if (site1 != null) site = site1; 3263 } 3264 } 3265 3266 if (env.info.isSerializable) { 3267 chk.checkElemAccessFromSerializableLambda(tree); 3268 } 3269 3270 env.info.selectSuper = selectSuperPrev; 3271 result = checkId(tree, site, sym, env, resultInfo); 3272 } 3273 //where 3274 /** Determine symbol referenced by a Select expression, 3275 * 3276 * @param tree The select tree. 3277 * @param site The type of the selected expression, 3278 * @param env The current environment. 3279 * @param resultInfo The current result. 3280 */ 3281 private Symbol selectSym(JCFieldAccess tree, 3282 Symbol location, 3283 Type site, 3284 Env<AttrContext> env, 3285 ResultInfo resultInfo) { 3286 DiagnosticPosition pos = tree.pos(); 3287 Name name = tree.name; 3288 switch (site.getTag()) { 3289 case PACKAGE: 3290 return rs.accessBase( 3291 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), 3292 pos, location, site, name, true); 3293 case ARRAY: 3294 case CLASS: 3295 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 3296 return rs.resolveQualifiedMethod( 3297 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 3298 } else if (name == names._this || name == names._super) { 3299 return rs.resolveSelf(pos, env, site.tsym, name); 3300 } else if (name == names._class) { 3301 // In this case, we have already made sure in 3302 // visitSelect that qualifier expression is a type. 3303 Type t = syms.classType; 3304 List<Type> typeargs = List.of(types.erasure(site)); 3305 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 3306 return new VarSymbol( 3307 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3308 } else { 3309 // We are seeing a plain identifier as selector. 3310 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); 3311 sym = rs.accessBase(sym, pos, location, site, name, true); 3312 return sym; 3313 } 3314 case WILDCARD: 3315 throw new AssertionError(tree); 3316 case TYPEVAR: 3317 // Normally, site.getUpperBound() shouldn't be null. 3318 // It should only happen during memberEnter/attribBase 3319 // when determining the super type which *must* beac 3320 // done before attributing the type variables. In 3321 // other words, we are seeing this illegal program: 3322 // class B<T> extends A<T.foo> {} 3323 Symbol sym = (site.getUpperBound() != null) 3324 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 3325 : null; 3326 if (sym == null) { 3327 log.error(pos, "type.var.cant.be.deref"); 3328 return syms.errSymbol; 3329 } else { 3330 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 3331 rs.new AccessError(env, site, sym) : 3332 sym; 3333 rs.accessBase(sym2, pos, location, site, name, true); 3334 return sym; 3335 } 3336 case ERROR: 3337 // preserve identifier names through errors 3338 return types.createErrorType(name, site.tsym, site).tsym; 3339 default: 3340 // The qualifier expression is of a primitive type -- only 3341 // .class is allowed for these. 3342 if (name == names._class) { 3343 // In this case, we have already made sure in Select that 3344 // qualifier expression is a type. 3345 Type t = syms.classType; 3346 Type arg = types.boxedClass(site).type; 3347 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 3348 return new VarSymbol( 3349 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3350 } else { 3351 log.error(pos, "cant.deref", site); 3352 return syms.errSymbol; 3353 } 3354 } 3355 } 3356 3357 /** Determine type of identifier or select expression and check that 3358 * (1) the referenced symbol is not deprecated 3359 * (2) the symbol's type is safe (@see checkSafe) 3360 * (3) if symbol is a variable, check that its type and kind are 3361 * compatible with the prototype and protokind. 3362 * (4) if symbol is an instance field of a raw type, 3363 * which is being assigned to, issue an unchecked warning if its 3364 * type changes under erasure. 3365 * (5) if symbol is an instance method of a raw type, issue an 3366 * unchecked warning if its argument types change under erasure. 3367 * If checks succeed: 3368 * If symbol is a constant, return its constant type 3369 * else if symbol is a method, return its result type 3370 * otherwise return its type. 3371 * Otherwise return errType. 3372 * 3373 * @param tree The syntax tree representing the identifier 3374 * @param site If this is a select, the type of the selected 3375 * expression, otherwise the type of the current class. 3376 * @param sym The symbol representing the identifier. 3377 * @param env The current environment. 3378 * @param resultInfo The expected result 3379 */ 3380 Type checkId(JCTree tree, 3381 Type site, 3382 Symbol sym, 3383 Env<AttrContext> env, 3384 ResultInfo resultInfo) { 3385 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 3386 checkMethodId(tree, site, sym, env, resultInfo) : 3387 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3388 } 3389 3390 Type checkMethodId(JCTree tree, 3391 Type site, 3392 Symbol sym, 3393 Env<AttrContext> env, 3394 ResultInfo resultInfo) { 3395 boolean isPolymorhicSignature = 3396 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0; 3397 return isPolymorhicSignature ? 3398 checkSigPolyMethodId(tree, site, sym, env, resultInfo) : 3399 checkMethodIdInternal(tree, site, sym, env, resultInfo); 3400 } 3401 3402 Type checkSigPolyMethodId(JCTree tree, 3403 Type site, 3404 Symbol sym, 3405 Env<AttrContext> env, 3406 ResultInfo resultInfo) { 3407 //recover original symbol for signature polymorphic methods 3408 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); 3409 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; 3410 return sym.type; 3411 } 3412 3413 Type checkMethodIdInternal(JCTree tree, 3414 Type site, 3415 Symbol sym, 3416 Env<AttrContext> env, 3417 ResultInfo resultInfo) { 3418 if (resultInfo.pkind.contains(KindSelector.POLY)) { 3419 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); 3420 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); 3421 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3422 return owntype; 3423 } else { 3424 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3425 } 3426 } 3427 3428 Type checkIdInternal(JCTree tree, 3429 Type site, 3430 Symbol sym, 3431 Type pt, 3432 Env<AttrContext> env, 3433 ResultInfo resultInfo) { 3434 if (pt.isErroneous()) { 3435 return types.createErrorType(site); 3436 } 3437 Type owntype; // The computed type of this identifier occurrence. 3438 switch (sym.kind) { 3439 case TYP: 3440 // For types, the computed type equals the symbol's type, 3441 // except for two situations: 3442 owntype = sym.type; 3443 if (owntype.hasTag(CLASS)) { 3444 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 3445 Type ownOuter = owntype.getEnclosingType(); 3446 3447 // (a) If the symbol's type is parameterized, erase it 3448 // because no type parameters were given. 3449 // We recover generic outer type later in visitTypeApply. 3450 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 3451 owntype = types.erasure(owntype); 3452 } 3453 3454 // (b) If the symbol's type is an inner class, then 3455 // we have to interpret its outer type as a superclass 3456 // of the site type. Example: 3457 // 3458 // class Tree<A> { class Visitor { ... } } 3459 // class PointTree extends Tree<Point> { ... } 3460 // ...PointTree.Visitor... 3461 // 3462 // Then the type of the last expression above is 3463 // Tree<Point>.Visitor. 3464 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 3465 Type normOuter = site; 3466 if (normOuter.hasTag(CLASS)) { 3467 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 3468 } 3469 if (normOuter == null) // perhaps from an import 3470 normOuter = types.erasure(ownOuter); 3471 if (normOuter != ownOuter) 3472 owntype = new ClassType( 3473 normOuter, List.<Type>nil(), owntype.tsym, 3474 owntype.getMetadata()); 3475 } 3476 } 3477 break; 3478 case VAR: 3479 VarSymbol v = (VarSymbol)sym; 3480 // Test (4): if symbol is an instance field of a raw type, 3481 // which is being assigned to, issue an unchecked warning if 3482 // its type changes under erasure. 3483 if (KindSelector.ASG.subset(pkind()) && 3484 v.owner.kind == TYP && 3485 (v.flags() & STATIC) == 0 && 3486 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3487 Type s = types.asOuterSuper(site, v.owner); 3488 if (s != null && 3489 s.isRaw() && 3490 !types.isSameType(v.type, v.erasure(types))) { 3491 chk.warnUnchecked(tree.pos(), 3492 "unchecked.assign.to.var", 3493 v, s); 3494 } 3495 } 3496 // The computed type of a variable is the type of the 3497 // variable symbol, taken as a member of the site type. 3498 owntype = (sym.owner.kind == TYP && 3499 sym.name != names._this && sym.name != names._super) 3500 ? types.memberType(site, sym) 3501 : sym.type; 3502 3503 // If the variable is a constant, record constant value in 3504 // computed type. 3505 if (v.getConstValue() != null && isStaticReference(tree)) 3506 owntype = owntype.constType(v.getConstValue()); 3507 3508 if (resultInfo.pkind == KindSelector.VAL) { 3509 owntype = capture(owntype); // capture "names as expressions" 3510 } 3511 break; 3512 case MTH: { 3513 owntype = checkMethod(site, sym, 3514 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext), 3515 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 3516 resultInfo.pt.getTypeArguments()); 3517 break; 3518 } 3519 case PCK: case ERR: 3520 owntype = sym.type; 3521 break; 3522 default: 3523 throw new AssertionError("unexpected kind: " + sym.kind + 3524 " in tree " + tree); 3525 } 3526 3527 // Test (1): emit a `deprecation' warning if symbol is deprecated. 3528 // (for constructors, the error was given when the constructor was 3529 // resolved) 3530 3531 if (sym.name != names.init) { 3532 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 3533 chk.checkSunAPI(tree.pos(), sym); 3534 chk.checkProfile(tree.pos(), sym); 3535 } 3536 3537 // Test (3): if symbol is a variable, check that its type and 3538 // kind are compatible with the prototype and protokind. 3539 return check(tree, owntype, sym.kind.toSelector(), resultInfo); 3540 } 3541 3542 /** Check that variable is initialized and evaluate the variable's 3543 * initializer, if not yet done. Also check that variable is not 3544 * referenced before it is defined. 3545 * @param tree The tree making up the variable reference. 3546 * @param env The current environment. 3547 * @param v The variable's symbol. 3548 */ 3549 private void checkInit(JCTree tree, 3550 Env<AttrContext> env, 3551 VarSymbol v, 3552 boolean onlyWarning) { 3553// System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 3554// tree.pos + " " + v.pos + " " + 3555// Resolve.isStatic(env));//DEBUG 3556 3557 // A forward reference is diagnosed if the declaration position 3558 // of the variable is greater than the current tree position 3559 // and the tree and variable definition occur in the same class 3560 // definition. Note that writes don't count as references. 3561 // This check applies only to class and instance 3562 // variables. Local variables follow different scope rules, 3563 // and are subject to definite assignment checking. 3564 if ((env.info.enclVar == v || v.pos > tree.pos) && 3565 v.owner.kind == TYP && 3566 enclosingInitEnv(env) != null && 3567 v.owner == env.info.scope.owner.enclClass() && 3568 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 3569 (!env.tree.hasTag(ASSIGN) || 3570 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 3571 String suffix = (env.info.enclVar == v) ? 3572 "self.ref" : "forward.ref"; 3573 if (!onlyWarning || isStaticEnumField(v)) { 3574 log.error(tree.pos(), "illegal." + suffix); 3575 } else if (useBeforeDeclarationWarning) { 3576 log.warning(tree.pos(), suffix, v); 3577 } 3578 } 3579 3580 v.getConstValue(); // ensure initializer is evaluated 3581 3582 checkEnumInitializer(tree, env, v); 3583 } 3584 3585 /** 3586 * Returns the enclosing init environment associated with this env (if any). An init env 3587 * can be either a field declaration env or a static/instance initializer env. 3588 */ 3589 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) { 3590 while (true) { 3591 switch (env.tree.getTag()) { 3592 case VARDEF: 3593 JCVariableDecl vdecl = (JCVariableDecl)env.tree; 3594 if (vdecl.sym.owner.kind == TYP) { 3595 //field 3596 return env; 3597 } 3598 break; 3599 case BLOCK: 3600 if (env.next.tree.hasTag(CLASSDEF)) { 3601 //instance/static initializer 3602 return env; 3603 } 3604 break; 3605 case METHODDEF: 3606 case CLASSDEF: 3607 case TOPLEVEL: 3608 return null; 3609 } 3610 Assert.checkNonNull(env.next); 3611 env = env.next; 3612 } 3613 } 3614 3615 /** 3616 * Check for illegal references to static members of enum. In 3617 * an enum type, constructors and initializers may not 3618 * reference its static members unless they are constant. 3619 * 3620 * @param tree The tree making up the variable reference. 3621 * @param env The current environment. 3622 * @param v The variable's symbol. 3623 * @jls section 8.9 Enums 3624 */ 3625 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 3626 // JLS: 3627 // 3628 // "It is a compile-time error to reference a static field 3629 // of an enum type that is not a compile-time constant 3630 // (15.28) from constructors, instance initializer blocks, 3631 // or instance variable initializer expressions of that 3632 // type. It is a compile-time error for the constructors, 3633 // instance initializer blocks, or instance variable 3634 // initializer expressions of an enum constant e to refer 3635 // to itself or to an enum constant of the same type that 3636 // is declared to the right of e." 3637 if (isStaticEnumField(v)) { 3638 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 3639 3640 if (enclClass == null || enclClass.owner == null) 3641 return; 3642 3643 // See if the enclosing class is the enum (or a 3644 // subclass thereof) declaring v. If not, this 3645 // reference is OK. 3646 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 3647 return; 3648 3649 // If the reference isn't from an initializer, then 3650 // the reference is OK. 3651 if (!Resolve.isInitializer(env)) 3652 return; 3653 3654 log.error(tree.pos(), "illegal.enum.static.ref"); 3655 } 3656 } 3657 3658 /** Is the given symbol a static, non-constant field of an Enum? 3659 * Note: enum literals should not be regarded as such 3660 */ 3661 private boolean isStaticEnumField(VarSymbol v) { 3662 return Flags.isEnum(v.owner) && 3663 Flags.isStatic(v) && 3664 !Flags.isConstant(v) && 3665 v.name != names._class; 3666 } 3667 3668 Warner noteWarner = new Warner(); 3669 3670 /** 3671 * Check that method arguments conform to its instantiation. 3672 **/ 3673 public Type checkMethod(Type site, 3674 final Symbol sym, 3675 ResultInfo resultInfo, 3676 Env<AttrContext> env, 3677 final List<JCExpression> argtrees, 3678 List<Type> argtypes, 3679 List<Type> typeargtypes) { 3680 // Test (5): if symbol is an instance method of a raw type, issue 3681 // an unchecked warning if its argument types change under erasure. 3682 if ((sym.flags() & STATIC) == 0 && 3683 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3684 Type s = types.asOuterSuper(site, sym.owner); 3685 if (s != null && s.isRaw() && 3686 !types.isSameTypes(sym.type.getParameterTypes(), 3687 sym.erasure(types).getParameterTypes())) { 3688 chk.warnUnchecked(env.tree.pos(), 3689 "unchecked.call.mbr.of.raw.type", 3690 sym, s); 3691 } 3692 } 3693 3694 if (env.info.defaultSuperCallSite != null) { 3695 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 3696 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 3697 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 3698 List<MethodSymbol> icand_sup = 3699 types.interfaceCandidates(sup, (MethodSymbol)sym); 3700 if (icand_sup.nonEmpty() && 3701 icand_sup.head != sym && 3702 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 3703 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, 3704 diags.fragment("overridden.default", sym, sup)); 3705 break; 3706 } 3707 } 3708 env.info.defaultSuperCallSite = null; 3709 } 3710 3711 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { 3712 JCMethodInvocation app = (JCMethodInvocation)env.tree; 3713 if (app.meth.hasTag(SELECT) && 3714 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { 3715 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site); 3716 } 3717 } 3718 3719 // Compute the identifier's instantiated type. 3720 // For methods, we need to compute the instance type by 3721 // Resolve.instantiate from the symbol's type as well as 3722 // any type arguments and value arguments. 3723 noteWarner.clear(); 3724 try { 3725 Type owntype = rs.checkMethod( 3726 env, 3727 site, 3728 sym, 3729 resultInfo, 3730 argtypes, 3731 typeargtypes, 3732 noteWarner); 3733 3734 DeferredAttr.DeferredTypeMap checkDeferredMap = 3735 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase); 3736 3737 argtypes = Type.map(argtypes, checkDeferredMap); 3738 3739 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 3740 chk.warnUnchecked(env.tree.pos(), 3741 "unchecked.meth.invocation.applied", 3742 kindName(sym), 3743 sym.name, 3744 rs.methodArguments(sym.type.getParameterTypes()), 3745 rs.methodArguments(Type.map(argtypes, checkDeferredMap)), 3746 kindName(sym.location()), 3747 sym.location()); 3748 owntype = new MethodType(owntype.getParameterTypes(), 3749 types.erasure(owntype.getReturnType()), 3750 types.erasure(owntype.getThrownTypes()), 3751 syms.methodClass); 3752 } 3753 3754 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 3755 resultInfo.checkContext.inferenceContext()); 3756 } catch (Infer.InferenceException ex) { 3757 //invalid target type - propagate exception outwards or report error 3758 //depending on the current check context 3759 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 3760 return types.createErrorType(site); 3761 } catch (Resolve.InapplicableMethodException ex) { 3762 final JCDiagnostic diag = ex.getDiagnostic(); 3763 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) { 3764 @Override 3765 protected Pair<Symbol, JCDiagnostic> errCandidate() { 3766 return new Pair<>(sym, diag); 3767 } 3768 }; 3769 List<Type> argtypes2 = Type.map(argtypes, 3770 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3771 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 3772 env.tree, sym, site, sym.name, argtypes2, typeargtypes); 3773 log.report(errDiag); 3774 return types.createErrorType(site); 3775 } 3776 } 3777 3778 public void visitLiteral(JCLiteral tree) { 3779 result = check(tree, litType(tree.typetag).constType(tree.value), 3780 KindSelector.VAL, resultInfo); 3781 } 3782 //where 3783 /** Return the type of a literal with given type tag. 3784 */ 3785 Type litType(TypeTag tag) { 3786 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 3787 } 3788 3789 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 3790 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo); 3791 } 3792 3793 public void visitTypeArray(JCArrayTypeTree tree) { 3794 Type etype = attribType(tree.elemtype, env); 3795 Type type = new ArrayType(etype, syms.arrayClass); 3796 result = check(tree, type, KindSelector.TYP, resultInfo); 3797 } 3798 3799 /** Visitor method for parameterized types. 3800 * Bound checking is left until later, since types are attributed 3801 * before supertype structure is completely known 3802 */ 3803 public void visitTypeApply(JCTypeApply tree) { 3804 Type owntype = types.createErrorType(tree.type); 3805 3806 // Attribute functor part of application and make sure it's a class. 3807 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 3808 3809 // Attribute type parameters 3810 List<Type> actuals = attribTypes(tree.arguments, env); 3811 3812 if (clazztype.hasTag(CLASS)) { 3813 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 3814 if (actuals.isEmpty()) //diamond 3815 actuals = formals; 3816 3817 if (actuals.length() == formals.length()) { 3818 List<Type> a = actuals; 3819 List<Type> f = formals; 3820 while (a.nonEmpty()) { 3821 a.head = a.head.withTypeVar(f.head); 3822 a = a.tail; 3823 f = f.tail; 3824 } 3825 // Compute the proper generic outer 3826 Type clazzOuter = clazztype.getEnclosingType(); 3827 if (clazzOuter.hasTag(CLASS)) { 3828 Type site; 3829 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 3830 if (clazz.hasTag(IDENT)) { 3831 site = env.enclClass.sym.type; 3832 } else if (clazz.hasTag(SELECT)) { 3833 site = ((JCFieldAccess) clazz).selected.type; 3834 } else throw new AssertionError(""+tree); 3835 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 3836 if (site.hasTag(CLASS)) 3837 site = types.asOuterSuper(site, clazzOuter.tsym); 3838 if (site == null) 3839 site = types.erasure(clazzOuter); 3840 clazzOuter = site; 3841 } 3842 } 3843 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym, 3844 clazztype.getMetadata()); 3845 } else { 3846 if (formals.length() != 0) { 3847 log.error(tree.pos(), "wrong.number.type.args", 3848 Integer.toString(formals.length())); 3849 } else { 3850 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 3851 } 3852 owntype = types.createErrorType(tree.type); 3853 } 3854 } 3855 result = check(tree, owntype, KindSelector.TYP, resultInfo); 3856 } 3857 3858 public void visitTypeUnion(JCTypeUnion tree) { 3859 ListBuffer<Type> multicatchTypes = new ListBuffer<>(); 3860 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 3861 for (JCExpression typeTree : tree.alternatives) { 3862 Type ctype = attribType(typeTree, env); 3863 ctype = chk.checkType(typeTree.pos(), 3864 chk.checkClassType(typeTree.pos(), ctype), 3865 syms.throwableType); 3866 if (!ctype.isErroneous()) { 3867 //check that alternatives of a union type are pairwise 3868 //unrelated w.r.t. subtyping 3869 if (chk.intersects(ctype, multicatchTypes.toList())) { 3870 for (Type t : multicatchTypes) { 3871 boolean sub = types.isSubtype(ctype, t); 3872 boolean sup = types.isSubtype(t, ctype); 3873 if (sub || sup) { 3874 //assume 'a' <: 'b' 3875 Type a = sub ? ctype : t; 3876 Type b = sub ? t : ctype; 3877 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); 3878 } 3879 } 3880 } 3881 multicatchTypes.append(ctype); 3882 if (all_multicatchTypes != null) 3883 all_multicatchTypes.append(ctype); 3884 } else { 3885 if (all_multicatchTypes == null) { 3886 all_multicatchTypes = new ListBuffer<>(); 3887 all_multicatchTypes.appendList(multicatchTypes); 3888 } 3889 all_multicatchTypes.append(ctype); 3890 } 3891 } 3892 Type t = check(noCheckTree, types.lub(multicatchTypes.toList()), 3893 KindSelector.TYP, resultInfo); 3894 if (t.hasTag(CLASS)) { 3895 List<Type> alternatives = 3896 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 3897 t = new UnionClassType((ClassType) t, alternatives); 3898 } 3899 tree.type = result = t; 3900 } 3901 3902 public void visitTypeIntersection(JCTypeIntersection tree) { 3903 attribTypes(tree.bounds, env); 3904 tree.type = result = checkIntersection(tree, tree.bounds); 3905 } 3906 3907 public void visitTypeParameter(JCTypeParameter tree) { 3908 TypeVar typeVar = (TypeVar) tree.type; 3909 3910 if (tree.annotations != null && tree.annotations.nonEmpty()) { 3911 annotateType(tree, tree.annotations); 3912 } 3913 3914 if (!typeVar.bound.isErroneous()) { 3915 //fixup type-parameter bound computed in 'attribTypeVariables' 3916 typeVar.bound = checkIntersection(tree, tree.bounds); 3917 } 3918 } 3919 3920 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 3921 Set<Type> boundSet = new HashSet<>(); 3922 if (bounds.nonEmpty()) { 3923 // accept class or interface or typevar as first bound. 3924 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 3925 boundSet.add(types.erasure(bounds.head.type)); 3926 if (bounds.head.type.isErroneous()) { 3927 return bounds.head.type; 3928 } 3929 else if (bounds.head.type.hasTag(TYPEVAR)) { 3930 // if first bound was a typevar, do not accept further bounds. 3931 if (bounds.tail.nonEmpty()) { 3932 log.error(bounds.tail.head.pos(), 3933 "type.var.may.not.be.followed.by.other.bounds"); 3934 return bounds.head.type; 3935 } 3936 } else { 3937 // if first bound was a class or interface, accept only interfaces 3938 // as further bounds. 3939 for (JCExpression bound : bounds.tail) { 3940 bound.type = checkBase(bound.type, bound, env, false, true, false); 3941 if (bound.type.isErroneous()) { 3942 bounds = List.of(bound); 3943 } 3944 else if (bound.type.hasTag(CLASS)) { 3945 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 3946 } 3947 } 3948 } 3949 } 3950 3951 if (bounds.length() == 0) { 3952 return syms.objectType; 3953 } else if (bounds.length() == 1) { 3954 return bounds.head.type; 3955 } else { 3956 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds)); 3957 // ... the variable's bound is a class type flagged COMPOUND 3958 // (see comment for TypeVar.bound). 3959 // In this case, generate a class tree that represents the 3960 // bound class, ... 3961 JCExpression extending; 3962 List<JCExpression> implementing; 3963 if (!bounds.head.type.isInterface()) { 3964 extending = bounds.head; 3965 implementing = bounds.tail; 3966 } else { 3967 extending = null; 3968 implementing = bounds; 3969 } 3970 JCClassDecl cd = make.at(tree).ClassDef( 3971 make.Modifiers(PUBLIC | ABSTRACT), 3972 names.empty, List.<JCTypeParameter>nil(), 3973 extending, implementing, List.<JCTree>nil()); 3974 3975 ClassSymbol c = (ClassSymbol)owntype.tsym; 3976 Assert.check((c.flags() & COMPOUND) != 0); 3977 cd.sym = c; 3978 c.sourcefile = env.toplevel.sourcefile; 3979 3980 // ... and attribute the bound class 3981 c.flags_field |= UNATTRIBUTED; 3982 Env<AttrContext> cenv = enter.classEnv(cd, env); 3983 typeEnvs.put(c, cenv); 3984 attribClass(c); 3985 return owntype; 3986 } 3987 } 3988 3989 public void visitWildcard(JCWildcard tree) { 3990 //- System.err.println("visitWildcard("+tree+");");//DEBUG 3991 Type type = (tree.kind.kind == BoundKind.UNBOUND) 3992 ? syms.objectType 3993 : attribType(tree.inner, env); 3994 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 3995 tree.kind.kind, 3996 syms.boundClass), 3997 KindSelector.TYP, resultInfo); 3998 } 3999 4000 public void visitAnnotation(JCAnnotation tree) { 4001 Assert.error("should be handled in Annotate"); 4002 } 4003 4004 public void visitAnnotatedType(JCAnnotatedType tree) { 4005 Type underlyingType = attribType(tree.getUnderlyingType(), env); 4006 this.attribAnnotationTypes(tree.annotations, env); 4007 annotateType(tree, tree.annotations); 4008 result = tree.type = underlyingType; 4009 } 4010 4011 /** 4012 * Apply the annotations to the particular type. 4013 */ 4014 public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) { 4015 annotate.typeAnnotation(new Annotate.Worker() { 4016 @Override 4017 public String toString() { 4018 return "annotate " + annotations + " onto " + tree; 4019 } 4020 @Override 4021 public void run() { 4022 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations); 4023 Assert.check(annotations.size() == compounds.size()); 4024 tree.type = tree.type.annotatedType(compounds); 4025 } 4026 }); 4027 } 4028 4029 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) { 4030 if (annotations.isEmpty()) { 4031 return List.nil(); 4032 } 4033 4034 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>(); 4035 for (JCAnnotation anno : annotations) { 4036 Assert.checkNonNull(anno.attribute); 4037 buf.append((Attribute.TypeCompound) anno.attribute); 4038 } 4039 return buf.toList(); 4040 } 4041 4042 public void visitErroneous(JCErroneous tree) { 4043 if (tree.errs != null) 4044 for (JCTree err : tree.errs) 4045 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt())); 4046 result = tree.type = syms.errType; 4047 } 4048 4049 /** Default visitor method for all other trees. 4050 */ 4051 public void visitTree(JCTree tree) { 4052 throw new AssertionError(); 4053 } 4054 4055 /** 4056 * Attribute an env for either a top level tree or class declaration. 4057 */ 4058 public void attrib(Env<AttrContext> env) { 4059 if (env.tree.hasTag(TOPLEVEL)) 4060 attribTopLevel(env); 4061 else 4062 attribClass(env.tree.pos(), env.enclClass.sym); 4063 } 4064 4065 /** 4066 * Attribute a top level tree. These trees are encountered when the 4067 * package declaration has annotations. 4068 */ 4069 public void attribTopLevel(Env<AttrContext> env) { 4070 JCCompilationUnit toplevel = env.toplevel; 4071 try { 4072 annotate.flush(); 4073 } catch (CompletionFailure ex) { 4074 chk.completionError(toplevel.pos(), ex); 4075 } 4076 } 4077 4078 /** Main method: attribute class definition associated with given class symbol. 4079 * reporting completion failures at the given position. 4080 * @param pos The source position at which completion errors are to be 4081 * reported. 4082 * @param c The class symbol whose definition will be attributed. 4083 */ 4084 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 4085 try { 4086 annotate.flush(); 4087 attribClass(c); 4088 } catch (CompletionFailure ex) { 4089 chk.completionError(pos, ex); 4090 } 4091 } 4092 4093 /** Attribute class definition associated with given class symbol. 4094 * @param c The class symbol whose definition will be attributed. 4095 */ 4096 void attribClass(ClassSymbol c) throws CompletionFailure { 4097 if (c.type.hasTag(ERROR)) return; 4098 4099 // Check for cycles in the inheritance graph, which can arise from 4100 // ill-formed class files. 4101 chk.checkNonCyclic(null, c.type); 4102 4103 Type st = types.supertype(c.type); 4104 if ((c.flags_field & Flags.COMPOUND) == 0) { 4105 // First, attribute superclass. 4106 if (st.hasTag(CLASS)) 4107 attribClass((ClassSymbol)st.tsym); 4108 4109 // Next attribute owner, if it is a class. 4110 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 4111 attribClass((ClassSymbol)c.owner); 4112 } 4113 4114 // The previous operations might have attributed the current class 4115 // if there was a cycle. So we test first whether the class is still 4116 // UNATTRIBUTED. 4117 if ((c.flags_field & UNATTRIBUTED) != 0) { 4118 c.flags_field &= ~UNATTRIBUTED; 4119 4120 // Get environment current at the point of class definition. 4121 Env<AttrContext> env = typeEnvs.get(c); 4122 4123 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized, 4124 // because the annotations were not available at the time the env was created. Therefore, 4125 // we look up the environment chain for the first enclosing environment for which the 4126 // lint value is set. Typically, this is the parent env, but might be further if there 4127 // are any envs created as a result of TypeParameter nodes. 4128 Env<AttrContext> lintEnv = env; 4129 while (lintEnv.info.lint == null) 4130 lintEnv = lintEnv.next; 4131 4132 // Having found the enclosing lint value, we can initialize the lint value for this class 4133 env.info.lint = lintEnv.info.lint.augment(c); 4134 4135 Lint prevLint = chk.setLint(env.info.lint); 4136 JavaFileObject prev = log.useSource(c.sourcefile); 4137 ResultInfo prevReturnRes = env.info.returnResult; 4138 4139 try { 4140 deferredLintHandler.flush(env.tree); 4141 env.info.returnResult = null; 4142 // java.lang.Enum may not be subclassed by a non-enum 4143 if (st.tsym == syms.enumSym && 4144 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 4145 log.error(env.tree.pos(), "enum.no.subclassing"); 4146 4147 // Enums may not be extended by source-level classes 4148 if (st.tsym != null && 4149 ((st.tsym.flags_field & Flags.ENUM) != 0) && 4150 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { 4151 log.error(env.tree.pos(), "enum.types.not.extensible"); 4152 } 4153 4154 if (isSerializable(c.type)) { 4155 env.info.isSerializable = true; 4156 } 4157 4158 attribClassBody(env, c); 4159 4160 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 4161 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); 4162 chk.checkFunctionalInterface((JCClassDecl) env.tree, c); 4163 } finally { 4164 env.info.returnResult = prevReturnRes; 4165 log.useSource(prev); 4166 chk.setLint(prevLint); 4167 } 4168 4169 } 4170 } 4171 4172 public void visitImport(JCImport tree) { 4173 // nothing to do 4174 } 4175 4176 /** Finish the attribution of a class. */ 4177 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 4178 JCClassDecl tree = (JCClassDecl)env.tree; 4179 Assert.check(c == tree.sym); 4180 4181 // Validate type parameters, supertype and interfaces. 4182 attribStats(tree.typarams, env); 4183 if (!c.isAnonymous()) { 4184 //already checked if anonymous 4185 chk.validate(tree.typarams, env); 4186 chk.validate(tree.extending, env); 4187 chk.validate(tree.implementing, env); 4188 } 4189 4190 c.markAbstractIfNeeded(types); 4191 4192 // If this is a non-abstract class, check that it has no abstract 4193 // methods or unimplemented methods of an implemented interface. 4194 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 4195 if (!relax) 4196 chk.checkAllDefined(tree.pos(), c); 4197 } 4198 4199 if ((c.flags() & ANNOTATION) != 0) { 4200 if (tree.implementing.nonEmpty()) 4201 log.error(tree.implementing.head.pos(), 4202 "cant.extend.intf.annotation"); 4203 if (tree.typarams.nonEmpty()) 4204 log.error(tree.typarams.head.pos(), 4205 "intf.annotation.cant.have.type.params"); 4206 4207 // If this annotation has a @Repeatable, validate 4208 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym); 4209 if (repeatable != null) { 4210 // get diagnostic position for error reporting 4211 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); 4212 Assert.checkNonNull(cbPos); 4213 4214 chk.validateRepeatable(c, repeatable, cbPos); 4215 } 4216 } else { 4217 // Check that all extended classes and interfaces 4218 // are compatible (i.e. no two define methods with same arguments 4219 // yet different return types). (JLS 8.4.6.3) 4220 chk.checkCompatibleSupertypes(tree.pos(), c.type); 4221 if (allowDefaultMethods) { 4222 chk.checkDefaultMethodClashes(tree.pos(), c.type); 4223 } 4224 } 4225 4226 // Check that class does not import the same parameterized interface 4227 // with two different argument lists. 4228 chk.checkClassBounds(tree.pos(), c.type); 4229 4230 tree.type = c.type; 4231 4232 for (List<JCTypeParameter> l = tree.typarams; 4233 l.nonEmpty(); l = l.tail) { 4234 Assert.checkNonNull(env.info.scope.findFirst(l.head.name)); 4235 } 4236 4237 // Check that a generic class doesn't extend Throwable 4238 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 4239 log.error(tree.extending.pos(), "generic.throwable"); 4240 4241 // Check that all methods which implement some 4242 // method conform to the method they implement. 4243 chk.checkImplementations(tree); 4244 4245 //check that a resource implementing AutoCloseable cannot throw InterruptedException 4246 checkAutoCloseable(tree.pos(), env, c.type); 4247 4248 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 4249 // Attribute declaration 4250 attribStat(l.head, env); 4251 // Check that declarations in inner classes are not static (JLS 8.1.2) 4252 // Make an exception for static constants. 4253 if (c.owner.kind != PCK && 4254 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 4255 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 4256 Symbol sym = null; 4257 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 4258 if (sym == null || 4259 sym.kind != VAR || 4260 ((VarSymbol) sym).getConstValue() == null) 4261 log.error(l.head.pos(), "icls.cant.have.static.decl", c); 4262 } 4263 } 4264 4265 // Check for cycles among non-initial constructors. 4266 chk.checkCyclicConstructors(tree); 4267 4268 // Check for cycles among annotation elements. 4269 chk.checkNonCyclicElements(tree); 4270 4271 // Check for proper use of serialVersionUID 4272 if (env.info.lint.isEnabled(LintCategory.SERIAL) && 4273 isSerializable(c.type) && 4274 (c.flags() & Flags.ENUM) == 0 && 4275 checkForSerial(c)) { 4276 checkSerialVersionUID(tree, c); 4277 } 4278 if (allowTypeAnnos) { 4279 // Correctly organize the postions of the type annotations 4280 typeAnnotations.organizeTypeAnnotationsBodies(tree); 4281 4282 // Check type annotations applicability rules 4283 validateTypeAnnotations(tree, false); 4284 } 4285 } 4286 // where 4287 boolean checkForSerial(ClassSymbol c) { 4288 if ((c.flags() & ABSTRACT) == 0) { 4289 return true; 4290 } else { 4291 return c.members().anyMatch(anyNonAbstractOrDefaultMethod); 4292 } 4293 } 4294 4295 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() { 4296 @Override 4297 public boolean accepts(Symbol s) { 4298 return s.kind == MTH && 4299 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT; 4300 } 4301 }; 4302 4303 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 4304 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 4305 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 4306 if (types.isSameType(al.head.annotationType.type, t)) 4307 return al.head.pos(); 4308 } 4309 4310 return null; 4311 } 4312 4313 /** check if a type is a subtype of Serializable, if that is available. */ 4314 boolean isSerializable(Type t) { 4315 try { 4316 syms.serializableType.complete(); 4317 } 4318 catch (CompletionFailure e) { 4319 return false; 4320 } 4321 return types.isSubtype(t, syms.serializableType); 4322 } 4323 4324 /** Check that an appropriate serialVersionUID member is defined. */ 4325 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 4326 4327 // check for presence of serialVersionUID 4328 VarSymbol svuid = null; 4329 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { 4330 if (sym.kind == VAR) { 4331 svuid = (VarSymbol)sym; 4332 break; 4333 } 4334 } 4335 4336 if (svuid == null) { 4337 log.warning(LintCategory.SERIAL, 4338 tree.pos(), "missing.SVUID", c); 4339 return; 4340 } 4341 4342 // check that it is static final 4343 if ((svuid.flags() & (STATIC | FINAL)) != 4344 (STATIC | FINAL)) 4345 log.warning(LintCategory.SERIAL, 4346 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 4347 4348 // check that it is long 4349 else if (!svuid.type.hasTag(LONG)) 4350 log.warning(LintCategory.SERIAL, 4351 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 4352 4353 // check constant 4354 else if (svuid.getConstValue() == null) 4355 log.warning(LintCategory.SERIAL, 4356 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 4357 } 4358 4359 private Type capture(Type type) { 4360 return types.capture(type); 4361 } 4362 4363 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { 4364 tree.accept(new TypeAnnotationsValidator(sigOnly)); 4365 } 4366 //where 4367 private final class TypeAnnotationsValidator extends TreeScanner { 4368 4369 private final boolean sigOnly; 4370 public TypeAnnotationsValidator(boolean sigOnly) { 4371 this.sigOnly = sigOnly; 4372 } 4373 4374 public void visitAnnotation(JCAnnotation tree) { 4375 chk.validateTypeAnnotation(tree, false); 4376 super.visitAnnotation(tree); 4377 } 4378 public void visitAnnotatedType(JCAnnotatedType tree) { 4379 if (!tree.underlyingType.type.isErroneous()) { 4380 super.visitAnnotatedType(tree); 4381 } 4382 } 4383 public void visitTypeParameter(JCTypeParameter tree) { 4384 chk.validateTypeAnnotations(tree.annotations, true); 4385 scan(tree.bounds); 4386 // Don't call super. 4387 // This is needed because above we call validateTypeAnnotation with 4388 // false, which would forbid annotations on type parameters. 4389 // super.visitTypeParameter(tree); 4390 } 4391 public void visitMethodDef(JCMethodDecl tree) { 4392 if (tree.recvparam != null && 4393 !tree.recvparam.vartype.type.isErroneous()) { 4394 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, 4395 tree.recvparam.vartype.type.tsym); 4396 } 4397 if (tree.restype != null && tree.restype.type != null) { 4398 validateAnnotatedType(tree.restype, tree.restype.type); 4399 } 4400 if (sigOnly) { 4401 scan(tree.mods); 4402 scan(tree.restype); 4403 scan(tree.typarams); 4404 scan(tree.recvparam); 4405 scan(tree.params); 4406 scan(tree.thrown); 4407 } else { 4408 scan(tree.defaultValue); 4409 scan(tree.body); 4410 } 4411 } 4412 public void visitVarDef(final JCVariableDecl tree) { 4413 //System.err.println("validateTypeAnnotations.visitVarDef " + tree); 4414 if (tree.sym != null && tree.sym.type != null) 4415 validateAnnotatedType(tree.vartype, tree.sym.type); 4416 scan(tree.mods); 4417 scan(tree.vartype); 4418 if (!sigOnly) { 4419 scan(tree.init); 4420 } 4421 } 4422 public void visitTypeCast(JCTypeCast tree) { 4423 if (tree.clazz != null && tree.clazz.type != null) 4424 validateAnnotatedType(tree.clazz, tree.clazz.type); 4425 super.visitTypeCast(tree); 4426 } 4427 public void visitTypeTest(JCInstanceOf tree) { 4428 if (tree.clazz != null && tree.clazz.type != null) 4429 validateAnnotatedType(tree.clazz, tree.clazz.type); 4430 super.visitTypeTest(tree); 4431 } 4432 public void visitNewClass(JCNewClass tree) { 4433 if (tree.clazz != null && tree.clazz.type != null) { 4434 if (tree.clazz.hasTag(ANNOTATED_TYPE)) { 4435 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations, 4436 tree.clazz.type.tsym); 4437 } 4438 if (tree.def != null) { 4439 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym); 4440 } 4441 4442 validateAnnotatedType(tree.clazz, tree.clazz.type); 4443 } 4444 super.visitNewClass(tree); 4445 } 4446 public void visitNewArray(JCNewArray tree) { 4447 if (tree.elemtype != null && tree.elemtype.type != null) { 4448 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) { 4449 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations, 4450 tree.elemtype.type.tsym); 4451 } 4452 validateAnnotatedType(tree.elemtype, tree.elemtype.type); 4453 } 4454 super.visitNewArray(tree); 4455 } 4456 public void visitClassDef(JCClassDecl tree) { 4457 //System.err.println("validateTypeAnnotations.visitClassDef " + tree); 4458 if (sigOnly) { 4459 scan(tree.mods); 4460 scan(tree.typarams); 4461 scan(tree.extending); 4462 scan(tree.implementing); 4463 } 4464 for (JCTree member : tree.defs) { 4465 if (member.hasTag(Tag.CLASSDEF)) { 4466 continue; 4467 } 4468 scan(member); 4469 } 4470 } 4471 public void visitBlock(JCBlock tree) { 4472 if (!sigOnly) { 4473 scan(tree.stats); 4474 } 4475 } 4476 4477 /* I would want to model this after 4478 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) 4479 * and override visitSelect and visitTypeApply. 4480 * However, we only set the annotated type in the top-level type 4481 * of the symbol. 4482 * Therefore, we need to override each individual location where a type 4483 * can occur. 4484 */ 4485 private void validateAnnotatedType(final JCTree errtree, final Type type) { 4486 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type); 4487 4488 if (type.isPrimitiveOrVoid()) { 4489 return; 4490 } 4491 4492 JCTree enclTr = errtree; 4493 Type enclTy = type; 4494 4495 boolean repeat = true; 4496 while (repeat) { 4497 if (enclTr.hasTag(TYPEAPPLY)) { 4498 List<Type> tyargs = enclTy.getTypeArguments(); 4499 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments(); 4500 if (trargs.length() > 0) { 4501 // Nothing to do for diamonds 4502 if (tyargs.length() == trargs.length()) { 4503 for (int i = 0; i < tyargs.length(); ++i) { 4504 validateAnnotatedType(trargs.get(i), tyargs.get(i)); 4505 } 4506 } 4507 // If the lengths don't match, it's either a diamond 4508 // or some nested type that redundantly provides 4509 // type arguments in the tree. 4510 } 4511 4512 // Look at the clazz part of a generic type 4513 enclTr = ((JCTree.JCTypeApply)enclTr).clazz; 4514 } 4515 4516 if (enclTr.hasTag(SELECT)) { 4517 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression(); 4518 if (enclTy != null && 4519 !enclTy.hasTag(NONE)) { 4520 enclTy = enclTy.getEnclosingType(); 4521 } 4522 } else if (enclTr.hasTag(ANNOTATED_TYPE)) { 4523 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; 4524 if (enclTy == null || enclTy.hasTag(NONE)) { 4525 if (at.getAnnotations().size() == 1) { 4526 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute); 4527 } else { 4528 ListBuffer<Attribute.Compound> comps = new ListBuffer<>(); 4529 for (JCAnnotation an : at.getAnnotations()) { 4530 comps.add(an.attribute); 4531 } 4532 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList()); 4533 } 4534 repeat = false; 4535 } 4536 enclTr = at.underlyingType; 4537 // enclTy doesn't need to be changed 4538 } else if (enclTr.hasTag(IDENT)) { 4539 repeat = false; 4540 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) { 4541 JCWildcard wc = (JCWildcard) enclTr; 4542 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) { 4543 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound()); 4544 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) { 4545 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound()); 4546 } else { 4547 // Nothing to do for UNBOUND 4548 } 4549 repeat = false; 4550 } else if (enclTr.hasTag(TYPEARRAY)) { 4551 JCArrayTypeTree art = (JCArrayTypeTree) enclTr; 4552 validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType()); 4553 repeat = false; 4554 } else if (enclTr.hasTag(TYPEUNION)) { 4555 JCTypeUnion ut = (JCTypeUnion) enclTr; 4556 for (JCTree t : ut.getTypeAlternatives()) { 4557 validateAnnotatedType(t, t.type); 4558 } 4559 repeat = false; 4560 } else if (enclTr.hasTag(TYPEINTERSECTION)) { 4561 JCTypeIntersection it = (JCTypeIntersection) enclTr; 4562 for (JCTree t : it.getBounds()) { 4563 validateAnnotatedType(t, t.type); 4564 } 4565 repeat = false; 4566 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE || 4567 enclTr.getKind() == JCTree.Kind.ERRONEOUS) { 4568 repeat = false; 4569 } else { 4570 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() + 4571 " within: "+ errtree + " with kind: " + errtree.getKind()); 4572 } 4573 } 4574 } 4575 4576 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations, 4577 Symbol sym) { 4578 // Ensure that no declaration annotations are present. 4579 // Note that a tree type might be an AnnotatedType with 4580 // empty annotations, if only declaration annotations were given. 4581 // This method will raise an error for such a type. 4582 for (JCAnnotation ai : annotations) { 4583 if (!ai.type.isErroneous() && 4584 typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) { 4585 log.error(ai.pos(), "annotation.type.not.applicable"); 4586 } 4587 } 4588 } 4589 } 4590 4591 // <editor-fold desc="post-attribution visitor"> 4592 4593 /** 4594 * Handle missing types/symbols in an AST. This routine is useful when 4595 * the compiler has encountered some errors (which might have ended up 4596 * terminating attribution abruptly); if the compiler is used in fail-over 4597 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 4598 * prevents NPE to be progagated during subsequent compilation steps. 4599 */ 4600 public void postAttr(JCTree tree) { 4601 new PostAttrAnalyzer().scan(tree); 4602 } 4603 4604 class PostAttrAnalyzer extends TreeScanner { 4605 4606 private void initTypeIfNeeded(JCTree that) { 4607 if (that.type == null) { 4608 if (that.hasTag(METHODDEF)) { 4609 that.type = dummyMethodType((JCMethodDecl)that); 4610 } else { 4611 that.type = syms.unknownType; 4612 } 4613 } 4614 } 4615 4616 /* Construct a dummy method type. If we have a method declaration, 4617 * and the declared return type is void, then use that return type 4618 * instead of UNKNOWN to avoid spurious error messages in lambda 4619 * bodies (see:JDK-8041704). 4620 */ 4621 private Type dummyMethodType(JCMethodDecl md) { 4622 Type restype = syms.unknownType; 4623 if (md != null && md.restype.hasTag(TYPEIDENT)) { 4624 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; 4625 if (prim.typetag == VOID) 4626 restype = syms.voidType; 4627 } 4628 return new MethodType(List.<Type>nil(), restype, 4629 List.<Type>nil(), syms.methodClass); 4630 } 4631 private Type dummyMethodType() { 4632 return dummyMethodType(null); 4633 } 4634 4635 @Override 4636 public void scan(JCTree tree) { 4637 if (tree == null) return; 4638 if (tree instanceof JCExpression) { 4639 initTypeIfNeeded(tree); 4640 } 4641 super.scan(tree); 4642 } 4643 4644 @Override 4645 public void visitIdent(JCIdent that) { 4646 if (that.sym == null) { 4647 that.sym = syms.unknownSymbol; 4648 } 4649 } 4650 4651 @Override 4652 public void visitSelect(JCFieldAccess that) { 4653 if (that.sym == null) { 4654 that.sym = syms.unknownSymbol; 4655 } 4656 super.visitSelect(that); 4657 } 4658 4659 @Override 4660 public void visitClassDef(JCClassDecl that) { 4661 initTypeIfNeeded(that); 4662 if (that.sym == null) { 4663 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 4664 } 4665 super.visitClassDef(that); 4666 } 4667 4668 @Override 4669 public void visitMethodDef(JCMethodDecl that) { 4670 initTypeIfNeeded(that); 4671 if (that.sym == null) { 4672 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 4673 } 4674 super.visitMethodDef(that); 4675 } 4676 4677 @Override 4678 public void visitVarDef(JCVariableDecl that) { 4679 initTypeIfNeeded(that); 4680 if (that.sym == null) { 4681 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 4682 that.sym.adr = 0; 4683 } 4684 super.visitVarDef(that); 4685 } 4686 4687 @Override 4688 public void visitNewClass(JCNewClass that) { 4689 if (that.constructor == null) { 4690 that.constructor = new MethodSymbol(0, names.init, 4691 dummyMethodType(), syms.noSymbol); 4692 } 4693 if (that.constructorType == null) { 4694 that.constructorType = syms.unknownType; 4695 } 4696 super.visitNewClass(that); 4697 } 4698 4699 @Override 4700 public void visitAssignop(JCAssignOp that) { 4701 if (that.operator == null) { 4702 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4703 -1, syms.noSymbol); 4704 } 4705 super.visitAssignop(that); 4706 } 4707 4708 @Override 4709 public void visitBinary(JCBinary that) { 4710 if (that.operator == null) { 4711 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4712 -1, syms.noSymbol); 4713 } 4714 super.visitBinary(that); 4715 } 4716 4717 @Override 4718 public void visitUnary(JCUnary that) { 4719 if (that.operator == null) { 4720 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4721 -1, syms.noSymbol); 4722 } 4723 super.visitUnary(that); 4724 } 4725 4726 @Override 4727 public void visitLambda(JCLambda that) { 4728 super.visitLambda(that); 4729 if (that.targets == null) { 4730 that.targets = List.nil(); 4731 } 4732 } 4733 4734 @Override 4735 public void visitReference(JCMemberReference that) { 4736 super.visitReference(that); 4737 if (that.sym == null) { 4738 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(), 4739 syms.noSymbol); 4740 } 4741 if (that.targets == null) { 4742 that.targets = List.nil(); 4743 } 4744 } 4745 } 4746 // </editor-fold> 4747} 4748