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