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