Path: blob/master/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java
43153 views
/*1* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.tools.javac.comp;2627import java.util.EnumSet;28import java.util.Set;2930import com.sun.tools.javac.code.*;31import com.sun.tools.javac.code.Scope.WriteableScope;32import com.sun.tools.javac.tree.*;33import com.sun.tools.javac.util.*;34import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;35import com.sun.tools.javac.util.JCDiagnostic.Error;3637import com.sun.tools.javac.code.Symbol.*;38import com.sun.tools.javac.code.Type.*;39import com.sun.tools.javac.resources.CompilerProperties.Errors;40import com.sun.tools.javac.tree.JCTree.*;4142import static com.sun.tools.javac.code.Flags.*;43import static com.sun.tools.javac.code.Kinds.*;44import static com.sun.tools.javac.code.Kinds.Kind.*;45import static com.sun.tools.javac.code.TypeTag.TYPEVAR;4647/** Resolves field, method and constructor header, and constructs corresponding Symbols.48*49* <p><b>This is NOT part of any supported API.50* If you write code that depends on this, you do so at your own risk.51* This code and its internal interfaces are subject to change or52* deletion without notice.</b>53*/54public class MemberEnter extends JCTree.Visitor {55protected static final Context.Key<MemberEnter> memberEnterKey = new Context.Key<>();5657private final Enter enter;58private final Log log;59private final Check chk;60private final Attr attr;61private final Symtab syms;62private final Annotate annotate;63private final Types types;64private final DeferredLintHandler deferredLintHandler;6566public static MemberEnter instance(Context context) {67MemberEnter instance = context.get(memberEnterKey);68if (instance == null)69instance = new MemberEnter(context);70return instance;71}7273protected MemberEnter(Context context) {74context.put(memberEnterKey, this);75enter = Enter.instance(context);76log = Log.instance(context);77chk = Check.instance(context);78attr = Attr.instance(context);79syms = Symtab.instance(context);80annotate = Annotate.instance(context);81types = Types.instance(context);82deferredLintHandler = DeferredLintHandler.instance(context);83}8485/** Construct method type from method signature.86* @param typarams The method's type parameters.87* @param params The method's value parameters.88* @param res The method's result type,89* null if it is a constructor.90* @param recvparam The method's receiver parameter,91* null if none given; TODO: or already set here?92* @param thrown The method's thrown exceptions.93* @param env The method's (local) environment.94*/95Type signature(MethodSymbol msym,96List<JCTypeParameter> typarams,97List<JCVariableDecl> params,98JCTree res,99JCVariableDecl recvparam,100List<JCExpression> thrown,101Env<AttrContext> env) {102103// Enter and attribute type parameters.104List<Type> tvars = enter.classEnter(typarams, env);105attr.attribTypeVariables(typarams, env, true);106107// Enter and attribute value parameters.108ListBuffer<Type> argbuf = new ListBuffer<>();109for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {110memberEnter(l.head, env);111argbuf.append(l.head.vartype.type);112}113114// Attribute result type, if one is given.115Type restype = res == null ? syms.voidType : attr.attribType(res, env);116117// Attribute receiver type, if one is given.118Type recvtype;119if (recvparam!=null) {120memberEnter(recvparam, env);121recvtype = recvparam.vartype.type;122} else {123recvtype = null;124}125126// Attribute thrown exceptions.127ListBuffer<Type> thrownbuf = new ListBuffer<>();128for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {129Type exc = attr.attribType(l.head, env);130if (!exc.hasTag(TYPEVAR)) {131exc = chk.checkClassType(l.head.pos(), exc);132} else if (exc.tsym.owner == msym) {133//mark inference variables in 'throws' clause134exc.tsym.flags_field |= THROWS;135}136thrownbuf.append(exc);137}138MethodType mtype = new MethodType(argbuf.toList(),139restype,140thrownbuf.toList(),141syms.methodClass);142mtype.recvtype = recvtype;143144return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);145}146147/* ********************************************************************148* Visitor methods for member enter149*********************************************************************/150151/** Visitor argument: the current environment152*/153protected Env<AttrContext> env;154155/** Enter field and method definitions and process import156* clauses, catching any completion failure exceptions.157*/158protected void memberEnter(JCTree tree, Env<AttrContext> env) {159Env<AttrContext> prevEnv = this.env;160try {161this.env = env;162tree.accept(this);163} catch (CompletionFailure ex) {164chk.completionError(tree.pos(), ex);165} finally {166this.env = prevEnv;167}168}169170/** Enter members from a list of trees.171*/172void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {173for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)174memberEnter(l.head, env);175}176177public void visitMethodDef(JCMethodDecl tree) {178WriteableScope enclScope = enter.enterScope(env);179MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);180m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);181tree.sym = m;182183//if this is a default method, add the DEFAULT flag to the enclosing interface184if ((tree.mods.flags & DEFAULT) != 0) {185m.owner.flags_field |= DEFAULT;186}187188Env<AttrContext> localEnv = methodEnv(tree, env);189DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());190try {191// Compute the method type192m.type = signature(m, tree.typarams, tree.params,193tree.restype, tree.recvparam,194tree.thrown,195localEnv);196} finally {197deferredLintHandler.setPos(prevLintPos);198}199200if (types.isSignaturePolymorphic(m)) {201m.flags_field |= SIGNATURE_POLYMORPHIC;202}203204// Set m.params205ListBuffer<VarSymbol> params = new ListBuffer<>();206JCVariableDecl lastParam = null;207for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {208JCVariableDecl param = lastParam = l.head;209params.append(Assert.checkNonNull(param.sym));210}211m.params = params.toList();212213// mark the method varargs, if necessary214if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)215m.flags_field |= Flags.VARARGS;216217localEnv.info.scope.leave();218if (chk.checkUnique(tree.pos(), m, enclScope)) {219enclScope.enter(m);220}221222annotate.annotateLater(tree.mods.annotations, localEnv, m, tree.pos());223// Visit the signature of the method. Note that224// TypeAnnotate doesn't descend into the body.225annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, m, tree.pos());226227if (tree.defaultValue != null) {228m.defaultValue = annotate.unfinishedDefaultValue(); // set it to temporary sentinel for now229annotate.annotateDefaultValueLater(tree.defaultValue, localEnv, m, tree.pos());230}231}232233/** Create a fresh environment for method bodies.234* @param tree The method definition.235* @param env The environment current outside of the method definition.236*/237Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {238Env<AttrContext> localEnv =239env.dup(tree, env.info.dup(env.info.scope.dupUnshared(tree.sym)));240localEnv.enclMethod = tree;241if (tree.sym.type != null) {242//when this is called in the enter stage, there's no type to be set243localEnv.info.returnResult = attr.new ResultInfo(KindSelector.VAL,244tree.sym.type.getReturnType());245}246if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;247localEnv.info.yieldResult = null;248return localEnv;249}250251public void visitVarDef(JCVariableDecl tree) {252Env<AttrContext> localEnv = env;253if ((tree.mods.flags & STATIC) != 0 ||254(env.info.scope.owner.flags() & INTERFACE) != 0) {255localEnv = env.dup(tree, env.info.dup());256localEnv.info.staticLevel++;257}258DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());259260try {261if (TreeInfo.isEnumInit(tree)) {262attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);263} else if (!tree.isImplicitlyTyped()) {264attr.attribType(tree.vartype, localEnv);265if (TreeInfo.isReceiverParam(tree))266checkReceiver(tree, localEnv);267}268} finally {269deferredLintHandler.setPos(prevLintPos);270}271272if ((tree.mods.flags & VARARGS) != 0) {273//if we are entering a varargs parameter, we need to274//replace its type (a plain array type) with the more275//precise VarargsType --- we need to do it this way276//because varargs is represented in the tree as a277//modifier on the parameter declaration, and not as a278//distinct type of array node.279ArrayType atype = (ArrayType)tree.vartype.type;280tree.vartype.type = atype.makeVarargs();281}282WriteableScope enclScope = enter.enterScope(env);283Type vartype = tree.isImplicitlyTyped()284? env.info.scope.owner.kind == MTH ? Type.noType : syms.errType285: tree.vartype.type;286VarSymbol v = new VarSymbol(0, tree.name, vartype, enclScope.owner);287v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);288tree.sym = v;289if (tree.init != null) {290v.flags_field |= HASINIT;291if ((v.flags_field & FINAL) != 0 &&292needsLazyConstValue(tree.init)) {293Env<AttrContext> initEnv = getInitEnv(tree, env);294initEnv.info.enclVar = v;295v.setLazyConstValue(initEnv(tree, initEnv), attr, tree);296}297}298if (chk.checkUnique(tree.pos(), v, enclScope)) {299chk.checkTransparentVar(tree.pos(), v, enclScope);300enclScope.enter(v);301} else if (v.owner.kind == MTH || (v.flags_field & (Flags.PRIVATE | Flags.FINAL | Flags.GENERATED_MEMBER | Flags.RECORD)) != 0) {302// if this is a parameter or a field obtained from a record component, enter it303enclScope.enter(v);304}305306annotate.annotateLater(tree.mods.annotations, localEnv, v, tree.pos());307if (!tree.isImplicitlyTyped()) {308annotate.queueScanTreeAndTypeAnnotate(tree.vartype, localEnv, v, tree.pos());309}310311v.pos = tree.pos;312}313// where314void checkType(JCTree tree, Type type, Error errorKey) {315if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {316log.error(tree, errorKey);317}318}319void checkReceiver(JCVariableDecl tree, Env<AttrContext> localEnv) {320attr.attribExpr(tree.nameexpr, localEnv);321MethodSymbol m = localEnv.enclMethod.sym;322if (m.isConstructor()) {323Type outertype = m.owner.owner.type;324if (outertype.hasTag(TypeTag.METHOD)) {325// we have a local inner class326outertype = m.owner.owner.owner.type;327}328if (outertype.hasTag(TypeTag.CLASS)) {329checkType(tree.vartype, outertype, Errors.IncorrectConstructorReceiverType(outertype, tree.vartype.type));330checkType(tree.nameexpr, outertype, Errors.IncorrectConstructorReceiverName(outertype, tree.nameexpr.type));331} else {332log.error(tree, Errors.ReceiverParameterNotApplicableConstructorToplevelClass);333}334} else {335checkType(tree.vartype, m.owner.type, Errors.IncorrectReceiverType(m.owner.type, tree.vartype.type));336checkType(tree.nameexpr, m.owner.type, Errors.IncorrectReceiverName(m.owner.type, tree.nameexpr.type));337}338}339340public boolean needsLazyConstValue(JCTree tree) {341InitTreeVisitor initTreeVisitor = new InitTreeVisitor();342tree.accept(initTreeVisitor);343return initTreeVisitor.result;344}345346/** Visitor class for expressions which might be constant expressions,347* as per JLS 15.28 (Constant Expressions).348*/349static class InitTreeVisitor extends JCTree.Visitor {350351private static final Set<Tag> ALLOWED_OPERATORS =352EnumSet.of(Tag.POS, Tag.NEG, Tag.NOT, Tag.COMPL, Tag.PLUS, Tag.MINUS,353Tag.MUL, Tag.DIV, Tag.MOD, Tag.SL, Tag.SR, Tag.USR,354Tag.LT, Tag.LE, Tag.GT, Tag.GE, Tag.EQ, Tag.NE,355Tag.BITAND, Tag.BITXOR, Tag.BITOR, Tag.AND, Tag.OR);356357boolean result = true;358359@Override360public void visitTree(JCTree tree) {361result = false;362}363364@Override365public void visitLiteral(JCLiteral that) {}366367@Override368public void visitTypeCast(JCTypeCast tree) {369tree.expr.accept(this);370}371372@Override373public void visitUnary(JCUnary that) {374if (!ALLOWED_OPERATORS.contains(that.getTag())) {375result = false;376return ;377}378that.arg.accept(this);379}380381@Override382public void visitBinary(JCBinary that) {383if (!ALLOWED_OPERATORS.contains(that.getTag())) {384result = false;385return ;386}387that.lhs.accept(this);388that.rhs.accept(this);389}390391@Override392public void visitConditional(JCConditional tree) {393tree.cond.accept(this);394tree.truepart.accept(this);395tree.falsepart.accept(this);396}397398@Override399public void visitParens(JCParens tree) {400tree.expr.accept(this);401}402403@Override404public void visitIdent(JCIdent that) {}405406@Override407public void visitSelect(JCFieldAccess tree) {408tree.selected.accept(this);409}410}411412/** Create a fresh environment for a variable's initializer.413* If the variable is a field, the owner of the environment's scope414* is be the variable itself, otherwise the owner is the method415* enclosing the variable definition.416*417* @param tree The variable definition.418* @param env The environment current outside of the variable definition.419*/420Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {421Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));422if (tree.sym.owner.kind == TYP) {423localEnv.info.scope = env.info.scope.dupUnshared(tree.sym);424}425if ((tree.mods.flags & STATIC) != 0 ||426((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))427localEnv.info.staticLevel++;428return localEnv;429}430431/** Default member enter visitor method: do nothing432*/433public void visitTree(JCTree tree) {434}435436public void visitErroneous(JCErroneous tree) {437if (tree.errs != null)438memberEnter(tree.errs, env);439}440441public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {442Env<AttrContext> mEnv = methodEnv(tree, env);443mEnv.info.lint = mEnv.info.lint.augment(tree.sym);444for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)445mEnv.info.scope.enterIfAbsent(l.head.type.tsym);446for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)447mEnv.info.scope.enterIfAbsent(l.head.sym);448return mEnv;449}450451public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {452Env<AttrContext> iEnv = initEnv(tree, env);453return iEnv;454}455}456457458