aoqi@0: /* aoqi@0: * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. aoqi@0: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. aoqi@0: * aoqi@0: * This code is free software; you can redistribute it and/or modify it aoqi@0: * under the terms of the GNU General Public License version 2 only, as aoqi@0: * published by the Free Software Foundation. Oracle designates this aoqi@0: * particular file as subject to the "Classpath" exception as provided aoqi@0: * by Oracle in the LICENSE file that accompanied this code. aoqi@0: * aoqi@0: * This code is distributed in the hope that it will be useful, but WITHOUT aoqi@0: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or aoqi@0: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License aoqi@0: * version 2 for more details (a copy is included in the LICENSE file that aoqi@0: * accompanied this code). aoqi@0: * aoqi@0: * You should have received a copy of the GNU General Public License version aoqi@0: * 2 along with this work; if not, write to the Free Software Foundation, aoqi@0: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. aoqi@0: * aoqi@0: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA aoqi@0: * or visit www.oracle.com if you need additional information or have any aoqi@0: * questions. aoqi@0: */ aoqi@0: aoqi@0: package com.sun.tools.javac.comp; aoqi@0: aoqi@0: import java.util.*; aoqi@0: aoqi@0: import javax.lang.model.element.ElementKind; aoqi@0: import javax.tools.JavaFileObject; aoqi@0: aoqi@0: import com.sun.source.tree.IdentifierTree; aoqi@0: import com.sun.source.tree.MemberReferenceTree.ReferenceMode; aoqi@0: import com.sun.source.tree.MemberSelectTree; aoqi@0: import com.sun.source.tree.TreeVisitor; aoqi@0: import com.sun.source.util.SimpleTreeVisitor; aoqi@0: import com.sun.tools.javac.code.*; aoqi@0: import com.sun.tools.javac.code.Lint.LintCategory; aoqi@0: import com.sun.tools.javac.code.Symbol.*; aoqi@0: import com.sun.tools.javac.code.Type.*; aoqi@0: import com.sun.tools.javac.comp.Check.CheckContext; aoqi@0: import com.sun.tools.javac.comp.DeferredAttr.AttrMode; aoqi@0: import com.sun.tools.javac.comp.Infer.InferenceContext; aoqi@0: import com.sun.tools.javac.comp.Infer.FreeTypeListener; aoqi@0: import com.sun.tools.javac.jvm.*; aoqi@0: import com.sun.tools.javac.tree.*; aoqi@0: import com.sun.tools.javac.tree.JCTree.*; aoqi@0: import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; aoqi@0: import com.sun.tools.javac.util.*; aoqi@0: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; aoqi@0: import com.sun.tools.javac.util.List; aoqi@0: import static com.sun.tools.javac.code.Flags.*; aoqi@0: import static com.sun.tools.javac.code.Flags.ANNOTATION; aoqi@0: import static com.sun.tools.javac.code.Flags.BLOCK; aoqi@0: import static com.sun.tools.javac.code.Kinds.*; aoqi@0: import static com.sun.tools.javac.code.Kinds.ERRONEOUS; aoqi@0: import static com.sun.tools.javac.code.TypeTag.*; aoqi@0: import static com.sun.tools.javac.code.TypeTag.WILDCARD; aoqi@0: import static com.sun.tools.javac.tree.JCTree.Tag.*; aoqi@0: aoqi@0: /** This is the main context-dependent analysis phase in GJC. It aoqi@0: * encompasses name resolution, type checking and constant folding as aoqi@0: * subtasks. Some subtasks involve auxiliary classes. aoqi@0: * @see Check aoqi@0: * @see Resolve aoqi@0: * @see ConstFold aoqi@0: * @see Infer aoqi@0: * aoqi@0: *

This is NOT part of any supported API. aoqi@0: * If you write code that depends on this, you do so at your own risk. aoqi@0: * This code and its internal interfaces are subject to change or aoqi@0: * deletion without notice. aoqi@0: */ aoqi@0: public class Attr extends JCTree.Visitor { aoqi@0: protected static final Context.Key attrKey = aoqi@0: new Context.Key(); aoqi@0: aoqi@0: final Names names; aoqi@0: final Log log; aoqi@0: final Symtab syms; aoqi@0: final Resolve rs; aoqi@0: final Infer infer; aoqi@0: final DeferredAttr deferredAttr; aoqi@0: final Check chk; aoqi@0: final Flow flow; aoqi@0: final MemberEnter memberEnter; aoqi@0: final TreeMaker make; aoqi@0: final ConstFold cfolder; aoqi@0: final Enter enter; aoqi@0: final Target target; aoqi@0: final Types types; aoqi@0: final JCDiagnostic.Factory diags; aoqi@0: final Annotate annotate; aoqi@0: final TypeAnnotations typeAnnotations; aoqi@0: final DeferredLintHandler deferredLintHandler; aoqi@0: final TypeEnvs typeEnvs; aoqi@0: aoqi@0: public static Attr instance(Context context) { aoqi@0: Attr instance = context.get(attrKey); aoqi@0: if (instance == null) aoqi@0: instance = new Attr(context); aoqi@0: return instance; aoqi@0: } aoqi@0: aoqi@0: protected Attr(Context context) { aoqi@0: context.put(attrKey, this); aoqi@0: aoqi@0: names = Names.instance(context); aoqi@0: log = Log.instance(context); aoqi@0: syms = Symtab.instance(context); aoqi@0: rs = Resolve.instance(context); aoqi@0: chk = Check.instance(context); aoqi@0: flow = Flow.instance(context); aoqi@0: memberEnter = MemberEnter.instance(context); aoqi@0: make = TreeMaker.instance(context); aoqi@0: enter = Enter.instance(context); aoqi@0: infer = Infer.instance(context); aoqi@0: deferredAttr = DeferredAttr.instance(context); aoqi@0: cfolder = ConstFold.instance(context); aoqi@0: target = Target.instance(context); aoqi@0: types = Types.instance(context); aoqi@0: diags = JCDiagnostic.Factory.instance(context); aoqi@0: annotate = Annotate.instance(context); aoqi@0: typeAnnotations = TypeAnnotations.instance(context); aoqi@0: deferredLintHandler = DeferredLintHandler.instance(context); aoqi@0: typeEnvs = TypeEnvs.instance(context); aoqi@0: aoqi@0: Options options = Options.instance(context); aoqi@0: aoqi@0: Source source = Source.instance(context); aoqi@0: allowGenerics = source.allowGenerics(); aoqi@0: allowVarargs = source.allowVarargs(); aoqi@0: allowEnums = source.allowEnums(); aoqi@0: allowBoxing = source.allowBoxing(); aoqi@0: allowCovariantReturns = source.allowCovariantReturns(); aoqi@0: allowAnonOuterThis = source.allowAnonOuterThis(); aoqi@0: allowStringsInSwitch = source.allowStringsInSwitch(); aoqi@0: allowPoly = source.allowPoly(); aoqi@0: allowTypeAnnos = source.allowTypeAnnotations(); aoqi@0: allowLambda = source.allowLambda(); aoqi@0: allowDefaultMethods = source.allowDefaultMethods(); aoqi@0: allowStaticInterfaceMethods = source.allowStaticInterfaceMethods(); aoqi@0: sourceName = source.name; aoqi@0: relax = (options.isSet("-retrofit") || aoqi@0: options.isSet("-relax")); aoqi@0: findDiamonds = options.get("findDiamond") != null && aoqi@0: source.allowDiamond(); aoqi@0: useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); aoqi@0: identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false); aoqi@0: aoqi@0: statInfo = new ResultInfo(NIL, Type.noType); aoqi@0: varInfo = new ResultInfo(VAR, Type.noType); aoqi@0: unknownExprInfo = new ResultInfo(VAL, Type.noType); aoqi@0: unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly); aoqi@0: unknownTypeInfo = new ResultInfo(TYP, Type.noType); aoqi@0: unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType); aoqi@0: recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); aoqi@0: } aoqi@0: aoqi@0: /** Switch: relax some constraints for retrofit mode. aoqi@0: */ aoqi@0: boolean relax; aoqi@0: aoqi@0: /** Switch: support target-typing inference aoqi@0: */ aoqi@0: boolean allowPoly; aoqi@0: aoqi@0: /** Switch: support type annotations. aoqi@0: */ aoqi@0: boolean allowTypeAnnos; aoqi@0: aoqi@0: /** Switch: support generics? aoqi@0: */ aoqi@0: boolean allowGenerics; aoqi@0: aoqi@0: /** Switch: allow variable-arity methods. aoqi@0: */ aoqi@0: boolean allowVarargs; aoqi@0: aoqi@0: /** Switch: support enums? aoqi@0: */ aoqi@0: boolean allowEnums; aoqi@0: aoqi@0: /** Switch: support boxing and unboxing? aoqi@0: */ aoqi@0: boolean allowBoxing; aoqi@0: aoqi@0: /** Switch: support covariant result types? aoqi@0: */ aoqi@0: boolean allowCovariantReturns; aoqi@0: aoqi@0: /** Switch: support lambda expressions ? aoqi@0: */ aoqi@0: boolean allowLambda; aoqi@0: aoqi@0: /** Switch: support default methods ? aoqi@0: */ aoqi@0: boolean allowDefaultMethods; aoqi@0: aoqi@0: /** Switch: static interface methods enabled? aoqi@0: */ aoqi@0: boolean allowStaticInterfaceMethods; aoqi@0: aoqi@0: /** Switch: allow references to surrounding object from anonymous aoqi@0: * objects during constructor call? aoqi@0: */ aoqi@0: boolean allowAnonOuterThis; aoqi@0: aoqi@0: /** Switch: generates a warning if diamond can be safely applied aoqi@0: * to a given new expression aoqi@0: */ aoqi@0: boolean findDiamonds; aoqi@0: aoqi@0: /** aoqi@0: * Internally enables/disables diamond finder feature aoqi@0: */ aoqi@0: static final boolean allowDiamondFinder = true; aoqi@0: aoqi@0: /** aoqi@0: * Switch: warn about use of variable before declaration? aoqi@0: * RFE: 6425594 aoqi@0: */ aoqi@0: boolean useBeforeDeclarationWarning; aoqi@0: aoqi@0: /** aoqi@0: * Switch: generate warnings whenever an anonymous inner class that is convertible aoqi@0: * to a lambda expression is found aoqi@0: */ aoqi@0: boolean identifyLambdaCandidate; aoqi@0: aoqi@0: /** aoqi@0: * Switch: allow strings in switch? aoqi@0: */ aoqi@0: boolean allowStringsInSwitch; aoqi@0: aoqi@0: /** aoqi@0: * Switch: name of source level; used for error reporting. aoqi@0: */ aoqi@0: String sourceName; aoqi@0: aoqi@0: /** Check kind and type of given tree against protokind and prototype. aoqi@0: * If check succeeds, store type in tree and return it. aoqi@0: * If check fails, store errType in tree and return it. aoqi@0: * No checks are performed if the prototype is a method type. aoqi@0: * It is not necessary in this case since we know that kind and type aoqi@0: * are correct. aoqi@0: * aoqi@0: * @param tree The tree whose kind and type is checked aoqi@0: * @param ownkind The computed kind of the tree aoqi@0: * @param resultInfo The expected result of the tree aoqi@0: */ aoqi@0: Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) { aoqi@0: InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); vromero@2543: Type owntype; vromero@2543: if (!found.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) { vromero@2543: if ((ownkind & ~resultInfo.pkind) != 0) { vromero@2543: log.error(tree.pos(), "unexpected.type", vromero@2543: kindNames(resultInfo.pkind), vromero@2543: kindName(ownkind)); vromero@2543: owntype = types.createErrorType(found); vromero@2543: } else if (allowPoly && inferenceContext.free(found)) { vromero@2543: //delay the check if there are inference variables in the found type vromero@2543: //this means we are dealing with a partially inferred poly expression vromero@2543: owntype = resultInfo.pt; aoqi@0: inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() { aoqi@0: @Override aoqi@0: public void typesInferred(InferenceContext inferenceContext) { aoqi@0: ResultInfo pendingResult = vromero@2543: resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); aoqi@0: check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); aoqi@0: } aoqi@0: }); aoqi@0: } else { vromero@2543: owntype = resultInfo.check(tree, found); aoqi@0: } vromero@2543: } else { vromero@2543: owntype = found; aoqi@0: } aoqi@0: tree.type = owntype; aoqi@0: return owntype; aoqi@0: } aoqi@0: aoqi@0: /** Is given blank final variable assignable, i.e. in a scope where it aoqi@0: * may be assigned to even though it is final? aoqi@0: * @param v The blank final variable. aoqi@0: * @param env The current environment. aoqi@0: */ aoqi@0: boolean isAssignableAsBlankFinal(VarSymbol v, Env env) { mcimadamore@2558: Symbol owner = env.info.scope.owner; aoqi@0: // owner refers to the innermost variable, method or aoqi@0: // initializer block declaration at this point. aoqi@0: return aoqi@0: v.owner == owner aoqi@0: || aoqi@0: ((owner.name == names.init || // i.e. we are in a constructor aoqi@0: owner.kind == VAR || // i.e. we are in a variable initializer aoqi@0: (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block aoqi@0: && aoqi@0: v.owner == owner.owner aoqi@0: && aoqi@0: ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); aoqi@0: } aoqi@0: aoqi@0: /** Check that variable can be assigned to. aoqi@0: * @param pos The current source code position. aoqi@0: * @param v The assigned varaible aoqi@0: * @param base If the variable is referred to in a Select, the part aoqi@0: * to the left of the `.', null otherwise. aoqi@0: * @param env The current environment. aoqi@0: */ aoqi@0: void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env env) { aoqi@0: if ((v.flags() & FINAL) != 0 && aoqi@0: ((v.flags() & HASINIT) != 0 aoqi@0: || aoqi@0: !((base == null || aoqi@0: (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) && aoqi@0: isAssignableAsBlankFinal(v, env)))) { aoqi@0: if (v.isResourceVariable()) { //TWR resource aoqi@0: log.error(pos, "try.resource.may.not.be.assigned", v); aoqi@0: } else { aoqi@0: log.error(pos, "cant.assign.val.to.final.var", v); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Does tree represent a static reference to an identifier? aoqi@0: * It is assumed that tree is either a SELECT or an IDENT. aoqi@0: * We have to weed out selects from non-type names here. aoqi@0: * @param tree The candidate tree. aoqi@0: */ aoqi@0: boolean isStaticReference(JCTree tree) { aoqi@0: if (tree.hasTag(SELECT)) { aoqi@0: Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); aoqi@0: if (lsym == null || lsym.kind != TYP) { aoqi@0: return false; aoqi@0: } aoqi@0: } aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: /** Is this symbol a type? aoqi@0: */ aoqi@0: static boolean isType(Symbol sym) { aoqi@0: return sym != null && sym.kind == TYP; aoqi@0: } aoqi@0: aoqi@0: /** The current `this' symbol. aoqi@0: * @param env The current environment. aoqi@0: */ aoqi@0: Symbol thisSym(DiagnosticPosition pos, Env env) { aoqi@0: return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); aoqi@0: } aoqi@0: aoqi@0: /** Attribute a parsed identifier. aoqi@0: * @param tree Parsed identifier name aoqi@0: * @param topLevel The toplevel to use aoqi@0: */ aoqi@0: public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { aoqi@0: Env localEnv = enter.topLevelEnv(topLevel); aoqi@0: localEnv.enclClass = make.ClassDef(make.Modifiers(0), aoqi@0: syms.errSymbol.name, aoqi@0: null, null, null, null); aoqi@0: localEnv.enclClass.sym = syms.errSymbol; aoqi@0: return tree.accept(identAttributer, localEnv); aoqi@0: } aoqi@0: // where aoqi@0: private TreeVisitor> identAttributer = new IdentAttributer(); aoqi@0: private class IdentAttributer extends SimpleTreeVisitor> { aoqi@0: @Override aoqi@0: public Symbol visitMemberSelect(MemberSelectTree node, Env env) { aoqi@0: Symbol site = visit(node.getExpression(), env); aoqi@0: if (site.kind == ERR || site.kind == ABSENT_TYP) aoqi@0: return site; aoqi@0: Name name = (Name)node.getIdentifier(); aoqi@0: if (site.kind == PCK) { aoqi@0: env.toplevel.packge = (PackageSymbol)site; aoqi@0: return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK); aoqi@0: } else { aoqi@0: env.enclClass.sym = (ClassSymbol)site; aoqi@0: return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public Symbol visitIdentifier(IdentifierTree node, Env env) { aoqi@0: return rs.findIdent(env, (Name)node.getName(), TYP | PCK); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public Type coerce(Type etype, Type ttype) { aoqi@0: return cfolder.coerce(etype, ttype); aoqi@0: } aoqi@0: aoqi@0: public Type attribType(JCTree node, TypeSymbol sym) { aoqi@0: Env env = typeEnvs.get(sym); aoqi@0: Env localEnv = env.dup(node, env.info.dup()); aoqi@0: return attribTree(node, localEnv, unknownTypeInfo); aoqi@0: } aoqi@0: aoqi@0: public Type attribImportQualifier(JCImport tree, Env env) { aoqi@0: // Attribute qualifying package or class. aoqi@0: JCFieldAccess s = (JCFieldAccess)tree.qualid; aoqi@0: return attribTree(s.selected, aoqi@0: env, aoqi@0: new ResultInfo(tree.staticImport ? TYP : (TYP | PCK), aoqi@0: Type.noType)); aoqi@0: } aoqi@0: aoqi@0: public Env attribExprToTree(JCTree expr, Env env, JCTree tree) { aoqi@0: breakTree = tree; aoqi@0: JavaFileObject prev = log.useSource(env.toplevel.sourcefile); aoqi@0: try { aoqi@0: attribExpr(expr, env); aoqi@0: } catch (BreakAttr b) { aoqi@0: return b.env; aoqi@0: } catch (AssertionError ae) { aoqi@0: if (ae.getCause() instanceof BreakAttr) { aoqi@0: return ((BreakAttr)(ae.getCause())).env; aoqi@0: } else { aoqi@0: throw ae; aoqi@0: } aoqi@0: } finally { aoqi@0: breakTree = null; aoqi@0: log.useSource(prev); aoqi@0: } aoqi@0: return env; aoqi@0: } aoqi@0: aoqi@0: public Env attribStatToTree(JCTree stmt, Env env, JCTree tree) { aoqi@0: breakTree = tree; aoqi@0: JavaFileObject prev = log.useSource(env.toplevel.sourcefile); aoqi@0: try { aoqi@0: attribStat(stmt, env); aoqi@0: } catch (BreakAttr b) { aoqi@0: return b.env; aoqi@0: } catch (AssertionError ae) { aoqi@0: if (ae.getCause() instanceof BreakAttr) { aoqi@0: return ((BreakAttr)(ae.getCause())).env; aoqi@0: } else { aoqi@0: throw ae; aoqi@0: } aoqi@0: } finally { aoqi@0: breakTree = null; aoqi@0: log.useSource(prev); aoqi@0: } aoqi@0: return env; aoqi@0: } aoqi@0: aoqi@0: private JCTree breakTree = null; aoqi@0: aoqi@0: private static class BreakAttr extends RuntimeException { aoqi@0: static final long serialVersionUID = -6924771130405446405L; aoqi@0: private Env env; aoqi@0: private BreakAttr(Env env) { aoqi@0: this.env = env; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: class ResultInfo { aoqi@0: final int pkind; aoqi@0: final Type pt; aoqi@0: final CheckContext checkContext; aoqi@0: aoqi@0: ResultInfo(int pkind, Type pt) { aoqi@0: this(pkind, pt, chk.basicHandler); aoqi@0: } aoqi@0: aoqi@0: protected ResultInfo(int pkind, Type pt, CheckContext checkContext) { aoqi@0: this.pkind = pkind; aoqi@0: this.pt = pt; aoqi@0: this.checkContext = checkContext; aoqi@0: } aoqi@0: aoqi@0: protected Type check(final DiagnosticPosition pos, final Type found) { aoqi@0: return chk.checkType(pos, found, pt, checkContext); aoqi@0: } aoqi@0: aoqi@0: protected ResultInfo dup(Type newPt) { aoqi@0: return new ResultInfo(pkind, newPt, checkContext); aoqi@0: } aoqi@0: aoqi@0: protected ResultInfo dup(CheckContext newContext) { aoqi@0: return new ResultInfo(pkind, pt, newContext); aoqi@0: } aoqi@0: aoqi@0: protected ResultInfo dup(Type newPt, CheckContext newContext) { aoqi@0: return new ResultInfo(pkind, newPt, newContext); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public String toString() { aoqi@0: if (pt != null) { aoqi@0: return pt.toString(); aoqi@0: } else { aoqi@0: return ""; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: class RecoveryInfo extends ResultInfo { aoqi@0: aoqi@0: public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { aoqi@0: super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) { aoqi@0: @Override aoqi@0: public DeferredAttr.DeferredAttrContext deferredAttrContext() { aoqi@0: return deferredAttrContext; aoqi@0: } aoqi@0: @Override aoqi@0: public boolean compatible(Type found, Type req, Warner warn) { aoqi@0: return true; aoqi@0: } aoqi@0: @Override aoqi@0: public void report(DiagnosticPosition pos, JCDiagnostic details) { aoqi@0: chk.basicHandler.report(pos, details); aoqi@0: } aoqi@0: }); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: final ResultInfo statInfo; aoqi@0: final ResultInfo varInfo; aoqi@0: final ResultInfo unknownAnyPolyInfo; aoqi@0: final ResultInfo unknownExprInfo; aoqi@0: final ResultInfo unknownTypeInfo; aoqi@0: final ResultInfo unknownTypeExprInfo; aoqi@0: final ResultInfo recoveryInfo; aoqi@0: aoqi@0: Type pt() { aoqi@0: return resultInfo.pt; aoqi@0: } aoqi@0: aoqi@0: int pkind() { aoqi@0: return resultInfo.pkind; aoqi@0: } aoqi@0: aoqi@0: /* ************************************************************************ aoqi@0: * Visitor methods aoqi@0: *************************************************************************/ aoqi@0: aoqi@0: /** Visitor argument: the current environment. aoqi@0: */ aoqi@0: Env env; aoqi@0: aoqi@0: /** Visitor argument: the currently expected attribution result. aoqi@0: */ aoqi@0: ResultInfo resultInfo; aoqi@0: aoqi@0: /** Visitor result: the computed type. aoqi@0: */ aoqi@0: Type result; aoqi@0: aoqi@0: /** Visitor method: attribute a tree, catching any completion failure aoqi@0: * exceptions. Return the tree's type. aoqi@0: * aoqi@0: * @param tree The tree to be visited. aoqi@0: * @param env The environment visitor argument. aoqi@0: * @param resultInfo The result info visitor argument. aoqi@0: */ aoqi@0: Type attribTree(JCTree tree, Env env, ResultInfo resultInfo) { aoqi@0: Env prevEnv = this.env; aoqi@0: ResultInfo prevResult = this.resultInfo; aoqi@0: try { aoqi@0: this.env = env; aoqi@0: this.resultInfo = resultInfo; aoqi@0: tree.accept(this); aoqi@0: if (tree == breakTree && aoqi@0: resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { aoqi@0: throw new BreakAttr(copyEnv(env)); aoqi@0: } aoqi@0: return result; aoqi@0: } catch (CompletionFailure ex) { aoqi@0: tree.type = syms.errType; aoqi@0: return chk.completionError(tree.pos(), ex); aoqi@0: } finally { aoqi@0: this.env = prevEnv; aoqi@0: this.resultInfo = prevResult; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: Env copyEnv(Env env) { aoqi@0: Env newEnv = aoqi@0: env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); aoqi@0: if (newEnv.outer != null) { aoqi@0: newEnv.outer = copyEnv(newEnv.outer); aoqi@0: } aoqi@0: return newEnv; aoqi@0: } aoqi@0: aoqi@0: Scope copyScope(Scope sc) { aoqi@0: Scope newScope = new Scope(sc.owner); aoqi@0: List elemsList = List.nil(); aoqi@0: while (sc != null) { aoqi@0: for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) { aoqi@0: elemsList = elemsList.prepend(e.sym); aoqi@0: } aoqi@0: sc = sc.next; aoqi@0: } aoqi@0: for (Symbol s : elemsList) { aoqi@0: newScope.enter(s); aoqi@0: } aoqi@0: return newScope; aoqi@0: } aoqi@0: aoqi@0: /** Derived visitor method: attribute an expression tree. aoqi@0: */ aoqi@0: public Type attribExpr(JCTree tree, Env env, Type pt) { aoqi@0: return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); aoqi@0: } aoqi@0: aoqi@0: /** Derived visitor method: attribute an expression tree with aoqi@0: * no constraints on the computed type. aoqi@0: */ aoqi@0: public Type attribExpr(JCTree tree, Env env) { aoqi@0: return attribTree(tree, env, unknownExprInfo); aoqi@0: } aoqi@0: aoqi@0: /** Derived visitor method: attribute a type tree. aoqi@0: */ aoqi@0: public Type attribType(JCTree tree, Env env) { aoqi@0: Type result = attribType(tree, env, Type.noType); aoqi@0: return result; aoqi@0: } aoqi@0: aoqi@0: /** Derived visitor method: attribute a type tree. aoqi@0: */ aoqi@0: Type attribType(JCTree tree, Env env, Type pt) { aoqi@0: Type result = attribTree(tree, env, new ResultInfo(TYP, pt)); aoqi@0: return result; aoqi@0: } aoqi@0: aoqi@0: /** Derived visitor method: attribute a statement or definition tree. aoqi@0: */ aoqi@0: public Type attribStat(JCTree tree, Env env) { aoqi@0: return attribTree(tree, env, statInfo); aoqi@0: } aoqi@0: aoqi@0: /** Attribute a list of expressions, returning a list of types. aoqi@0: */ aoqi@0: List attribExprs(List trees, Env env, Type pt) { aoqi@0: ListBuffer ts = new ListBuffer(); aoqi@0: for (List l = trees; l.nonEmpty(); l = l.tail) aoqi@0: ts.append(attribExpr(l.head, env, pt)); aoqi@0: return ts.toList(); aoqi@0: } aoqi@0: aoqi@0: /** Attribute a list of statements, returning nothing. aoqi@0: */ aoqi@0: void attribStats(List trees, Env env) { aoqi@0: for (List l = trees; l.nonEmpty(); l = l.tail) aoqi@0: attribStat(l.head, env); aoqi@0: } aoqi@0: aoqi@0: /** Attribute the arguments in a method call, returning the method kind. aoqi@0: */ aoqi@0: int attribArgs(List trees, Env env, ListBuffer argtypes) { aoqi@0: int kind = VAL; aoqi@0: for (JCExpression arg : trees) { aoqi@0: Type argtype; aoqi@0: if (allowPoly && deferredAttr.isDeferred(env, arg)) { aoqi@0: argtype = deferredAttr.new DeferredType(arg, env); aoqi@0: kind |= POLY; aoqi@0: } else { aoqi@0: argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo)); aoqi@0: } aoqi@0: argtypes.append(argtype); aoqi@0: } aoqi@0: return kind; aoqi@0: } aoqi@0: aoqi@0: /** Attribute a type argument list, returning a list of types. aoqi@0: * Caller is responsible for calling checkRefTypes. aoqi@0: */ aoqi@0: List attribAnyTypes(List trees, Env env) { aoqi@0: ListBuffer argtypes = new ListBuffer(); aoqi@0: for (List l = trees; l.nonEmpty(); l = l.tail) aoqi@0: argtypes.append(attribType(l.head, env)); aoqi@0: return argtypes.toList(); aoqi@0: } aoqi@0: aoqi@0: /** Attribute a type argument list, returning a list of types. aoqi@0: * Check that all the types are references. aoqi@0: */ aoqi@0: List attribTypes(List trees, Env env) { aoqi@0: List types = attribAnyTypes(trees, env); aoqi@0: return chk.checkRefTypes(trees, types); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Attribute type variables (of generic classes or methods). aoqi@0: * Compound types are attributed later in attribBounds. aoqi@0: * @param typarams the type variables to enter aoqi@0: * @param env the current environment aoqi@0: */ aoqi@0: void attribTypeVariables(List typarams, Env env) { aoqi@0: for (JCTypeParameter tvar : typarams) { aoqi@0: TypeVar a = (TypeVar)tvar.type; aoqi@0: a.tsym.flags_field |= UNATTRIBUTED; aoqi@0: a.bound = Type.noType; aoqi@0: if (!tvar.bounds.isEmpty()) { aoqi@0: List bounds = List.of(attribType(tvar.bounds.head, env)); aoqi@0: for (JCExpression bound : tvar.bounds.tail) aoqi@0: bounds = bounds.prepend(attribType(bound, env)); aoqi@0: types.setBounds(a, bounds.reverse()); aoqi@0: } else { aoqi@0: // if no bounds are given, assume a single bound of aoqi@0: // java.lang.Object. aoqi@0: types.setBounds(a, List.of(syms.objectType)); aoqi@0: } aoqi@0: a.tsym.flags_field &= ~UNATTRIBUTED; aoqi@0: } aoqi@0: for (JCTypeParameter tvar : typarams) { aoqi@0: chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Attribute the type references in a list of annotations. aoqi@0: */ aoqi@0: void attribAnnotationTypes(List annotations, aoqi@0: Env env) { aoqi@0: for (List al = annotations; al.nonEmpty(); al = al.tail) { aoqi@0: JCAnnotation a = al.head; aoqi@0: attribType(a.annotationType, env); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Attribute a "lazy constant value". aoqi@0: * @param env The env for the const value aoqi@0: * @param initializer The initializer for the const value aoqi@0: * @param type The expected type, or null aoqi@0: * @see VarSymbol#setLazyConstValue aoqi@0: */ aoqi@0: public Object attribLazyConstantValue(Env env, aoqi@0: JCVariableDecl variable, aoqi@0: Type type) { aoqi@0: aoqi@0: DiagnosticPosition prevLintPos aoqi@0: = deferredLintHandler.setPos(variable.pos()); aoqi@0: aoqi@0: try { aoqi@0: // Use null as symbol to not attach the type annotation to any symbol. aoqi@0: // The initializer will later also be visited and then we'll attach aoqi@0: // to the symbol. aoqi@0: // This prevents having multiple type annotations, just because of aoqi@0: // lazy constant value evaluation. aoqi@0: memberEnter.typeAnnotate(variable.init, env, null, variable.pos()); aoqi@0: annotate.flush(); aoqi@0: Type itype = attribExpr(variable.init, env, type); aoqi@0: if (itype.constValue() != null) { aoqi@0: return coerce(itype, type).constValue(); aoqi@0: } else { aoqi@0: return null; aoqi@0: } aoqi@0: } finally { aoqi@0: deferredLintHandler.setPos(prevLintPos); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Attribute type reference in an `extends' or `implements' clause. aoqi@0: * Supertypes of anonymous inner classes are usually already attributed. aoqi@0: * aoqi@0: * @param tree The tree making up the type reference. aoqi@0: * @param env The environment current at the reference. aoqi@0: * @param classExpected true if only a class is expected here. aoqi@0: * @param interfaceExpected true if only an interface is expected here. aoqi@0: */ aoqi@0: Type attribBase(JCTree tree, aoqi@0: Env env, aoqi@0: boolean classExpected, aoqi@0: boolean interfaceExpected, aoqi@0: boolean checkExtensible) { aoqi@0: Type t = tree.type != null ? aoqi@0: tree.type : aoqi@0: attribType(tree, env); aoqi@0: return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); aoqi@0: } aoqi@0: Type checkBase(Type t, aoqi@0: JCTree tree, aoqi@0: Env env, aoqi@0: boolean classExpected, aoqi@0: boolean interfaceExpected, aoqi@0: boolean checkExtensible) { aoqi@0: if (t.tsym.isAnonymous()) { aoqi@0: log.error(tree.pos(), "cant.inherit.from.anon"); aoqi@0: return types.createErrorType(t); aoqi@0: } aoqi@0: if (t.isErroneous()) aoqi@0: return t; aoqi@0: if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { aoqi@0: // check that type variable is already visible aoqi@0: if (t.getUpperBound() == null) { aoqi@0: log.error(tree.pos(), "illegal.forward.ref"); aoqi@0: return types.createErrorType(t); aoqi@0: } aoqi@0: } else { aoqi@0: t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics); aoqi@0: } aoqi@0: if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { aoqi@0: log.error(tree.pos(), "intf.expected.here"); aoqi@0: // return errType is necessary since otherwise there might aoqi@0: // be undetected cycles which cause attribution to loop aoqi@0: return types.createErrorType(t); aoqi@0: } else if (checkExtensible && aoqi@0: classExpected && aoqi@0: (t.tsym.flags() & INTERFACE) != 0) { aoqi@0: log.error(tree.pos(), "no.intf.expected.here"); aoqi@0: return types.createErrorType(t); aoqi@0: } aoqi@0: if (checkExtensible && aoqi@0: ((t.tsym.flags() & FINAL) != 0)) { aoqi@0: log.error(tree.pos(), aoqi@0: "cant.inherit.from.final", t.tsym); aoqi@0: } aoqi@0: chk.checkNonCyclic(tree.pos(), t); aoqi@0: return t; aoqi@0: } aoqi@0: aoqi@0: Type attribIdentAsEnumType(Env env, JCIdent id) { aoqi@0: Assert.check((env.enclClass.sym.flags() & ENUM) != 0); aoqi@0: id.type = env.info.scope.owner.type; aoqi@0: id.sym = env.info.scope.owner; aoqi@0: return id.type; aoqi@0: } aoqi@0: aoqi@0: public void visitClassDef(JCClassDecl tree) { aoqi@0: // Local classes have not been entered yet, so we need to do it now: aoqi@0: if ((env.info.scope.owner.kind & (VAR | MTH)) != 0) aoqi@0: enter.classEnter(tree, env); aoqi@0: aoqi@0: ClassSymbol c = tree.sym; aoqi@0: if (c == null) { aoqi@0: // exit in case something drastic went wrong during enter. aoqi@0: result = null; aoqi@0: } else { aoqi@0: // make sure class has been completed: aoqi@0: c.complete(); aoqi@0: aoqi@0: // If this class appears as an anonymous class aoqi@0: // in a superclass constructor call where aoqi@0: // no explicit outer instance is given, aoqi@0: // disable implicit outer instance from being passed. aoqi@0: // (This would be an illegal access to "this before super"). aoqi@0: if (env.info.isSelfCall && aoqi@0: env.tree.hasTag(NEWCLASS) && aoqi@0: ((JCNewClass) env.tree).encl == null) aoqi@0: { aoqi@0: c.flags_field |= NOOUTERTHIS; aoqi@0: } aoqi@0: attribClass(tree.pos(), c); aoqi@0: result = tree.type = c.type; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitMethodDef(JCMethodDecl tree) { aoqi@0: MethodSymbol m = tree.sym; aoqi@0: boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; aoqi@0: aoqi@0: Lint lint = env.info.lint.augment(m); aoqi@0: Lint prevLint = chk.setLint(lint); aoqi@0: MethodSymbol prevMethod = chk.setMethod(m); aoqi@0: try { aoqi@0: deferredLintHandler.flush(tree.pos()); aoqi@0: chk.checkDeprecatedAnnotation(tree.pos(), m); aoqi@0: aoqi@0: aoqi@0: // Create a new environment with local scope aoqi@0: // for attributing the method. aoqi@0: Env localEnv = memberEnter.methodEnv(tree, env); aoqi@0: localEnv.info.lint = lint; aoqi@0: aoqi@0: attribStats(tree.typarams, localEnv); aoqi@0: aoqi@0: // If we override any other methods, check that we do so properly. aoqi@0: // JLS ??? aoqi@0: if (m.isStatic()) { aoqi@0: chk.checkHideClashes(tree.pos(), env.enclClass.type, m); aoqi@0: } else { aoqi@0: chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); aoqi@0: } aoqi@0: chk.checkOverride(tree, m); aoqi@0: aoqi@0: if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { aoqi@0: log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); aoqi@0: } aoqi@0: aoqi@0: // Enter all type parameters into the local method scope. aoqi@0: for (List l = tree.typarams; l.nonEmpty(); l = l.tail) aoqi@0: localEnv.info.scope.enterIfAbsent(l.head.type.tsym); aoqi@0: aoqi@0: ClassSymbol owner = env.enclClass.sym; aoqi@0: if ((owner.flags() & ANNOTATION) != 0 && aoqi@0: tree.params.nonEmpty()) aoqi@0: log.error(tree.params.head.pos(), aoqi@0: "intf.annotation.members.cant.have.params"); aoqi@0: aoqi@0: // Attribute all value parameters. aoqi@0: for (List l = tree.params; l.nonEmpty(); l = l.tail) { aoqi@0: attribStat(l.head, localEnv); aoqi@0: } aoqi@0: aoqi@0: chk.checkVarargsMethodDecl(localEnv, tree); aoqi@0: aoqi@0: // Check that type parameters are well-formed. aoqi@0: chk.validate(tree.typarams, localEnv); aoqi@0: aoqi@0: // Check that result type is well-formed. aoqi@0: if (tree.restype != null && !tree.restype.type.hasTag(VOID)) aoqi@0: chk.validate(tree.restype, localEnv); aoqi@0: aoqi@0: // Check that receiver type is well-formed. aoqi@0: if (tree.recvparam != null) { aoqi@0: // Use a new environment to check the receiver parameter. aoqi@0: // Otherwise I get "might not have been initialized" errors. aoqi@0: // Is there a better way? aoqi@0: Env newEnv = memberEnter.methodEnv(tree, env); aoqi@0: attribType(tree.recvparam, newEnv); aoqi@0: chk.validate(tree.recvparam, newEnv); aoqi@0: } aoqi@0: aoqi@0: // annotation method checks aoqi@0: if ((owner.flags() & ANNOTATION) != 0) { aoqi@0: // annotation method cannot have throws clause aoqi@0: if (tree.thrown.nonEmpty()) { aoqi@0: log.error(tree.thrown.head.pos(), aoqi@0: "throws.not.allowed.in.intf.annotation"); aoqi@0: } aoqi@0: // annotation method cannot declare type-parameters aoqi@0: if (tree.typarams.nonEmpty()) { aoqi@0: log.error(tree.typarams.head.pos(), aoqi@0: "intf.annotation.members.cant.have.type.params"); aoqi@0: } aoqi@0: // validate annotation method's return type (could be an annotation type) aoqi@0: chk.validateAnnotationType(tree.restype); aoqi@0: // ensure that annotation method does not clash with members of Object/Annotation aoqi@0: chk.validateAnnotationMethod(tree.pos(), m); aoqi@0: } aoqi@0: aoqi@0: for (List l = tree.thrown; l.nonEmpty(); l = l.tail) aoqi@0: chk.checkType(l.head.pos(), l.head.type, syms.throwableType); aoqi@0: aoqi@0: if (tree.body == null) { aoqi@0: // Empty bodies are only allowed for aoqi@0: // abstract, native, or interface methods, or for methods aoqi@0: // in a retrofit signature class. aoqi@0: if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 && aoqi@0: !relax) aoqi@0: log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); aoqi@0: if (tree.defaultValue != null) { aoqi@0: if ((owner.flags() & ANNOTATION) == 0) aoqi@0: log.error(tree.pos(), aoqi@0: "default.allowed.in.intf.annotation.member"); aoqi@0: } aoqi@0: } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) { aoqi@0: if ((owner.flags() & INTERFACE) != 0) { aoqi@0: log.error(tree.body.pos(), "intf.meth.cant.have.body"); aoqi@0: } else { aoqi@0: log.error(tree.pos(), "abstract.meth.cant.have.body"); aoqi@0: } aoqi@0: } else if ((tree.mods.flags & NATIVE) != 0) { aoqi@0: log.error(tree.pos(), "native.meth.cant.have.body"); aoqi@0: } else { aoqi@0: // Add an implicit super() call unless an explicit call to aoqi@0: // super(...) or this(...) is given aoqi@0: // or we are compiling class java.lang.Object. aoqi@0: if (tree.name == names.init && owner.type != syms.objectType) { aoqi@0: JCBlock body = tree.body; aoqi@0: if (body.stats.isEmpty() || aoqi@0: !TreeInfo.isSelfCall(body.stats.head)) { aoqi@0: body.stats = body.stats. aoqi@0: prepend(memberEnter.SuperCall(make.at(body.pos), aoqi@0: List.nil(), aoqi@0: List.nil(), aoqi@0: false)); aoqi@0: } else if ((env.enclClass.sym.flags() & ENUM) != 0 && aoqi@0: (tree.mods.flags & GENERATEDCONSTR) == 0 && aoqi@0: TreeInfo.isSuperCall(body.stats.head)) { aoqi@0: // enum constructors are not allowed to call super aoqi@0: // directly, so make sure there aren't any super calls aoqi@0: // in enum constructors, except in the compiler aoqi@0: // generated one. aoqi@0: log.error(tree.body.stats.head.pos(), aoqi@0: "call.to.super.not.allowed.in.enum.ctor", aoqi@0: env.enclClass.sym); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Attribute all type annotations in the body aoqi@0: memberEnter.typeAnnotate(tree.body, localEnv, m, null); aoqi@0: annotate.flush(); aoqi@0: aoqi@0: // Attribute method body. aoqi@0: attribStat(tree.body, localEnv); aoqi@0: } aoqi@0: aoqi@0: localEnv.info.scope.leave(); aoqi@0: result = tree.type = m.type; aoqi@0: } aoqi@0: finally { aoqi@0: chk.setLint(prevLint); aoqi@0: chk.setMethod(prevMethod); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitVarDef(JCVariableDecl tree) { aoqi@0: // Local variables have not been entered yet, so we need to do it now: aoqi@0: if (env.info.scope.owner.kind == MTH) { aoqi@0: if (tree.sym != null) { aoqi@0: // parameters have already been entered aoqi@0: env.info.scope.enter(tree.sym); aoqi@0: } else { jfranck@2596: try { jfranck@2596: annotate.enterStart(); jfranck@2596: memberEnter.memberEnter(tree, env); jfranck@2596: } finally { jfranck@2596: annotate.enterDone(); jfranck@2596: } aoqi@0: } aoqi@0: } else { aoqi@0: if (tree.init != null) { aoqi@0: // Field initializer expression need to be entered. aoqi@0: memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos()); aoqi@0: annotate.flush(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: VarSymbol v = tree.sym; aoqi@0: Lint lint = env.info.lint.augment(v); aoqi@0: Lint prevLint = chk.setLint(lint); aoqi@0: aoqi@0: // Check that the variable's declared type is well-formed. aoqi@0: boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) && aoqi@0: ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT && aoqi@0: (tree.sym.flags() & PARAMETER) != 0; aoqi@0: chk.validate(tree.vartype, env, !isImplicitLambdaParameter); aoqi@0: aoqi@0: try { aoqi@0: v.getConstValue(); // ensure compile-time constant initializer is evaluated aoqi@0: deferredLintHandler.flush(tree.pos()); aoqi@0: chk.checkDeprecatedAnnotation(tree.pos(), v); aoqi@0: aoqi@0: if (tree.init != null) { aoqi@0: if ((v.flags_field & FINAL) == 0 || aoqi@0: !memberEnter.needsLazyConstValue(tree.init)) { aoqi@0: // Not a compile-time constant aoqi@0: // Attribute initializer in a new environment aoqi@0: // with the declared variable as owner. aoqi@0: // Check that initializer conforms to variable's declared type. aoqi@0: Env initEnv = memberEnter.initEnv(tree, env); aoqi@0: initEnv.info.lint = lint; aoqi@0: // In order to catch self-references, we set the variable's aoqi@0: // declaration position to maximal possible value, effectively aoqi@0: // marking the variable as undefined. aoqi@0: initEnv.info.enclVar = v; aoqi@0: attribExpr(tree.init, initEnv, v.type); aoqi@0: } aoqi@0: } aoqi@0: result = tree.type = v.type; aoqi@0: } aoqi@0: finally { aoqi@0: chk.setLint(prevLint); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitSkip(JCSkip tree) { aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitBlock(JCBlock tree) { aoqi@0: if (env.info.scope.owner.kind == TYP) { aoqi@0: // Block is a static or instance initializer; aoqi@0: // let the owner of the environment be a freshly aoqi@0: // created BLOCK-method. aoqi@0: Env localEnv = aoqi@0: env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); aoqi@0: localEnv.info.scope.owner = aoqi@0: new MethodSymbol(tree.flags | BLOCK | aoqi@0: env.info.scope.owner.flags() & STRICTFP, names.empty, null, aoqi@0: env.info.scope.owner); aoqi@0: if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; aoqi@0: aoqi@0: // Attribute all type annotations in the block aoqi@0: memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null); aoqi@0: annotate.flush(); aoqi@0: aoqi@0: { aoqi@0: // Store init and clinit type annotations with the ClassSymbol aoqi@0: // to allow output in Gen.normalizeDefs. aoqi@0: ClassSymbol cs = (ClassSymbol)env.info.scope.owner; aoqi@0: List tas = localEnv.info.scope.owner.getRawTypeAttributes(); aoqi@0: if ((tree.flags & STATIC) != 0) { aoqi@0: cs.appendClassInitTypeAttributes(tas); aoqi@0: } else { aoqi@0: cs.appendInitTypeAttributes(tas); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: attribStats(tree.stats, localEnv); aoqi@0: } else { aoqi@0: // Create a new local environment with a local scope. aoqi@0: Env localEnv = aoqi@0: env.dup(tree, env.info.dup(env.info.scope.dup())); aoqi@0: try { aoqi@0: attribStats(tree.stats, localEnv); aoqi@0: } finally { aoqi@0: localEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitDoLoop(JCDoWhileLoop tree) { aoqi@0: attribStat(tree.body, env.dup(tree)); aoqi@0: attribExpr(tree.cond, env, syms.booleanType); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitWhileLoop(JCWhileLoop tree) { aoqi@0: attribExpr(tree.cond, env, syms.booleanType); aoqi@0: attribStat(tree.body, env.dup(tree)); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitForLoop(JCForLoop tree) { aoqi@0: Env loopEnv = aoqi@0: env.dup(env.tree, env.info.dup(env.info.scope.dup())); aoqi@0: try { aoqi@0: attribStats(tree.init, loopEnv); aoqi@0: if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); aoqi@0: loopEnv.tree = tree; // before, we were not in loop! aoqi@0: attribStats(tree.step, loopEnv); aoqi@0: attribStat(tree.body, loopEnv); aoqi@0: result = null; aoqi@0: } aoqi@0: finally { aoqi@0: loopEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitForeachLoop(JCEnhancedForLoop tree) { aoqi@0: Env loopEnv = aoqi@0: env.dup(env.tree, env.info.dup(env.info.scope.dup())); aoqi@0: try { aoqi@0: //the Formal Parameter of a for-each loop is not in the scope when aoqi@0: //attributing the for-each expression; we mimick this by attributing aoqi@0: //the for-each expression first (against original scope). aoqi@0: Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); aoqi@0: attribStat(tree.var, loopEnv); aoqi@0: chk.checkNonVoid(tree.pos(), exprType); aoqi@0: Type elemtype = types.elemtype(exprType); // perhaps expr is an array? aoqi@0: if (elemtype == null) { aoqi@0: // or perhaps expr implements Iterable? aoqi@0: Type base = types.asSuper(exprType, syms.iterableType.tsym); aoqi@0: if (base == null) { aoqi@0: log.error(tree.expr.pos(), aoqi@0: "foreach.not.applicable.to.type", aoqi@0: exprType, aoqi@0: diags.fragment("type.req.array.or.iterable")); aoqi@0: elemtype = types.createErrorType(exprType); aoqi@0: } else { aoqi@0: List iterableParams = base.allparams(); aoqi@0: elemtype = iterableParams.isEmpty() aoqi@0: ? syms.objectType aoqi@0: : types.wildUpperBound(iterableParams.head); aoqi@0: } aoqi@0: } aoqi@0: chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); aoqi@0: loopEnv.tree = tree; // before, we were not in loop! aoqi@0: attribStat(tree.body, loopEnv); aoqi@0: result = null; aoqi@0: } aoqi@0: finally { aoqi@0: loopEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitLabelled(JCLabeledStatement tree) { aoqi@0: // Check that label is not used in an enclosing statement aoqi@0: Env env1 = env; aoqi@0: while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { aoqi@0: if (env1.tree.hasTag(LABELLED) && aoqi@0: ((JCLabeledStatement) env1.tree).label == tree.label) { aoqi@0: log.error(tree.pos(), "label.already.in.use", aoqi@0: tree.label); aoqi@0: break; aoqi@0: } aoqi@0: env1 = env1.next; aoqi@0: } aoqi@0: aoqi@0: attribStat(tree.body, env.dup(tree)); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitSwitch(JCSwitch tree) { aoqi@0: Type seltype = attribExpr(tree.selector, env); aoqi@0: aoqi@0: Env switchEnv = aoqi@0: env.dup(tree, env.info.dup(env.info.scope.dup())); aoqi@0: aoqi@0: try { aoqi@0: aoqi@0: boolean enumSwitch = aoqi@0: allowEnums && aoqi@0: (seltype.tsym.flags() & Flags.ENUM) != 0; aoqi@0: boolean stringSwitch = false; aoqi@0: if (types.isSameType(seltype, syms.stringType)) { aoqi@0: if (allowStringsInSwitch) { aoqi@0: stringSwitch = true; aoqi@0: } else { aoqi@0: log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); aoqi@0: } aoqi@0: } aoqi@0: if (!enumSwitch && !stringSwitch) aoqi@0: seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); aoqi@0: aoqi@0: // Attribute all cases and aoqi@0: // check that there are no duplicate case labels or default clauses. aoqi@0: Set labels = new HashSet(); // The set of case labels. aoqi@0: boolean hasDefault = false; // Is there a default label? aoqi@0: for (List l = tree.cases; l.nonEmpty(); l = l.tail) { aoqi@0: JCCase c = l.head; aoqi@0: Env caseEnv = aoqi@0: switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); aoqi@0: try { aoqi@0: if (c.pat != null) { aoqi@0: if (enumSwitch) { aoqi@0: Symbol sym = enumConstant(c.pat, seltype); aoqi@0: if (sym == null) { aoqi@0: log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); aoqi@0: } else if (!labels.add(sym)) { aoqi@0: log.error(c.pos(), "duplicate.case.label"); aoqi@0: } aoqi@0: } else { aoqi@0: Type pattype = attribExpr(c.pat, switchEnv, seltype); aoqi@0: if (!pattype.hasTag(ERROR)) { aoqi@0: if (pattype.constValue() == null) { aoqi@0: log.error(c.pat.pos(), aoqi@0: (stringSwitch ? "string.const.req" : "const.expr.req")); aoqi@0: } else if (labels.contains(pattype.constValue())) { aoqi@0: log.error(c.pos(), "duplicate.case.label"); aoqi@0: } else { aoqi@0: labels.add(pattype.constValue()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } else if (hasDefault) { aoqi@0: log.error(c.pos(), "duplicate.default.label"); aoqi@0: } else { aoqi@0: hasDefault = true; aoqi@0: } aoqi@0: attribStats(c.stats, caseEnv); aoqi@0: } finally { aoqi@0: caseEnv.info.scope.leave(); aoqi@0: addVars(c.stats, switchEnv.info.scope); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: result = null; aoqi@0: } aoqi@0: finally { aoqi@0: switchEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: // where aoqi@0: /** Add any variables defined in stats to the switch scope. */ aoqi@0: private static void addVars(List stats, Scope switchScope) { aoqi@0: for (;stats.nonEmpty(); stats = stats.tail) { aoqi@0: JCTree stat = stats.head; aoqi@0: if (stat.hasTag(VARDEF)) aoqi@0: switchScope.enter(((JCVariableDecl) stat).sym); aoqi@0: } aoqi@0: } aoqi@0: // where aoqi@0: /** Return the selected enumeration constant symbol, or null. */ aoqi@0: private Symbol enumConstant(JCTree tree, Type enumType) { aoqi@0: if (!tree.hasTag(IDENT)) { aoqi@0: log.error(tree.pos(), "enum.label.must.be.unqualified.enum"); aoqi@0: return syms.errSymbol; aoqi@0: } aoqi@0: JCIdent ident = (JCIdent)tree; aoqi@0: Name name = ident.name; aoqi@0: for (Scope.Entry e = enumType.tsym.members().lookup(name); aoqi@0: e.scope != null; e = e.next()) { aoqi@0: if (e.sym.kind == VAR) { aoqi@0: Symbol s = ident.sym = e.sym; aoqi@0: ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated aoqi@0: ident.type = s.type; aoqi@0: return ((s.flags_field & Flags.ENUM) == 0) aoqi@0: ? null : s; aoqi@0: } aoqi@0: } aoqi@0: return null; aoqi@0: } aoqi@0: aoqi@0: public void visitSynchronized(JCSynchronized tree) { aoqi@0: chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); aoqi@0: attribStat(tree.body, env); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitTry(JCTry tree) { aoqi@0: // Create a new local environment with a local aoqi@0: Env localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); aoqi@0: try { aoqi@0: boolean isTryWithResource = tree.resources.nonEmpty(); aoqi@0: // Create a nested environment for attributing the try block if needed aoqi@0: Env tryEnv = isTryWithResource ? aoqi@0: env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : aoqi@0: localEnv; aoqi@0: try { aoqi@0: // Attribute resource declarations aoqi@0: for (JCTree resource : tree.resources) { aoqi@0: CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { aoqi@0: @Override aoqi@0: public void report(DiagnosticPosition pos, JCDiagnostic details) { aoqi@0: chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details)); aoqi@0: } aoqi@0: }; aoqi@0: ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext); aoqi@0: if (resource.hasTag(VARDEF)) { aoqi@0: attribStat(resource, tryEnv); aoqi@0: twrResult.check(resource, resource.type); aoqi@0: aoqi@0: //check that resource type cannot throw InterruptedException aoqi@0: checkAutoCloseable(resource.pos(), localEnv, resource.type); aoqi@0: aoqi@0: VarSymbol var = ((JCVariableDecl) resource).sym; aoqi@0: var.setData(ElementKind.RESOURCE_VARIABLE); aoqi@0: } else { aoqi@0: attribTree(resource, tryEnv, twrResult); aoqi@0: } aoqi@0: } aoqi@0: // Attribute body aoqi@0: attribStat(tree.body, tryEnv); aoqi@0: } finally { aoqi@0: if (isTryWithResource) aoqi@0: tryEnv.info.scope.leave(); aoqi@0: } aoqi@0: aoqi@0: // Attribute catch clauses aoqi@0: for (List l = tree.catchers; l.nonEmpty(); l = l.tail) { aoqi@0: JCCatch c = l.head; aoqi@0: Env catchEnv = aoqi@0: localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); aoqi@0: try { aoqi@0: Type ctype = attribStat(c.param, catchEnv); aoqi@0: if (TreeInfo.isMultiCatch(c)) { aoqi@0: //multi-catch parameter is implicitly marked as final aoqi@0: c.param.sym.flags_field |= FINAL | UNION; aoqi@0: } aoqi@0: if (c.param.sym.kind == Kinds.VAR) { aoqi@0: c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); aoqi@0: } aoqi@0: chk.checkType(c.param.vartype.pos(), aoqi@0: chk.checkClassType(c.param.vartype.pos(), ctype), aoqi@0: syms.throwableType); aoqi@0: attribStat(c.body, catchEnv); aoqi@0: } finally { aoqi@0: catchEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Attribute finalizer aoqi@0: if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); aoqi@0: result = null; aoqi@0: } aoqi@0: finally { aoqi@0: localEnv.info.scope.leave(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void checkAutoCloseable(DiagnosticPosition pos, Env env, Type resource) { aoqi@0: if (!resource.isErroneous() && aoqi@0: types.asSuper(resource, syms.autoCloseableType.tsym) != null && aoqi@0: !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself aoqi@0: Symbol close = syms.noSymbol; aoqi@0: Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); aoqi@0: try { aoqi@0: close = rs.resolveQualifiedMethod(pos, aoqi@0: env, aoqi@0: resource, aoqi@0: names.close, aoqi@0: List.nil(), aoqi@0: List.nil()); aoqi@0: } aoqi@0: finally { aoqi@0: log.popDiagnosticHandler(discardHandler); aoqi@0: } aoqi@0: if (close.kind == MTH && aoqi@0: close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && aoqi@0: chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && aoqi@0: env.info.lint.isEnabled(LintCategory.TRY)) { aoqi@0: log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitConditional(JCConditional tree) { aoqi@0: Type condtype = attribExpr(tree.cond, env, syms.booleanType); aoqi@0: aoqi@0: tree.polyKind = (!allowPoly || aoqi@0: pt().hasTag(NONE) && pt() != Type.recoveryType || aoqi@0: isBooleanOrNumeric(env, tree)) ? aoqi@0: PolyKind.STANDALONE : PolyKind.POLY; aoqi@0: aoqi@0: if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { aoqi@0: //cannot get here (i.e. it means we are returning from void method - which is already an error) aoqi@0: resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void")); aoqi@0: result = tree.type = types.createErrorType(resultInfo.pt); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? aoqi@0: unknownExprInfo : aoqi@0: resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) { aoqi@0: //this will use enclosing check context to check compatibility of aoqi@0: //subexpression against target type; if we are in a method check context, aoqi@0: //depending on whether boxing is allowed, we could have incompatibilities aoqi@0: @Override aoqi@0: public void report(DiagnosticPosition pos, JCDiagnostic details) { aoqi@0: enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details)); aoqi@0: } aoqi@0: }); aoqi@0: aoqi@0: Type truetype = attribTree(tree.truepart, env, condInfo); aoqi@0: Type falsetype = attribTree(tree.falsepart, env, condInfo); aoqi@0: aoqi@0: Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt(); aoqi@0: if (condtype.constValue() != null && aoqi@0: truetype.constValue() != null && aoqi@0: falsetype.constValue() != null && aoqi@0: !owntype.hasTag(NONE)) { aoqi@0: //constant folding aoqi@0: owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); aoqi@0: } aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: } aoqi@0: //where aoqi@0: private boolean isBooleanOrNumeric(Env env, JCExpression tree) { aoqi@0: switch (tree.getTag()) { aoqi@0: case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || aoqi@0: ((JCLiteral)tree).typetag == BOOLEAN || aoqi@0: ((JCLiteral)tree).typetag == BOT; aoqi@0: case LAMBDA: case REFERENCE: return false; aoqi@0: case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); aoqi@0: case CONDEXPR: aoqi@0: JCConditional condTree = (JCConditional)tree; aoqi@0: return isBooleanOrNumeric(env, condTree.truepart) && aoqi@0: isBooleanOrNumeric(env, condTree.falsepart); aoqi@0: case APPLY: aoqi@0: JCMethodInvocation speculativeMethodTree = aoqi@0: (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo); aoqi@0: Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType(); aoqi@0: return types.unboxedTypeOrType(owntype).isPrimitive(); aoqi@0: case NEWCLASS: aoqi@0: JCExpression className = aoqi@0: removeClassParams.translate(((JCNewClass)tree).clazz); aoqi@0: JCExpression speculativeNewClassTree = aoqi@0: (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo); aoqi@0: return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive(); aoqi@0: default: aoqi@0: Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type; aoqi@0: speculativeType = types.unboxedTypeOrType(speculativeType); aoqi@0: return speculativeType.isPrimitive(); aoqi@0: } aoqi@0: } aoqi@0: //where aoqi@0: TreeTranslator removeClassParams = new TreeTranslator() { aoqi@0: @Override aoqi@0: public void visitTypeApply(JCTypeApply tree) { aoqi@0: result = translate(tree.clazz); aoqi@0: } aoqi@0: }; aoqi@0: aoqi@0: /** Compute the type of a conditional expression, after aoqi@0: * checking that it exists. See JLS 15.25. Does not take into aoqi@0: * account the special case where condition and both arms aoqi@0: * are constants. aoqi@0: * aoqi@0: * @param pos The source position to be used for error aoqi@0: * diagnostics. aoqi@0: * @param thentype The type of the expression's then-part. aoqi@0: * @param elsetype The type of the expression's else-part. aoqi@0: */ aoqi@0: private Type condType(DiagnosticPosition pos, aoqi@0: Type thentype, Type elsetype) { aoqi@0: // If same type, that is the result aoqi@0: if (types.isSameType(thentype, elsetype)) aoqi@0: return thentype.baseType(); aoqi@0: aoqi@0: Type thenUnboxed = (!allowBoxing || thentype.isPrimitive()) aoqi@0: ? thentype : types.unboxedType(thentype); aoqi@0: Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive()) aoqi@0: ? elsetype : types.unboxedType(elsetype); aoqi@0: aoqi@0: // Otherwise, if both arms can be converted to a numeric aoqi@0: // type, return the least numeric type that fits both arms aoqi@0: // (i.e. return larger of the two, or return int if one aoqi@0: // arm is short, the other is char). aoqi@0: if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { aoqi@0: // If one arm has an integer subrange type (i.e., byte, aoqi@0: // short, or char), and the other is an integer constant aoqi@0: // that fits into the subrange, return the subrange type. aoqi@0: if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && aoqi@0: elseUnboxed.hasTag(INT) && aoqi@0: types.isAssignable(elseUnboxed, thenUnboxed)) { aoqi@0: return thenUnboxed.baseType(); aoqi@0: } aoqi@0: if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && aoqi@0: thenUnboxed.hasTag(INT) && aoqi@0: types.isAssignable(thenUnboxed, elseUnboxed)) { aoqi@0: return elseUnboxed.baseType(); aoqi@0: } aoqi@0: aoqi@0: for (TypeTag tag : primitiveTags) { aoqi@0: Type candidate = syms.typeOfTag[tag.ordinal()]; aoqi@0: if (types.isSubtype(thenUnboxed, candidate) && aoqi@0: types.isSubtype(elseUnboxed, candidate)) { aoqi@0: return candidate; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Those were all the cases that could result in a primitive aoqi@0: if (allowBoxing) { aoqi@0: if (thentype.isPrimitive()) aoqi@0: thentype = types.boxedClass(thentype).type; aoqi@0: if (elsetype.isPrimitive()) aoqi@0: elsetype = types.boxedClass(elsetype).type; aoqi@0: } aoqi@0: aoqi@0: if (types.isSubtype(thentype, elsetype)) aoqi@0: return elsetype.baseType(); aoqi@0: if (types.isSubtype(elsetype, thentype)) aoqi@0: return thentype.baseType(); aoqi@0: aoqi@0: if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) { aoqi@0: log.error(pos, "neither.conditional.subtype", aoqi@0: thentype, elsetype); aoqi@0: return thentype.baseType(); aoqi@0: } aoqi@0: aoqi@0: // both are known to be reference types. The result is aoqi@0: // lub(thentype,elsetype). This cannot fail, as it will aoqi@0: // always be possible to infer "Object" if nothing better. aoqi@0: return types.lub(thentype.baseType(), elsetype.baseType()); aoqi@0: } aoqi@0: aoqi@0: final static TypeTag[] primitiveTags = new TypeTag[]{ aoqi@0: BYTE, aoqi@0: CHAR, aoqi@0: SHORT, aoqi@0: INT, aoqi@0: LONG, aoqi@0: FLOAT, aoqi@0: DOUBLE, aoqi@0: BOOLEAN, aoqi@0: }; aoqi@0: aoqi@0: public void visitIf(JCIf tree) { aoqi@0: attribExpr(tree.cond, env, syms.booleanType); aoqi@0: attribStat(tree.thenpart, env); aoqi@0: if (tree.elsepart != null) aoqi@0: attribStat(tree.elsepart, env); aoqi@0: chk.checkEmptyIf(tree); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitExec(JCExpressionStatement tree) { aoqi@0: //a fresh environment is required for 292 inference to work properly --- aoqi@0: //see Infer.instantiatePolymorphicSignatureInstance() aoqi@0: Env localEnv = env.dup(tree); aoqi@0: attribExpr(tree.expr, localEnv); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitBreak(JCBreak tree) { aoqi@0: tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitContinue(JCContinue tree) { aoqi@0: tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); aoqi@0: result = null; aoqi@0: } aoqi@0: //where aoqi@0: /** Return the target of a break or continue statement, if it exists, aoqi@0: * report an error if not. aoqi@0: * Note: The target of a labelled break or continue is the aoqi@0: * (non-labelled) statement tree referred to by the label, aoqi@0: * not the tree representing the labelled statement itself. aoqi@0: * aoqi@0: * @param pos The position to be used for error diagnostics aoqi@0: * @param tag The tag of the jump statement. This is either aoqi@0: * Tree.BREAK or Tree.CONTINUE. aoqi@0: * @param label The label of the jump statement, or null if no aoqi@0: * label is given. aoqi@0: * @param env The environment current at the jump statement. aoqi@0: */ aoqi@0: private JCTree findJumpTarget(DiagnosticPosition pos, aoqi@0: JCTree.Tag tag, aoqi@0: Name label, aoqi@0: Env env) { aoqi@0: // Search environments outwards from the point of jump. aoqi@0: Env env1 = env; aoqi@0: LOOP: aoqi@0: while (env1 != null) { aoqi@0: switch (env1.tree.getTag()) { aoqi@0: case LABELLED: aoqi@0: JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; aoqi@0: if (label == labelled.label) { aoqi@0: // If jump is a continue, check that target is a loop. aoqi@0: if (tag == CONTINUE) { aoqi@0: if (!labelled.body.hasTag(DOLOOP) && aoqi@0: !labelled.body.hasTag(WHILELOOP) && aoqi@0: !labelled.body.hasTag(FORLOOP) && aoqi@0: !labelled.body.hasTag(FOREACHLOOP)) aoqi@0: log.error(pos, "not.loop.label", label); aoqi@0: // Found labelled statement target, now go inwards aoqi@0: // to next non-labelled tree. aoqi@0: return TreeInfo.referencedStatement(labelled); aoqi@0: } else { aoqi@0: return labelled; aoqi@0: } aoqi@0: } aoqi@0: break; aoqi@0: case DOLOOP: aoqi@0: case WHILELOOP: aoqi@0: case FORLOOP: aoqi@0: case FOREACHLOOP: aoqi@0: if (label == null) return env1.tree; aoqi@0: break; aoqi@0: case SWITCH: aoqi@0: if (label == null && tag == BREAK) return env1.tree; aoqi@0: break; aoqi@0: case LAMBDA: aoqi@0: case METHODDEF: aoqi@0: case CLASSDEF: aoqi@0: break LOOP; aoqi@0: default: aoqi@0: } aoqi@0: env1 = env1.next; aoqi@0: } aoqi@0: if (label != null) aoqi@0: log.error(pos, "undef.label", label); aoqi@0: else if (tag == CONTINUE) aoqi@0: log.error(pos, "cont.outside.loop"); aoqi@0: else aoqi@0: log.error(pos, "break.outside.switch.loop"); aoqi@0: return null; aoqi@0: } aoqi@0: aoqi@0: public void visitReturn(JCReturn tree) { aoqi@0: // Check that there is an enclosing method which is aoqi@0: // nested within than the enclosing class. aoqi@0: if (env.info.returnResult == null) { aoqi@0: log.error(tree.pos(), "ret.outside.meth"); aoqi@0: } else { aoqi@0: // Attribute return expression, if it exists, and check that aoqi@0: // it conforms to result type of enclosing method. aoqi@0: if (tree.expr != null) { aoqi@0: if (env.info.returnResult.pt.hasTag(VOID)) { aoqi@0: env.info.returnResult.checkContext.report(tree.expr.pos(), aoqi@0: diags.fragment("unexpected.ret.val")); aoqi@0: } aoqi@0: attribTree(tree.expr, env, env.info.returnResult); aoqi@0: } else if (!env.info.returnResult.pt.hasTag(VOID) && aoqi@0: !env.info.returnResult.pt.hasTag(NONE)) { aoqi@0: env.info.returnResult.checkContext.report(tree.pos(), aoqi@0: diags.fragment("missing.ret.val")); aoqi@0: } aoqi@0: } aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitThrow(JCThrow tree) { aoqi@0: Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType); aoqi@0: if (allowPoly) { aoqi@0: chk.checkType(tree, owntype, syms.throwableType); aoqi@0: } aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: public void visitAssert(JCAssert tree) { aoqi@0: attribExpr(tree.cond, env, syms.booleanType); aoqi@0: if (tree.detail != null) { aoqi@0: chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); aoqi@0: } aoqi@0: result = null; aoqi@0: } aoqi@0: aoqi@0: /** Visitor method for method invocations. aoqi@0: * NOTE: The method part of an application will have in its type field aoqi@0: * the return type of the method, not the method's type itself! aoqi@0: */ aoqi@0: public void visitApply(JCMethodInvocation tree) { aoqi@0: // The local environment of a method application is aoqi@0: // a new environment nested in the current one. aoqi@0: Env localEnv = env.dup(tree, env.info.dup()); aoqi@0: aoqi@0: // The types of the actual method arguments. aoqi@0: List argtypes; aoqi@0: aoqi@0: // The types of the actual method type arguments. aoqi@0: List typeargtypes = null; aoqi@0: aoqi@0: Name methName = TreeInfo.name(tree.meth); aoqi@0: aoqi@0: boolean isConstructorCall = aoqi@0: methName == names._this || methName == names._super; aoqi@0: aoqi@0: ListBuffer argtypesBuf = new ListBuffer<>(); aoqi@0: if (isConstructorCall) { aoqi@0: // We are seeing a ...this(...) or ...super(...) call. aoqi@0: // Check that this is the first statement in a constructor. aoqi@0: if (checkFirstConstructorStat(tree, env)) { aoqi@0: aoqi@0: // Record the fact aoqi@0: // that this is a constructor call (using isSelfCall). aoqi@0: localEnv.info.isSelfCall = true; aoqi@0: aoqi@0: // Attribute arguments, yielding list of argument types. aoqi@0: attribArgs(tree.args, localEnv, argtypesBuf); aoqi@0: argtypes = argtypesBuf.toList(); aoqi@0: typeargtypes = attribTypes(tree.typeargs, localEnv); aoqi@0: aoqi@0: // Variable `site' points to the class in which the called aoqi@0: // constructor is defined. aoqi@0: Type site = env.enclClass.sym.type; aoqi@0: if (methName == names._super) { aoqi@0: if (site == syms.objectType) { aoqi@0: log.error(tree.meth.pos(), "no.superclass", site); aoqi@0: site = types.createErrorType(syms.objectType); aoqi@0: } else { aoqi@0: site = types.supertype(site); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (site.hasTag(CLASS)) { aoqi@0: Type encl = site.getEnclosingType(); aoqi@0: while (encl != null && encl.hasTag(TYPEVAR)) aoqi@0: encl = encl.getUpperBound(); aoqi@0: if (encl.hasTag(CLASS)) { aoqi@0: // we are calling a nested class aoqi@0: aoqi@0: if (tree.meth.hasTag(SELECT)) { aoqi@0: JCTree qualifier = ((JCFieldAccess) tree.meth).selected; aoqi@0: aoqi@0: // We are seeing a prefixed call, of the form aoqi@0: // .super(...). aoqi@0: // Check that the prefix expression conforms aoqi@0: // to the outer instance type of the class. aoqi@0: chk.checkRefType(qualifier.pos(), aoqi@0: attribExpr(qualifier, localEnv, aoqi@0: encl)); aoqi@0: } else if (methName == names._super) { aoqi@0: // qualifier omitted; check for existence aoqi@0: // of an appropriate implicit qualifier. aoqi@0: rs.resolveImplicitThis(tree.meth.pos(), aoqi@0: localEnv, site, true); aoqi@0: } aoqi@0: } else if (tree.meth.hasTag(SELECT)) { aoqi@0: log.error(tree.meth.pos(), "illegal.qual.not.icls", aoqi@0: site.tsym); aoqi@0: } aoqi@0: aoqi@0: // if we're calling a java.lang.Enum constructor, aoqi@0: // prefix the implicit String and int parameters aoqi@0: if (site.tsym == syms.enumSym && allowEnums) aoqi@0: argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); aoqi@0: aoqi@0: // Resolve the called constructor under the assumption aoqi@0: // that we are referring to a superclass instance of the aoqi@0: // current instance (JLS ???). aoqi@0: boolean selectSuperPrev = localEnv.info.selectSuper; aoqi@0: localEnv.info.selectSuper = true; aoqi@0: localEnv.info.pendingResolutionPhase = null; aoqi@0: Symbol sym = rs.resolveConstructor( aoqi@0: tree.meth.pos(), localEnv, site, argtypes, typeargtypes); aoqi@0: localEnv.info.selectSuper = selectSuperPrev; aoqi@0: aoqi@0: // Set method symbol to resolved constructor... aoqi@0: TreeInfo.setSymbol(tree.meth, sym); aoqi@0: aoqi@0: // ...and check that it is legal in the current context. aoqi@0: // (this will also set the tree's type) aoqi@0: Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); aoqi@0: checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt)); aoqi@0: } aoqi@0: // Otherwise, `site' is an error type and we do nothing aoqi@0: } aoqi@0: result = tree.type = syms.voidType; aoqi@0: } else { aoqi@0: // Otherwise, we are seeing a regular method call. aoqi@0: // Attribute the arguments, yielding list of argument types, ... aoqi@0: int kind = attribArgs(tree.args, localEnv, argtypesBuf); aoqi@0: argtypes = argtypesBuf.toList(); aoqi@0: typeargtypes = attribAnyTypes(tree.typeargs, localEnv); aoqi@0: aoqi@0: // ... and attribute the method using as a prototype a methodtype aoqi@0: // whose formal argument types is exactly the list of actual aoqi@0: // arguments (this will also set the method symbol). aoqi@0: Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); aoqi@0: localEnv.info.pendingResolutionPhase = null; aoqi@0: Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext)); aoqi@0: aoqi@0: // Compute the result type. aoqi@0: Type restype = mtype.getReturnType(); aoqi@0: if (restype.hasTag(WILDCARD)) aoqi@0: throw new AssertionError(mtype); aoqi@0: aoqi@0: Type qualifier = (tree.meth.hasTag(SELECT)) aoqi@0: ? ((JCFieldAccess) tree.meth).selected.type aoqi@0: : env.enclClass.sym.type; aoqi@0: restype = adjustMethodReturnType(qualifier, methName, argtypes, restype); aoqi@0: aoqi@0: chk.checkRefTypes(tree.typeargs, typeargtypes); aoqi@0: aoqi@0: // Check that value of resulting type is admissible in the aoqi@0: // current context. Also, capture the return type aoqi@0: result = check(tree, capture(restype), VAL, resultInfo); aoqi@0: } aoqi@0: chk.validate(tree.typeargs, localEnv); aoqi@0: } aoqi@0: //where aoqi@0: Type adjustMethodReturnType(Type qualifierType, Name methodName, List argtypes, Type restype) { aoqi@0: if (allowCovariantReturns && aoqi@0: methodName == names.clone && aoqi@0: types.isArray(qualifierType)) { aoqi@0: // as a special case, array.clone() has a result that is aoqi@0: // the same as static type of the array being cloned aoqi@0: return qualifierType; aoqi@0: } else if (allowGenerics && aoqi@0: methodName == names.getClass && aoqi@0: argtypes.isEmpty()) { aoqi@0: // as a special case, x.getClass() has type Class aoqi@0: return new ClassType(restype.getEnclosingType(), aoqi@0: List.of(new WildcardType(types.erasure(qualifierType), aoqi@0: BoundKind.EXTENDS, aoqi@0: syms.boundClass)), aoqi@0: restype.tsym); aoqi@0: } else { aoqi@0: return restype; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Check that given application node appears as first statement aoqi@0: * in a constructor call. aoqi@0: * @param tree The application node aoqi@0: * @param env The environment current at the application. aoqi@0: */ aoqi@0: boolean checkFirstConstructorStat(JCMethodInvocation tree, Env env) { aoqi@0: JCMethodDecl enclMethod = env.enclMethod; aoqi@0: if (enclMethod != null && enclMethod.name == names.init) { aoqi@0: JCBlock body = enclMethod.body; aoqi@0: if (body.stats.head.hasTag(EXEC) && aoqi@0: ((JCExpressionStatement) body.stats.head).expr == tree) aoqi@0: return true; aoqi@0: } aoqi@0: log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", aoqi@0: TreeInfo.name(tree.meth)); aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: /** Obtain a method type with given argument types. aoqi@0: */ aoqi@0: Type newMethodTemplate(Type restype, List argtypes, List typeargtypes) { aoqi@0: MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass); aoqi@0: return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); aoqi@0: } aoqi@0: aoqi@0: public void visitNewClass(final JCNewClass tree) { aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: aoqi@0: // The local environment of a class creation is aoqi@0: // a new environment nested in the current one. aoqi@0: Env localEnv = env.dup(tree, env.info.dup()); aoqi@0: aoqi@0: // The anonymous inner class definition of the new expression, aoqi@0: // if one is defined by it. aoqi@0: JCClassDecl cdef = tree.def; aoqi@0: aoqi@0: // If enclosing class is given, attribute it, and aoqi@0: // complete class name to be fully qualified aoqi@0: JCExpression clazz = tree.clazz; // Class field following new aoqi@0: JCExpression clazzid; // Identifier in class field aoqi@0: JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid aoqi@0: annoclazzid = null; aoqi@0: aoqi@0: if (clazz.hasTag(TYPEAPPLY)) { aoqi@0: clazzid = ((JCTypeApply) clazz).clazz; aoqi@0: if (clazzid.hasTag(ANNOTATED_TYPE)) { aoqi@0: annoclazzid = (JCAnnotatedType) clazzid; aoqi@0: clazzid = annoclazzid.underlyingType; aoqi@0: } aoqi@0: } else { aoqi@0: if (clazz.hasTag(ANNOTATED_TYPE)) { aoqi@0: annoclazzid = (JCAnnotatedType) clazz; aoqi@0: clazzid = annoclazzid.underlyingType; aoqi@0: } else { aoqi@0: clazzid = clazz; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: JCExpression clazzid1 = clazzid; // The same in fully qualified form aoqi@0: aoqi@0: if (tree.encl != null) { aoqi@0: // We are seeing a qualified new, of the form aoqi@0: // .new C <...> (...) ... aoqi@0: // In this case, we let clazz stand for the name of the aoqi@0: // allocated class C prefixed with the type of the qualifier aoqi@0: // expression, so that we can aoqi@0: // resolve it with standard techniques later. I.e., if aoqi@0: // has type T, then .new C <...> (...) aoqi@0: // yields a clazz T.C. aoqi@0: Type encltype = chk.checkRefType(tree.encl.pos(), aoqi@0: attribExpr(tree.encl, env)); aoqi@0: // TODO 308: in .new C, do we also want to add the type annotations aoqi@0: // from expr to the combined type, or not? Yes, do this. aoqi@0: clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), aoqi@0: ((JCIdent) clazzid).name); aoqi@0: aoqi@0: EndPosTable endPosTable = this.env.toplevel.endPositions; aoqi@0: endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable)); aoqi@0: if (clazz.hasTag(ANNOTATED_TYPE)) { aoqi@0: JCAnnotatedType annoType = (JCAnnotatedType) clazz; aoqi@0: List annos = annoType.annotations; aoqi@0: aoqi@0: if (annoType.underlyingType.hasTag(TYPEAPPLY)) { aoqi@0: clazzid1 = make.at(tree.pos). aoqi@0: TypeApply(clazzid1, aoqi@0: ((JCTypeApply) clazz).arguments); aoqi@0: } aoqi@0: aoqi@0: clazzid1 = make.at(tree.pos). aoqi@0: AnnotatedType(annos, clazzid1); aoqi@0: } else if (clazz.hasTag(TYPEAPPLY)) { aoqi@0: clazzid1 = make.at(tree.pos). aoqi@0: TypeApply(clazzid1, aoqi@0: ((JCTypeApply) clazz).arguments); aoqi@0: } aoqi@0: aoqi@0: clazz = clazzid1; aoqi@0: } aoqi@0: aoqi@0: // Attribute clazz expression and store aoqi@0: // symbol + type back into the attributed tree. aoqi@0: Type clazztype = TreeInfo.isEnumInit(env.tree) ? aoqi@0: attribIdentAsEnumType(env, (JCIdent)clazz) : aoqi@0: attribType(clazz, env); aoqi@0: aoqi@0: clazztype = chk.checkDiamond(tree, clazztype); aoqi@0: chk.validate(clazz, localEnv); aoqi@0: if (tree.encl != null) { aoqi@0: // We have to work in this case to store aoqi@0: // symbol + type back into the attributed tree. aoqi@0: tree.clazz.type = clazztype; aoqi@0: TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); aoqi@0: clazzid.type = ((JCIdent) clazzid).sym.type; aoqi@0: if (annoclazzid != null) { aoqi@0: annoclazzid.type = clazzid.type; aoqi@0: } aoqi@0: if (!clazztype.isErroneous()) { aoqi@0: if (cdef != null && clazztype.tsym.isInterface()) { aoqi@0: log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); aoqi@0: } else if (clazztype.tsym.isStatic()) { aoqi@0: log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); aoqi@0: } aoqi@0: } aoqi@0: } else if (!clazztype.tsym.isInterface() && aoqi@0: clazztype.getEnclosingType().hasTag(CLASS)) { aoqi@0: // Check for the existence of an apropos outer instance aoqi@0: rs.resolveImplicitThis(tree.pos(), env, clazztype); aoqi@0: } aoqi@0: aoqi@0: // Attribute constructor arguments. aoqi@0: ListBuffer argtypesBuf = new ListBuffer<>(); aoqi@0: int pkind = attribArgs(tree.args, localEnv, argtypesBuf); aoqi@0: List argtypes = argtypesBuf.toList(); aoqi@0: List typeargtypes = attribTypes(tree.typeargs, localEnv); aoqi@0: aoqi@0: // If we have made no mistakes in the class type... aoqi@0: if (clazztype.hasTag(CLASS)) { aoqi@0: // Enums may not be instantiated except implicitly aoqi@0: if (allowEnums && aoqi@0: (clazztype.tsym.flags_field&Flags.ENUM) != 0 && aoqi@0: (!env.tree.hasTag(VARDEF) || aoqi@0: (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 || aoqi@0: ((JCVariableDecl) env.tree).init != tree)) aoqi@0: log.error(tree.pos(), "enum.cant.be.instantiated"); aoqi@0: // Check that class is not abstract aoqi@0: if (cdef == null && aoqi@0: (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { aoqi@0: log.error(tree.pos(), "abstract.cant.be.instantiated", aoqi@0: clazztype.tsym); aoqi@0: } else if (cdef != null && clazztype.tsym.isInterface()) { aoqi@0: // Check that no constructor arguments are given to aoqi@0: // anonymous classes implementing an interface aoqi@0: if (!argtypes.isEmpty()) aoqi@0: log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); aoqi@0: aoqi@0: if (!typeargtypes.isEmpty()) aoqi@0: log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); aoqi@0: aoqi@0: // Error recovery: pretend no arguments were supplied. aoqi@0: argtypes = List.nil(); aoqi@0: typeargtypes = List.nil(); aoqi@0: } else if (TreeInfo.isDiamond(tree)) { aoqi@0: ClassType site = new ClassType(clazztype.getEnclosingType(), aoqi@0: clazztype.tsym.type.getTypeArguments(), aoqi@0: clazztype.tsym); aoqi@0: aoqi@0: Env diamondEnv = localEnv.dup(tree); aoqi@0: diamondEnv.info.selectSuper = cdef != null; aoqi@0: diamondEnv.info.pendingResolutionPhase = null; aoqi@0: aoqi@0: //if the type of the instance creation expression is a class type aoqi@0: //apply method resolution inference (JLS 15.12.2.7). The return type aoqi@0: //of the resolved constructor will be a partially instantiated type aoqi@0: Symbol constructor = rs.resolveDiamond(tree.pos(), aoqi@0: diamondEnv, aoqi@0: site, aoqi@0: argtypes, aoqi@0: typeargtypes); aoqi@0: tree.constructor = constructor.baseSymbol(); aoqi@0: aoqi@0: final TypeSymbol csym = clazztype.tsym; aoqi@0: ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) { aoqi@0: @Override aoqi@0: public void report(DiagnosticPosition _unused, JCDiagnostic details) { aoqi@0: enclosingContext.report(tree.clazz, aoqi@0: diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details)); aoqi@0: } aoqi@0: }); aoqi@0: Type constructorType = tree.constructorType = types.createErrorType(clazztype); aoqi@0: constructorType = checkId(tree, site, aoqi@0: constructor, aoqi@0: diamondEnv, aoqi@0: diamondResult); aoqi@0: aoqi@0: tree.clazz.type = types.createErrorType(clazztype); aoqi@0: if (!constructorType.isErroneous()) { aoqi@0: tree.clazz.type = clazztype = constructorType.getReturnType(); aoqi@0: tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); aoqi@0: } aoqi@0: clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); aoqi@0: } aoqi@0: aoqi@0: // Resolve the called constructor under the assumption aoqi@0: // that we are referring to a superclass instance of the aoqi@0: // current instance (JLS ???). aoqi@0: else { aoqi@0: //the following code alters some of the fields in the current aoqi@0: //AttrContext - hence, the current context must be dup'ed in aoqi@0: //order to avoid downstream failures aoqi@0: Env rsEnv = localEnv.dup(tree); aoqi@0: rsEnv.info.selectSuper = cdef != null; aoqi@0: rsEnv.info.pendingResolutionPhase = null; aoqi@0: tree.constructor = rs.resolveConstructor( aoqi@0: tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); aoqi@0: if (cdef == null) { //do not check twice! aoqi@0: tree.constructorType = checkId(tree, aoqi@0: clazztype, aoqi@0: tree.constructor, aoqi@0: rsEnv, aoqi@0: new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); aoqi@0: if (rsEnv.info.lastResolveVarargs()) aoqi@0: Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); aoqi@0: } aoqi@0: if (cdef == null && aoqi@0: !clazztype.isErroneous() && aoqi@0: clazztype.getTypeArguments().nonEmpty() && aoqi@0: findDiamonds) { aoqi@0: findDiamond(localEnv, tree, clazztype); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (cdef != null) { aoqi@0: // We are seeing an anonymous class instance creation. aoqi@0: // In this case, the class instance creation aoqi@0: // expression aoqi@0: // aoqi@0: // E.new C(args) { ... } aoqi@0: // aoqi@0: // is represented internally as aoqi@0: // aoqi@0: // E . new C(args) ( class { ... } ) . aoqi@0: // aoqi@0: // This expression is then *transformed* as follows: aoqi@0: // aoqi@0: // (1) add a STATIC flag to the class definition aoqi@0: // if the current environment is static aoqi@0: // (2) add an extends or implements clause aoqi@0: // (3) add a constructor. aoqi@0: // aoqi@0: // For instance, if C is a class, and ET is the type of E, aoqi@0: // the expression aoqi@0: // aoqi@0: // E.new C(args) { ... } aoqi@0: // aoqi@0: // is translated to (where X is a fresh name and typarams is the aoqi@0: // parameter list of the super constructor): aoqi@0: // aoqi@0: // new X(<*nullchk*>E, args) where aoqi@0: // X extends C { aoqi@0: // X(ET e, args) { aoqi@0: // e.super(args) aoqi@0: // } aoqi@0: // ... aoqi@0: // } aoqi@0: if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC; aoqi@0: aoqi@0: if (clazztype.tsym.isInterface()) { aoqi@0: cdef.implementing = List.of(clazz); aoqi@0: } else { aoqi@0: cdef.extending = clazz; aoqi@0: } aoqi@0: aoqi@0: if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && aoqi@0: isSerializable(clazztype)) { aoqi@0: localEnv.info.isSerializable = true; aoqi@0: } aoqi@0: aoqi@0: attribStat(cdef, localEnv); aoqi@0: aoqi@0: checkLambdaCandidate(tree, cdef.sym, clazztype); aoqi@0: aoqi@0: // If an outer instance is given, aoqi@0: // prefix it to the constructor arguments aoqi@0: // and delete it from the new expression aoqi@0: if (tree.encl != null && !clazztype.tsym.isInterface()) { aoqi@0: tree.args = tree.args.prepend(makeNullCheck(tree.encl)); aoqi@0: argtypes = argtypes.prepend(tree.encl.type); aoqi@0: tree.encl = null; aoqi@0: } aoqi@0: aoqi@0: // Reassign clazztype and recompute constructor. aoqi@0: clazztype = cdef.sym.type; aoqi@0: Symbol sym = tree.constructor = rs.resolveConstructor( aoqi@0: tree.pos(), localEnv, clazztype, argtypes, typeargtypes); aoqi@0: Assert.check(sym.kind < AMBIGUOUS); aoqi@0: tree.constructor = sym; aoqi@0: tree.constructorType = checkId(tree, aoqi@0: clazztype, aoqi@0: tree.constructor, aoqi@0: localEnv, aoqi@0: new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); aoqi@0: } aoqi@0: aoqi@0: if (tree.constructor != null && tree.constructor.kind == MTH) aoqi@0: owntype = clazztype; aoqi@0: } aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: chk.validate(tree.typeargs, localEnv); aoqi@0: } aoqi@0: //where aoqi@0: void findDiamond(Env env, JCNewClass tree, Type clazztype) { aoqi@0: JCTypeApply ta = (JCTypeApply)tree.clazz; aoqi@0: List prevTypeargs = ta.arguments; aoqi@0: try { aoqi@0: //create a 'fake' diamond AST node by removing type-argument trees aoqi@0: ta.arguments = List.nil(); aoqi@0: ResultInfo findDiamondResult = new ResultInfo(VAL, aoqi@0: resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt()); aoqi@0: Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type; aoqi@0: Type polyPt = allowPoly ? aoqi@0: syms.objectType : aoqi@0: clazztype; aoqi@0: if (!inferred.isErroneous() && aoqi@0: (allowPoly && pt() == Infer.anyPoly ? aoqi@0: types.isSameType(inferred, clazztype) : aoqi@0: types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) { aoqi@0: String key = types.isSameType(clazztype, inferred) ? aoqi@0: "diamond.redundant.args" : aoqi@0: "diamond.redundant.args.1"; aoqi@0: log.warning(tree.clazz.pos(), key, clazztype, inferred); aoqi@0: } aoqi@0: } finally { aoqi@0: ta.arguments = prevTypeargs; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) { aoqi@0: if (allowLambda && aoqi@0: identifyLambdaCandidate && aoqi@0: clazztype.hasTag(CLASS) && aoqi@0: !pt().hasTag(NONE) && aoqi@0: types.isFunctionalInterface(clazztype.tsym)) { aoqi@0: Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym); aoqi@0: int count = 0; aoqi@0: boolean found = false; aoqi@0: for (Symbol sym : csym.members().getElements()) { aoqi@0: if ((sym.flags() & SYNTHETIC) != 0 || aoqi@0: sym.isConstructor()) continue; aoqi@0: count++; aoqi@0: if (sym.kind != MTH || aoqi@0: !sym.name.equals(descriptor.name)) continue; aoqi@0: Type mtype = types.memberType(clazztype, sym); aoqi@0: if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) { aoqi@0: found = true; aoqi@0: } aoqi@0: } aoqi@0: if (found && count == 1) { aoqi@0: log.note(tree.def, "potential.lambda.found"); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Make an attributed null check tree. aoqi@0: */ aoqi@0: public JCExpression makeNullCheck(JCExpression arg) { aoqi@0: // optimization: X.this is never null; skip null check aoqi@0: Name name = TreeInfo.name(arg); aoqi@0: if (name == names._this || name == names._super) return arg; aoqi@0: aoqi@0: JCTree.Tag optag = NULLCHK; aoqi@0: JCUnary tree = make.at(arg.pos).Unary(optag, arg); aoqi@0: tree.operator = syms.nullcheck; aoqi@0: tree.type = arg.type; aoqi@0: return tree; aoqi@0: } aoqi@0: aoqi@0: public void visitNewArray(JCNewArray tree) { aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: Env localEnv = env.dup(tree); aoqi@0: Type elemtype; aoqi@0: if (tree.elemtype != null) { aoqi@0: elemtype = attribType(tree.elemtype, localEnv); aoqi@0: chk.validate(tree.elemtype, localEnv); aoqi@0: owntype = elemtype; aoqi@0: for (List l = tree.dims; l.nonEmpty(); l = l.tail) { aoqi@0: attribExpr(l.head, localEnv, syms.intType); aoqi@0: owntype = new ArrayType(owntype, syms.arrayClass); aoqi@0: } aoqi@0: } else { aoqi@0: // we are seeing an untyped aggregate { ... } aoqi@0: // this is allowed only if the prototype is an array aoqi@0: if (pt().hasTag(ARRAY)) { aoqi@0: elemtype = types.elemtype(pt()); aoqi@0: } else { aoqi@0: if (!pt().hasTag(ERROR)) { aoqi@0: log.error(tree.pos(), "illegal.initializer.for.type", aoqi@0: pt()); aoqi@0: } aoqi@0: elemtype = types.createErrorType(pt()); aoqi@0: } aoqi@0: } aoqi@0: if (tree.elems != null) { aoqi@0: attribExprs(tree.elems, localEnv, elemtype); aoqi@0: owntype = new ArrayType(elemtype, syms.arrayClass); aoqi@0: } aoqi@0: if (!types.isReifiable(elemtype)) aoqi@0: log.error(tree.pos(), "generic.array.creation"); aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: /* aoqi@0: * A lambda expression can only be attributed when a target-type is available. aoqi@0: * In addition, if the target-type is that of a functional interface whose aoqi@0: * descriptor contains inference variables in argument position the lambda expression aoqi@0: * is 'stuck' (see DeferredAttr). aoqi@0: */ aoqi@0: @Override aoqi@0: public void visitLambda(final JCLambda that) { aoqi@0: if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { aoqi@0: if (pt().hasTag(NONE)) { aoqi@0: //lambda only allowed in assignment or method invocation/cast context aoqi@0: log.error(that.pos(), "unexpected.lambda"); aoqi@0: } aoqi@0: result = that.type = types.createErrorType(pt()); aoqi@0: return; aoqi@0: } aoqi@0: //create an environment for attribution of the lambda expression aoqi@0: final Env localEnv = lambdaEnv(that, env); aoqi@0: boolean needsRecovery = aoqi@0: resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; aoqi@0: try { aoqi@0: Type currentTarget = pt(); aoqi@0: if (needsRecovery && isSerializable(currentTarget)) { aoqi@0: localEnv.info.isSerializable = true; aoqi@0: } aoqi@0: List explicitParamTypes = null; aoqi@0: if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) { aoqi@0: //attribute lambda parameters aoqi@0: attribStats(that.params, localEnv); aoqi@0: explicitParamTypes = TreeInfo.types(that.params); aoqi@0: } aoqi@0: aoqi@0: Type lambdaType; aoqi@0: if (pt() != Type.recoveryType) { aoqi@0: /* We need to adjust the target. If the target is an aoqi@0: * intersection type, for example: SAM & I1 & I2 ... aoqi@0: * the target will be updated to SAM aoqi@0: */ aoqi@0: currentTarget = targetChecker.visit(currentTarget, that); aoqi@0: if (explicitParamTypes != null) { aoqi@0: currentTarget = infer.instantiateFunctionalInterface(that, aoqi@0: currentTarget, explicitParamTypes, resultInfo.checkContext); aoqi@0: } vromero@2543: currentTarget = types.removeWildcards(currentTarget); aoqi@0: lambdaType = types.findDescriptorType(currentTarget); aoqi@0: } else { aoqi@0: currentTarget = Type.recoveryType; aoqi@0: lambdaType = fallbackDescriptorType(that); aoqi@0: } aoqi@0: aoqi@0: setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext); aoqi@0: aoqi@0: if (lambdaType.hasTag(FORALL)) { aoqi@0: //lambda expression target desc cannot be a generic method aoqi@0: resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", aoqi@0: lambdaType, kindName(currentTarget.tsym), currentTarget.tsym)); aoqi@0: result = that.type = types.createErrorType(pt()); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) { aoqi@0: //add param type info in the AST aoqi@0: List actuals = lambdaType.getParameterTypes(); aoqi@0: List params = that.params; aoqi@0: aoqi@0: boolean arityMismatch = false; aoqi@0: aoqi@0: while (params.nonEmpty()) { aoqi@0: if (actuals.isEmpty()) { aoqi@0: //not enough actuals to perform lambda parameter inference aoqi@0: arityMismatch = true; aoqi@0: } aoqi@0: //reset previously set info aoqi@0: Type argType = arityMismatch ? aoqi@0: syms.errType : aoqi@0: actuals.head; aoqi@0: params.head.vartype = make.at(params.head).Type(argType); aoqi@0: params.head.sym = null; aoqi@0: actuals = actuals.isEmpty() ? aoqi@0: actuals : aoqi@0: actuals.tail; aoqi@0: params = params.tail; aoqi@0: } aoqi@0: aoqi@0: //attribute lambda parameters aoqi@0: attribStats(that.params, localEnv); aoqi@0: aoqi@0: if (arityMismatch) { aoqi@0: resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda")); aoqi@0: result = that.type = types.createErrorType(currentTarget); aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: //from this point on, no recovery is needed; if we are in assignment context aoqi@0: //we will be able to attribute the whole lambda body, regardless of errors; aoqi@0: //if we are in a 'check' method context, and the lambda is not compatible aoqi@0: //with the target-type, it will be recovered anyway in Attr.checkId aoqi@0: needsRecovery = false; aoqi@0: aoqi@0: FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? aoqi@0: new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : aoqi@0: new FunctionalReturnContext(resultInfo.checkContext); aoqi@0: aoqi@0: ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ? aoqi@0: recoveryInfo : aoqi@0: new ResultInfo(VAL, lambdaType.getReturnType(), funcContext); aoqi@0: localEnv.info.returnResult = bodyResultInfo; aoqi@0: aoqi@0: if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { aoqi@0: attribTree(that.getBody(), localEnv, bodyResultInfo); aoqi@0: } else { aoqi@0: JCBlock body = (JCBlock)that.body; aoqi@0: attribStats(body.stats, localEnv); aoqi@0: } aoqi@0: aoqi@0: result = check(that, currentTarget, VAL, resultInfo); aoqi@0: aoqi@0: boolean isSpeculativeRound = aoqi@0: resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; aoqi@0: aoqi@0: preFlow(that); aoqi@0: flow.analyzeLambda(env, that, make, isSpeculativeRound); aoqi@0: aoqi@0: checkLambdaCompatible(that, lambdaType, resultInfo.checkContext); aoqi@0: aoqi@0: if (!isSpeculativeRound) { aoqi@0: //add thrown types as bounds to the thrown types free variables if needed: aoqi@0: if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) { aoqi@0: List inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make); aoqi@0: List thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes()); aoqi@0: aoqi@0: chk.unhandled(inferredThrownTypes, thrownTypes); aoqi@0: } aoqi@0: aoqi@0: checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget); aoqi@0: } aoqi@0: result = check(that, currentTarget, VAL, resultInfo); aoqi@0: } catch (Types.FunctionDescriptorLookupError ex) { aoqi@0: JCDiagnostic cause = ex.getDiagnostic(); aoqi@0: resultInfo.checkContext.report(that, cause); aoqi@0: result = that.type = types.createErrorType(pt()); aoqi@0: return; aoqi@0: } finally { aoqi@0: localEnv.info.scope.leave(); aoqi@0: if (needsRecovery) { aoqi@0: attribTree(that, env, recoveryInfo); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: //where aoqi@0: void preFlow(JCLambda tree) { aoqi@0: new PostAttrAnalyzer() { aoqi@0: @Override aoqi@0: public void scan(JCTree tree) { aoqi@0: if (tree == null || aoqi@0: (tree.type != null && aoqi@0: tree.type == Type.stuckType)) { aoqi@0: //don't touch stuck expressions! aoqi@0: return; aoqi@0: } aoqi@0: super.scan(tree); aoqi@0: } aoqi@0: }.scan(tree); aoqi@0: } aoqi@0: aoqi@0: Types.MapVisitor targetChecker = new Types.MapVisitor() { aoqi@0: aoqi@0: @Override aoqi@0: public Type visitClassType(ClassType t, DiagnosticPosition pos) { aoqi@0: return t.isCompound() ? aoqi@0: visitIntersectionClassType((IntersectionClassType)t, pos) : t; aoqi@0: } aoqi@0: aoqi@0: public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) { aoqi@0: Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict)); aoqi@0: Type target = null; aoqi@0: for (Type bound : ict.getExplicitComponents()) { aoqi@0: TypeSymbol boundSym = bound.tsym; aoqi@0: if (types.isFunctionalInterface(boundSym) && aoqi@0: types.findDescriptorSymbol(boundSym) == desc) { aoqi@0: target = bound; aoqi@0: } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) { aoqi@0: //bound must be an interface aoqi@0: reportIntersectionError(pos, "not.an.intf.component", boundSym); aoqi@0: } aoqi@0: } aoqi@0: return target != null ? aoqi@0: target : aoqi@0: ict.getExplicitComponents().head; //error recovery aoqi@0: } aoqi@0: aoqi@0: private TypeSymbol makeNotionalInterface(IntersectionClassType ict) { aoqi@0: ListBuffer targs = new ListBuffer<>(); aoqi@0: ListBuffer supertypes = new ListBuffer<>(); aoqi@0: for (Type i : ict.interfaces_field) { aoqi@0: if (i.isParameterized()) { aoqi@0: targs.appendList(i.tsym.type.allparams()); aoqi@0: } aoqi@0: supertypes.append(i.tsym.type); aoqi@0: } aoqi@0: IntersectionClassType notionalIntf = aoqi@0: (IntersectionClassType)types.makeCompoundType(supertypes.toList()); aoqi@0: notionalIntf.allparams_field = targs.toList(); aoqi@0: notionalIntf.tsym.flags_field |= INTERFACE; aoqi@0: return notionalIntf.tsym; aoqi@0: } aoqi@0: aoqi@0: private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) { aoqi@0: resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr", aoqi@0: diags.fragment(key, args))); aoqi@0: } aoqi@0: }; aoqi@0: aoqi@0: private Type fallbackDescriptorType(JCExpression tree) { aoqi@0: switch (tree.getTag()) { aoqi@0: case LAMBDA: aoqi@0: JCLambda lambda = (JCLambda)tree; aoqi@0: List argtypes = List.nil(); aoqi@0: for (JCVariableDecl param : lambda.params) { aoqi@0: argtypes = param.vartype != null ? aoqi@0: argtypes.append(param.vartype.type) : aoqi@0: argtypes.append(syms.errType); aoqi@0: } aoqi@0: return new MethodType(argtypes, Type.recoveryType, aoqi@0: List.of(syms.throwableType), syms.methodClass); aoqi@0: case REFERENCE: aoqi@0: return new MethodType(List.nil(), Type.recoveryType, aoqi@0: List.of(syms.throwableType), syms.methodClass); aoqi@0: default: aoqi@0: Assert.error("Cannot get here!"); aoqi@0: } aoqi@0: return null; aoqi@0: } aoqi@0: aoqi@0: private void checkAccessibleTypes(final DiagnosticPosition pos, final Env env, aoqi@0: final InferenceContext inferenceContext, final Type... ts) { aoqi@0: checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); aoqi@0: } aoqi@0: aoqi@0: private void checkAccessibleTypes(final DiagnosticPosition pos, final Env env, aoqi@0: final InferenceContext inferenceContext, final List ts) { aoqi@0: if (inferenceContext.free(ts)) { aoqi@0: inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { aoqi@0: @Override aoqi@0: public void typesInferred(InferenceContext inferenceContext) { aoqi@0: checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts)); aoqi@0: } aoqi@0: }); aoqi@0: } else { aoqi@0: for (Type t : ts) { aoqi@0: rs.checkAccessibleType(env, t); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Lambda/method reference have a special check context that ensures aoqi@0: * that i.e. a lambda return type is compatible with the expected aoqi@0: * type according to both the inherited context and the assignment aoqi@0: * context. aoqi@0: */ aoqi@0: class FunctionalReturnContext extends Check.NestedCheckContext { aoqi@0: aoqi@0: FunctionalReturnContext(CheckContext enclosingContext) { aoqi@0: super(enclosingContext); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public boolean compatible(Type found, Type req, Warner warn) { aoqi@0: //return type must be compatible in both current context and assignment context aoqi@0: return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void report(DiagnosticPosition pos, JCDiagnostic details) { aoqi@0: enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: class ExpressionLambdaReturnContext extends FunctionalReturnContext { aoqi@0: aoqi@0: JCExpression expr; aoqi@0: aoqi@0: ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { aoqi@0: super(enclosingContext); aoqi@0: this.expr = expr; aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public boolean compatible(Type found, Type req, Warner warn) { aoqi@0: //a void return is compatible with an expression statement lambda aoqi@0: return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) || aoqi@0: super.compatible(found, req, warn); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Lambda compatibility. Check that given return types, thrown types, parameter types aoqi@0: * are compatible with the expected functional interface descriptor. This means that: aoqi@0: * (i) parameter types must be identical to those of the target descriptor; (ii) return aoqi@0: * types must be compatible with the return type of the expected descriptor. aoqi@0: */ aoqi@0: private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) { aoqi@0: Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); aoqi@0: aoqi@0: //return values have already been checked - but if lambda has no return aoqi@0: //values, we must ensure that void/value compatibility is correct; aoqi@0: //this amounts at checking that, if a lambda body can complete normally, aoqi@0: //the descriptor's return type must be void aoqi@0: if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && aoqi@0: !returnType.hasTag(VOID) && returnType != Type.recoveryType) { aoqi@0: checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", aoqi@0: diags.fragment("missing.ret.val", returnType))); aoqi@0: } aoqi@0: aoqi@0: List argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes()); aoqi@0: if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { aoqi@0: checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a aoqi@0: * static field and that lambda has type annotations, these annotations will aoqi@0: * also be stored at these fake clinit methods. aoqi@0: * aoqi@0: * LambdaToMethod also use fake clinit methods so they can be reused. aoqi@0: * Also as LTM is a phase subsequent to attribution, the methods from aoqi@0: * clinits can be safely removed by LTM to save memory. aoqi@0: */ aoqi@0: private Map clinits = new HashMap<>(); aoqi@0: aoqi@0: public MethodSymbol removeClinit(ClassSymbol sym) { aoqi@0: return clinits.remove(sym); aoqi@0: } aoqi@0: aoqi@0: /* This method returns an environment to be used to attribute a lambda aoqi@0: * expression. aoqi@0: * aoqi@0: * The owner of this environment is a method symbol. If the current owner aoqi@0: * is not a method, for example if the lambda is used to initialize aoqi@0: * a field, then if the field is: aoqi@0: * aoqi@0: * - an instance field, we use the first constructor. aoqi@0: * - a static field, we create a fake clinit method. aoqi@0: */ aoqi@0: public Env lambdaEnv(JCLambda that, Env env) { aoqi@0: Env lambdaEnv; aoqi@0: Symbol owner = env.info.scope.owner; aoqi@0: if (owner.kind == VAR && owner.owner.kind == TYP) { aoqi@0: //field initializer aoqi@0: lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared())); aoqi@0: ClassSymbol enclClass = owner.enclClass(); aoqi@0: /* if the field isn't static, then we can get the first constructor aoqi@0: * and use it as the owner of the environment. This is what aoqi@0: * LTM code is doing to look for type annotations so we are fine. aoqi@0: */ aoqi@0: if ((owner.flags() & STATIC) == 0) { aoqi@0: for (Symbol s : enclClass.members_field.getElementsByName(names.init)) { aoqi@0: lambdaEnv.info.scope.owner = s; aoqi@0: break; aoqi@0: } aoqi@0: } else { aoqi@0: /* if the field is static then we need to create a fake clinit aoqi@0: * method, this method can later be reused by LTM. aoqi@0: */ aoqi@0: MethodSymbol clinit = clinits.get(enclClass); aoqi@0: if (clinit == null) { aoqi@0: Type clinitType = new MethodType(List.nil(), aoqi@0: syms.voidType, List.nil(), syms.methodClass); aoqi@0: clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE, aoqi@0: names.clinit, clinitType, enclClass); aoqi@0: clinit.params = List.nil(); aoqi@0: clinits.put(enclClass, clinit); aoqi@0: } aoqi@0: lambdaEnv.info.scope.owner = clinit; aoqi@0: } aoqi@0: } else { aoqi@0: lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); aoqi@0: } aoqi@0: return lambdaEnv; aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitReference(final JCMemberReference that) { aoqi@0: if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { aoqi@0: if (pt().hasTag(NONE)) { aoqi@0: //method reference only allowed in assignment or method invocation/cast context aoqi@0: log.error(that.pos(), "unexpected.mref"); aoqi@0: } aoqi@0: result = that.type = types.createErrorType(pt()); aoqi@0: return; aoqi@0: } aoqi@0: final Env localEnv = env.dup(that); aoqi@0: try { aoqi@0: //attribute member reference qualifier - if this is a constructor aoqi@0: //reference, the expected kind must be a type aoqi@0: Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); aoqi@0: aoqi@0: if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { aoqi@0: exprType = chk.checkConstructorRefType(that.expr, exprType); aoqi@0: if (!exprType.isErroneous() && aoqi@0: exprType.isRaw() && aoqi@0: that.typeargs != null) { aoqi@0: log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), aoqi@0: diags.fragment("mref.infer.and.explicit.params")); aoqi@0: exprType = types.createErrorType(exprType); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (exprType.isErroneous()) { aoqi@0: //if the qualifier expression contains problems, aoqi@0: //give up attribution of method reference aoqi@0: result = that.type = exprType; aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (TreeInfo.isStaticSelector(that.expr, names)) { aoqi@0: //if the qualifier is a type, validate it; raw warning check is aoqi@0: //omitted as we don't know at this stage as to whether this is a aoqi@0: //raw selector (because of inference) aoqi@0: chk.validate(that.expr, env, false); aoqi@0: } aoqi@0: aoqi@0: //attrib type-arguments aoqi@0: List typeargtypes = List.nil(); aoqi@0: if (that.typeargs != null) { aoqi@0: typeargtypes = attribTypes(that.typeargs, localEnv); aoqi@0: } aoqi@0: aoqi@0: Type desc; aoqi@0: Type currentTarget = pt(); aoqi@0: boolean isTargetSerializable = aoqi@0: resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && aoqi@0: isSerializable(currentTarget); aoqi@0: if (currentTarget != Type.recoveryType) { vromero@2543: currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that)); aoqi@0: desc = types.findDescriptorType(currentTarget); aoqi@0: } else { aoqi@0: currentTarget = Type.recoveryType; aoqi@0: desc = fallbackDescriptorType(that); aoqi@0: } aoqi@0: aoqi@0: setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext); aoqi@0: List argtypes = desc.getParameterTypes(); aoqi@0: Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck; aoqi@0: aoqi@0: if (resultInfo.checkContext.inferenceContext().free(argtypes)) { aoqi@0: referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); aoqi@0: } aoqi@0: aoqi@0: Pair refResult = null; aoqi@0: List saved_undet = resultInfo.checkContext.inferenceContext().save(); aoqi@0: try { aoqi@0: refResult = rs.resolveMemberReference(localEnv, that, that.expr.type, aoqi@0: that.name, argtypes, typeargtypes, referenceCheck, aoqi@0: resultInfo.checkContext.inferenceContext(), aoqi@0: resultInfo.checkContext.deferredAttrContext().mode); aoqi@0: } finally { aoqi@0: resultInfo.checkContext.inferenceContext().rollback(saved_undet); aoqi@0: } aoqi@0: aoqi@0: Symbol refSym = refResult.fst; aoqi@0: Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; aoqi@0: aoqi@0: if (refSym.kind != MTH) { aoqi@0: boolean targetError; aoqi@0: switch (refSym.kind) { aoqi@0: case ABSENT_MTH: aoqi@0: targetError = false; aoqi@0: break; aoqi@0: case WRONG_MTH: aoqi@0: case WRONG_MTHS: aoqi@0: case AMBIGUOUS: aoqi@0: case HIDDEN: aoqi@0: case STATICERR: aoqi@0: case MISSING_ENCL: aoqi@0: case WRONG_STATICNESS: aoqi@0: targetError = true; aoqi@0: break; aoqi@0: default: aoqi@0: Assert.error("unexpected result kind " + refSym.kind); aoqi@0: targetError = false; aoqi@0: } aoqi@0: aoqi@0: JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, aoqi@0: that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); aoqi@0: aoqi@0: JCDiagnostic.DiagnosticType diagKind = targetError ? aoqi@0: JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; aoqi@0: aoqi@0: JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, aoqi@0: "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); aoqi@0: aoqi@0: if (targetError && currentTarget == Type.recoveryType) { aoqi@0: //a target error doesn't make sense during recovery stage aoqi@0: //as we don't know what actual parameter types are aoqi@0: result = that.type = currentTarget; aoqi@0: return; aoqi@0: } else { aoqi@0: if (targetError) { aoqi@0: resultInfo.checkContext.report(that, diag); aoqi@0: } else { aoqi@0: log.report(diag); aoqi@0: } aoqi@0: result = that.type = types.createErrorType(currentTarget); aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: that.sym = refSym.baseSymbol(); aoqi@0: that.kind = lookupHelper.referenceKind(that.sym); aoqi@0: that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); aoqi@0: aoqi@0: if (desc.getReturnType() == Type.recoveryType) { aoqi@0: // stop here aoqi@0: result = that.type = currentTarget; aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { aoqi@0: aoqi@0: if (that.getMode() == ReferenceMode.INVOKE && aoqi@0: TreeInfo.isStaticSelector(that.expr, names) && aoqi@0: that.kind.isUnbound() && aoqi@0: !desc.getParameterTypes().head.isParameterized()) { aoqi@0: chk.checkRaw(that.expr, localEnv); aoqi@0: } aoqi@0: aoqi@0: if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && aoqi@0: exprType.getTypeArguments().nonEmpty()) { aoqi@0: //static ref with class type-args aoqi@0: log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), aoqi@0: diags.fragment("static.mref.with.targs")); aoqi@0: result = that.type = types.createErrorType(currentTarget); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) && aoqi@0: !that.kind.isUnbound()) { aoqi@0: //no static bound mrefs aoqi@0: log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), aoqi@0: diags.fragment("static.bound.mref")); aoqi@0: result = that.type = types.createErrorType(currentTarget); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { aoqi@0: // Check that super-qualified symbols are not abstract (JLS) aoqi@0: rs.checkNonAbstract(that.pos(), that.sym); aoqi@0: } aoqi@0: aoqi@0: if (isTargetSerializable) { aoqi@0: chk.checkElemAccessFromSerializableLambda(that); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: ResultInfo checkInfo = aoqi@0: resultInfo.dup(newMethodTemplate( aoqi@0: desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), aoqi@0: that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes), aoqi@0: new FunctionalReturnContext(resultInfo.checkContext)); aoqi@0: aoqi@0: Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); aoqi@0: aoqi@0: if (that.kind.isUnbound() && aoqi@0: resultInfo.checkContext.inferenceContext().free(argtypes.head)) { aoqi@0: //re-generate inference constraints for unbound receiver aoqi@0: if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) { aoqi@0: //cannot happen as this has already been checked - we just need aoqi@0: //to regenerate the inference constraints, as that has been lost aoqi@0: //as a result of the call to inferenceContext.save() aoqi@0: Assert.error("Can't get here"); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (!refType.isErroneous()) { aoqi@0: refType = types.createMethodTypeWithReturn(refType, aoqi@0: adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); aoqi@0: } aoqi@0: aoqi@0: //go ahead with standard method reference compatibility check - note that param check aoqi@0: //is a no-op (as this has been taken care during method applicability) aoqi@0: boolean isSpeculativeRound = aoqi@0: resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; aoqi@0: checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); aoqi@0: if (!isSpeculativeRound) { aoqi@0: checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget); aoqi@0: } aoqi@0: result = check(that, currentTarget, VAL, resultInfo); aoqi@0: } catch (Types.FunctionDescriptorLookupError ex) { aoqi@0: JCDiagnostic cause = ex.getDiagnostic(); aoqi@0: resultInfo.checkContext.report(that, cause); aoqi@0: result = that.type = types.createErrorType(pt()); aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: //where aoqi@0: ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { aoqi@0: //if this is a constructor reference, the expected kind must be a type aoqi@0: return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: @SuppressWarnings("fallthrough") aoqi@0: void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { aoqi@0: Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); aoqi@0: aoqi@0: Type resType; aoqi@0: switch (tree.getMode()) { aoqi@0: case NEW: aoqi@0: if (!tree.expr.type.isRaw()) { aoqi@0: resType = tree.expr.type; aoqi@0: break; aoqi@0: } aoqi@0: default: aoqi@0: resType = refType.getReturnType(); aoqi@0: } aoqi@0: aoqi@0: Type incompatibleReturnType = resType; aoqi@0: aoqi@0: if (returnType.hasTag(VOID)) { aoqi@0: incompatibleReturnType = null; aoqi@0: } aoqi@0: aoqi@0: if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { aoqi@0: if (resType.isErroneous() || aoqi@0: new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) { aoqi@0: incompatibleReturnType = null; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (incompatibleReturnType != null) { aoqi@0: checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", aoqi@0: diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); aoqi@0: } aoqi@0: aoqi@0: if (!speculativeAttr) { aoqi@0: List thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes()); aoqi@0: if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { aoqi@0: log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Set functional type info on the underlying AST. Note: as the target descriptor aoqi@0: * might contain inference variables, we might need to register an hook in the aoqi@0: * current inference context. aoqi@0: */ aoqi@0: private void setFunctionalInfo(final Env env, final JCFunctionalExpression fExpr, aoqi@0: final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) { aoqi@0: if (checkContext.inferenceContext().free(descriptorType)) { aoqi@0: checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() { aoqi@0: public void typesInferred(InferenceContext inferenceContext) { aoqi@0: setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType), aoqi@0: inferenceContext.asInstType(primaryTarget), checkContext); aoqi@0: } aoqi@0: }); aoqi@0: } else { aoqi@0: ListBuffer targets = new ListBuffer<>(); aoqi@0: if (pt.hasTag(CLASS)) { aoqi@0: if (pt.isCompound()) { aoqi@0: targets.append(types.removeWildcards(primaryTarget)); //this goes first aoqi@0: for (Type t : ((IntersectionClassType)pt()).interfaces_field) { aoqi@0: if (t != primaryTarget) { aoqi@0: targets.append(types.removeWildcards(t)); aoqi@0: } aoqi@0: } aoqi@0: } else { aoqi@0: targets.append(types.removeWildcards(primaryTarget)); aoqi@0: } aoqi@0: } aoqi@0: fExpr.targets = targets.toList(); aoqi@0: if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && aoqi@0: pt != Type.recoveryType) { aoqi@0: //check that functional interface class is well-formed aoqi@0: try { aoqi@0: /* Types.makeFunctionalInterfaceClass() may throw an exception aoqi@0: * when it's executed post-inference. See the listener code aoqi@0: * above. aoqi@0: */ aoqi@0: ClassSymbol csym = types.makeFunctionalInterfaceClass(env, aoqi@0: names.empty, List.of(fExpr.targets.head), ABSTRACT); aoqi@0: if (csym != null) { aoqi@0: chk.checkImplementations(env.tree, csym, csym); aoqi@0: } aoqi@0: } catch (Types.FunctionDescriptorLookupError ex) { aoqi@0: JCDiagnostic cause = ex.getDiagnostic(); aoqi@0: resultInfo.checkContext.report(env.tree, cause); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitParens(JCParens tree) { aoqi@0: Type owntype = attribTree(tree.expr, env, resultInfo); aoqi@0: result = check(tree, owntype, pkind(), resultInfo); aoqi@0: Symbol sym = TreeInfo.symbol(tree); aoqi@0: if (sym != null && (sym.kind&(TYP|PCK)) != 0) aoqi@0: log.error(tree.pos(), "illegal.start.of.type"); aoqi@0: } aoqi@0: aoqi@0: public void visitAssign(JCAssign tree) { aoqi@0: Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo); aoqi@0: Type capturedType = capture(owntype); aoqi@0: attribExpr(tree.rhs, env, owntype); aoqi@0: result = check(tree, capturedType, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitAssignop(JCAssignOp tree) { aoqi@0: // Attribute arguments. aoqi@0: Type owntype = attribTree(tree.lhs, env, varInfo); aoqi@0: Type operand = attribExpr(tree.rhs, env); aoqi@0: // Find operator. aoqi@0: Symbol operator = tree.operator = rs.resolveBinaryOperator( aoqi@0: tree.pos(), tree.getTag().noAssignOp(), env, aoqi@0: owntype, operand); aoqi@0: aoqi@0: if (operator.kind == MTH && aoqi@0: !owntype.isErroneous() && aoqi@0: !operand.isErroneous()) { aoqi@0: chk.checkOperator(tree.pos(), aoqi@0: (OperatorSymbol)operator, aoqi@0: tree.getTag().noAssignOp(), aoqi@0: owntype, aoqi@0: operand); aoqi@0: chk.checkDivZero(tree.rhs.pos(), operator, operand); aoqi@0: chk.checkCastable(tree.rhs.pos(), aoqi@0: operator.type.getReturnType(), aoqi@0: owntype); aoqi@0: } aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitUnary(JCUnary tree) { aoqi@0: // Attribute arguments. aoqi@0: Type argtype = (tree.getTag().isIncOrDecUnaryOp()) aoqi@0: ? attribTree(tree.arg, env, varInfo) aoqi@0: : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); aoqi@0: aoqi@0: // Find operator. aoqi@0: Symbol operator = tree.operator = aoqi@0: rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype); aoqi@0: aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: if (operator.kind == MTH && aoqi@0: !argtype.isErroneous()) { aoqi@0: owntype = (tree.getTag().isIncOrDecUnaryOp()) aoqi@0: ? tree.arg.type aoqi@0: : operator.type.getReturnType(); aoqi@0: int opc = ((OperatorSymbol)operator).opcode; aoqi@0: aoqi@0: // If the argument is constant, fold it. aoqi@0: if (argtype.constValue() != null) { aoqi@0: Type ctype = cfolder.fold1(opc, argtype); aoqi@0: if (ctype != null) { aoqi@0: owntype = cfolder.coerce(ctype, owntype); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitBinary(JCBinary tree) { aoqi@0: // Attribute arguments. aoqi@0: Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); aoqi@0: Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env)); aoqi@0: aoqi@0: // Find operator. aoqi@0: Symbol operator = tree.operator = aoqi@0: rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right); aoqi@0: aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: if (operator.kind == MTH && aoqi@0: !left.isErroneous() && aoqi@0: !right.isErroneous()) { aoqi@0: owntype = operator.type.getReturnType(); aoqi@0: // This will figure out when unboxing can happen and aoqi@0: // choose the right comparison operator. aoqi@0: int opc = chk.checkOperator(tree.lhs.pos(), aoqi@0: (OperatorSymbol)operator, aoqi@0: tree.getTag(), aoqi@0: left, aoqi@0: right); aoqi@0: aoqi@0: // If both arguments are constants, fold them. aoqi@0: if (left.constValue() != null && right.constValue() != null) { aoqi@0: Type ctype = cfolder.fold2(opc, left, right); aoqi@0: if (ctype != null) { aoqi@0: owntype = cfolder.coerce(ctype, owntype); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Check that argument types of a reference ==, != are aoqi@0: // castable to each other, (JLS 15.21). Note: unboxing aoqi@0: // comparisons will not have an acmp* opc at this point. aoqi@0: if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { aoqi@0: if (!types.isEqualityComparable(left, right, aoqi@0: new Warner(tree.pos()))) { aoqi@0: log.error(tree.pos(), "incomparable.types", left, right); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: chk.checkDivZero(tree.rhs.pos(), operator, right); aoqi@0: } aoqi@0: result = check(tree, owntype, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitTypeCast(final JCTypeCast tree) { aoqi@0: Type clazztype = attribType(tree.clazz, env); aoqi@0: chk.validate(tree.clazz, env, false); aoqi@0: //a fresh environment is required for 292 inference to work properly --- aoqi@0: //see Infer.instantiatePolymorphicSignatureInstance() aoqi@0: Env localEnv = env.dup(tree); aoqi@0: //should we propagate the target type? aoqi@0: final ResultInfo castInfo; aoqi@0: JCExpression expr = TreeInfo.skipParens(tree.expr); aoqi@0: boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE)); aoqi@0: if (isPoly) { aoqi@0: //expression is a poly - we need to propagate target type info aoqi@0: castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) { aoqi@0: @Override aoqi@0: public boolean compatible(Type found, Type req, Warner warn) { aoqi@0: return types.isCastable(found, req, warn); aoqi@0: } aoqi@0: }); aoqi@0: } else { aoqi@0: //standalone cast - target-type info is not propagated aoqi@0: castInfo = unknownExprInfo; aoqi@0: } aoqi@0: Type exprtype = attribTree(tree.expr, localEnv, castInfo); aoqi@0: Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); aoqi@0: if (exprtype.constValue() != null) aoqi@0: owntype = cfolder.coerce(exprtype, owntype); aoqi@0: result = check(tree, capture(owntype), VAL, resultInfo); aoqi@0: if (!isPoly) aoqi@0: chk.checkRedundantCast(localEnv, tree); aoqi@0: } aoqi@0: aoqi@0: public void visitTypeTest(JCInstanceOf tree) { aoqi@0: Type exprtype = chk.checkNullOrRefType( aoqi@0: tree.expr.pos(), attribExpr(tree.expr, env)); aoqi@0: Type clazztype = attribType(tree.clazz, env); aoqi@0: if (!clazztype.hasTag(TYPEVAR)) { aoqi@0: clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype); aoqi@0: } aoqi@0: if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) { aoqi@0: log.error(tree.clazz.pos(), "illegal.generic.type.for.instof"); aoqi@0: clazztype = types.createErrorType(clazztype); aoqi@0: } aoqi@0: chk.validate(tree.clazz, env, false); aoqi@0: chk.checkCastable(tree.expr.pos(), exprtype, clazztype); aoqi@0: result = check(tree, syms.booleanType, VAL, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitIndexed(JCArrayAccess tree) { aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: Type atype = attribExpr(tree.indexed, env); aoqi@0: attribExpr(tree.index, env, syms.intType); aoqi@0: if (types.isArray(atype)) aoqi@0: owntype = types.elemtype(atype); aoqi@0: else if (!atype.hasTag(ERROR)) aoqi@0: log.error(tree.pos(), "array.req.but.found", atype); aoqi@0: if ((pkind() & VAR) == 0) owntype = capture(owntype); aoqi@0: result = check(tree, owntype, VAR, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitIdent(JCIdent tree) { aoqi@0: Symbol sym; aoqi@0: aoqi@0: // Find symbol aoqi@0: if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { aoqi@0: // If we are looking for a method, the prototype `pt' will be a aoqi@0: // method type with the type of the call's arguments as parameters. aoqi@0: env.info.pendingResolutionPhase = null; aoqi@0: sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); aoqi@0: } else if (tree.sym != null && tree.sym.kind != VAR) { aoqi@0: sym = tree.sym; aoqi@0: } else { aoqi@0: sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); aoqi@0: } aoqi@0: tree.sym = sym; aoqi@0: aoqi@0: // (1) Also find the environment current for the class where aoqi@0: // sym is defined (`symEnv'). aoqi@0: // Only for pre-tiger versions (1.4 and earlier): aoqi@0: // (2) Also determine whether we access symbol out of an anonymous aoqi@0: // class in a this or super call. This is illegal for instance aoqi@0: // members since such classes don't carry a this$n link. aoqi@0: // (`noOuterThisPath'). aoqi@0: Env symEnv = env; aoqi@0: boolean noOuterThisPath = false; aoqi@0: if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class aoqi@0: (sym.kind & (VAR | MTH | TYP)) != 0 && aoqi@0: sym.owner.kind == TYP && aoqi@0: tree.name != names._this && tree.name != names._super) { aoqi@0: aoqi@0: // Find environment in which identifier is defined. aoqi@0: while (symEnv.outer != null && aoqi@0: !sym.isMemberOf(symEnv.enclClass.sym, types)) { aoqi@0: if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) aoqi@0: noOuterThisPath = !allowAnonOuterThis; aoqi@0: symEnv = symEnv.outer; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // If symbol is a variable, ... aoqi@0: if (sym.kind == VAR) { aoqi@0: VarSymbol v = (VarSymbol)sym; aoqi@0: aoqi@0: // ..., evaluate its initializer, if it has one, and check for aoqi@0: // illegal forward reference. aoqi@0: checkInit(tree, env, v, false); aoqi@0: aoqi@0: // If we are expecting a variable (as opposed to a value), check aoqi@0: // that the variable is assignable in the current environment. aoqi@0: if (pkind() == VAR) aoqi@0: checkAssignable(tree.pos(), v, null, env); aoqi@0: } aoqi@0: aoqi@0: // In a constructor body, aoqi@0: // if symbol is a field or instance method, check that it is aoqi@0: // not accessed before the supertype constructor is called. aoqi@0: if ((symEnv.info.isSelfCall || noOuterThisPath) && aoqi@0: (sym.kind & (VAR | MTH)) != 0 && aoqi@0: sym.owner.kind == TYP && aoqi@0: (sym.flags() & STATIC) == 0) { aoqi@0: chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env)); aoqi@0: } aoqi@0: Env env1 = env; aoqi@0: if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) { aoqi@0: // If the found symbol is inaccessible, then it is aoqi@0: // accessed through an enclosing instance. Locate this aoqi@0: // enclosing instance: aoqi@0: while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) aoqi@0: env1 = env1.outer; aoqi@0: } aoqi@0: aoqi@0: if (env.info.isSerializable) { aoqi@0: chk.checkElemAccessFromSerializableLambda(tree); aoqi@0: } aoqi@0: aoqi@0: result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitSelect(JCFieldAccess tree) { aoqi@0: // Determine the expected kind of the qualifier expression. aoqi@0: int skind = 0; aoqi@0: if (tree.name == names._this || tree.name == names._super || aoqi@0: tree.name == names._class) aoqi@0: { aoqi@0: skind = TYP; aoqi@0: } else { aoqi@0: if ((pkind() & PCK) != 0) skind = skind | PCK; aoqi@0: if ((pkind() & TYP) != 0) skind = skind | TYP | PCK; aoqi@0: if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP; aoqi@0: } aoqi@0: aoqi@0: // Attribute the qualifier expression, and determine its symbol (if any). aoqi@0: Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly)); aoqi@0: if ((pkind() & (PCK | TYP)) == 0) aoqi@0: site = capture(site); // Capture field access aoqi@0: aoqi@0: // don't allow T.class T[].class, etc aoqi@0: if (skind == TYP) { aoqi@0: Type elt = site; aoqi@0: while (elt.hasTag(ARRAY)) aoqi@0: elt = ((ArrayType)elt.unannotatedType()).elemtype; aoqi@0: if (elt.hasTag(TYPEVAR)) { aoqi@0: log.error(tree.pos(), "type.var.cant.be.deref"); jlahoda@2617: result = tree.type = types.createErrorType(tree.name, site.tsym, site); jlahoda@2617: tree.sym = tree.type.tsym; jlahoda@2617: return ; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // If qualifier symbol is a type or `super', assert `selectSuper' aoqi@0: // for the selection. This is relevant for determining whether aoqi@0: // protected symbols are accessible. aoqi@0: Symbol sitesym = TreeInfo.symbol(tree.selected); aoqi@0: boolean selectSuperPrev = env.info.selectSuper; aoqi@0: env.info.selectSuper = aoqi@0: sitesym != null && aoqi@0: sitesym.name == names._super; aoqi@0: aoqi@0: // Determine the symbol represented by the selection. aoqi@0: env.info.pendingResolutionPhase = null; aoqi@0: Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); vromero@2610: if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) { vromero@2610: log.error(tree.selected.pos(), "not.encl.class", site.tsym); vromero@2610: sym = syms.errSymbol; vromero@2610: } aoqi@0: if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) { aoqi@0: site = capture(site); aoqi@0: sym = selectSym(tree, sitesym, site, env, resultInfo); aoqi@0: } aoqi@0: boolean varArgs = env.info.lastResolveVarargs(); aoqi@0: tree.sym = sym; aoqi@0: aoqi@0: if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { aoqi@0: while (site.hasTag(TYPEVAR)) site = site.getUpperBound(); aoqi@0: site = capture(site); aoqi@0: } aoqi@0: aoqi@0: // If that symbol is a variable, ... aoqi@0: if (sym.kind == VAR) { aoqi@0: VarSymbol v = (VarSymbol)sym; aoqi@0: aoqi@0: // ..., evaluate its initializer, if it has one, and check for aoqi@0: // illegal forward reference. aoqi@0: checkInit(tree, env, v, true); aoqi@0: aoqi@0: // If we are expecting a variable (as opposed to a value), check aoqi@0: // that the variable is assignable in the current environment. aoqi@0: if (pkind() == VAR) aoqi@0: checkAssignable(tree.pos(), v, tree.selected, env); aoqi@0: } aoqi@0: aoqi@0: if (sitesym != null && aoqi@0: sitesym.kind == VAR && aoqi@0: ((VarSymbol)sitesym).isResourceVariable() && aoqi@0: sym.kind == MTH && aoqi@0: sym.name.equals(names.close) && aoqi@0: sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && aoqi@0: env.info.lint.isEnabled(LintCategory.TRY)) { aoqi@0: log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); aoqi@0: } aoqi@0: aoqi@0: // Disallow selecting a type from an expression aoqi@0: if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) { aoqi@0: tree.type = check(tree.selected, pt(), aoqi@0: sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt())); aoqi@0: } aoqi@0: aoqi@0: if (isType(sitesym)) { aoqi@0: if (sym.name == names._this) { aoqi@0: // If `C' is the currently compiled class, check that aoqi@0: // C.this' does not appear in a call to a super(...) aoqi@0: if (env.info.isSelfCall && aoqi@0: site.tsym == env.enclClass.sym) { aoqi@0: chk.earlyRefError(tree.pos(), sym); aoqi@0: } aoqi@0: } else { aoqi@0: // Check if type-qualified fields or methods are static (JLS) aoqi@0: if ((sym.flags() & STATIC) == 0 && aoqi@0: !env.next.tree.hasTag(REFERENCE) && aoqi@0: sym.name != names._super && aoqi@0: (sym.kind == VAR || sym.kind == MTH)) { aoqi@0: rs.accessBase(rs.new StaticError(sym), aoqi@0: tree.pos(), site, sym.name, true); aoqi@0: } aoqi@0: } aoqi@0: if (!allowStaticInterfaceMethods && sitesym.isInterface() && aoqi@0: sym.isStatic() && sym.kind == MTH) { aoqi@0: log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName); aoqi@0: } aoqi@0: } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) { aoqi@0: // If the qualified item is not a type and the selected item is static, report aoqi@0: // a warning. Make allowance for the class of an array type e.g. Object[].class) aoqi@0: chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner); aoqi@0: } aoqi@0: aoqi@0: // If we are selecting an instance member via a `super', ... aoqi@0: if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { aoqi@0: aoqi@0: // Check that super-qualified symbols are not abstract (JLS) aoqi@0: rs.checkNonAbstract(tree.pos(), sym); aoqi@0: aoqi@0: if (site.isRaw()) { aoqi@0: // Determine argument types for site. aoqi@0: Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); aoqi@0: if (site1 != null) site = site1; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (env.info.isSerializable) { aoqi@0: chk.checkElemAccessFromSerializableLambda(tree); aoqi@0: } aoqi@0: aoqi@0: env.info.selectSuper = selectSuperPrev; aoqi@0: result = checkId(tree, site, sym, env, resultInfo); aoqi@0: } aoqi@0: //where aoqi@0: /** Determine symbol referenced by a Select expression, aoqi@0: * aoqi@0: * @param tree The select tree. aoqi@0: * @param site The type of the selected expression, aoqi@0: * @param env The current environment. aoqi@0: * @param resultInfo The current result. aoqi@0: */ aoqi@0: private Symbol selectSym(JCFieldAccess tree, aoqi@0: Symbol location, aoqi@0: Type site, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: DiagnosticPosition pos = tree.pos(); aoqi@0: Name name = tree.name; aoqi@0: switch (site.getTag()) { aoqi@0: case PACKAGE: aoqi@0: return rs.accessBase( aoqi@0: rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), aoqi@0: pos, location, site, name, true); aoqi@0: case ARRAY: aoqi@0: case CLASS: aoqi@0: if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { aoqi@0: return rs.resolveQualifiedMethod( aoqi@0: pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); aoqi@0: } else if (name == names._this || name == names._super) { aoqi@0: return rs.resolveSelf(pos, env, site.tsym, name); aoqi@0: } else if (name == names._class) { aoqi@0: // In this case, we have already made sure in aoqi@0: // visitSelect that qualifier expression is a type. aoqi@0: Type t = syms.classType; aoqi@0: List typeargs = allowGenerics aoqi@0: ? List.of(types.erasure(site)) aoqi@0: : List.nil(); aoqi@0: t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); aoqi@0: return new VarSymbol( aoqi@0: STATIC | PUBLIC | FINAL, names._class, t, site.tsym); aoqi@0: } else { aoqi@0: // We are seeing a plain identifier as selector. aoqi@0: Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); aoqi@0: if ((resultInfo.pkind & ERRONEOUS) == 0) aoqi@0: sym = rs.accessBase(sym, pos, location, site, name, true); aoqi@0: return sym; aoqi@0: } aoqi@0: case WILDCARD: aoqi@0: throw new AssertionError(tree); aoqi@0: case TYPEVAR: aoqi@0: // Normally, site.getUpperBound() shouldn't be null. aoqi@0: // It should only happen during memberEnter/attribBase aoqi@0: // when determining the super type which *must* beac aoqi@0: // done before attributing the type variables. In aoqi@0: // other words, we are seeing this illegal program: aoqi@0: // class B extends A {} aoqi@0: Symbol sym = (site.getUpperBound() != null) aoqi@0: ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) aoqi@0: : null; aoqi@0: if (sym == null) { aoqi@0: log.error(pos, "type.var.cant.be.deref"); aoqi@0: return syms.errSymbol; aoqi@0: } else { aoqi@0: Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? aoqi@0: rs.new AccessError(env, site, sym) : aoqi@0: sym; aoqi@0: rs.accessBase(sym2, pos, location, site, name, true); aoqi@0: return sym; aoqi@0: } aoqi@0: case ERROR: aoqi@0: // preserve identifier names through errors aoqi@0: return types.createErrorType(name, site.tsym, site).tsym; aoqi@0: default: aoqi@0: // The qualifier expression is of a primitive type -- only aoqi@0: // .class is allowed for these. aoqi@0: if (name == names._class) { aoqi@0: // In this case, we have already made sure in Select that aoqi@0: // qualifier expression is a type. aoqi@0: Type t = syms.classType; aoqi@0: Type arg = types.boxedClass(site).type; aoqi@0: t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); aoqi@0: return new VarSymbol( aoqi@0: STATIC | PUBLIC | FINAL, names._class, t, site.tsym); aoqi@0: } else { aoqi@0: log.error(pos, "cant.deref", site); aoqi@0: return syms.errSymbol; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Determine type of identifier or select expression and check that aoqi@0: * (1) the referenced symbol is not deprecated aoqi@0: * (2) the symbol's type is safe (@see checkSafe) aoqi@0: * (3) if symbol is a variable, check that its type and kind are aoqi@0: * compatible with the prototype and protokind. aoqi@0: * (4) if symbol is an instance field of a raw type, aoqi@0: * which is being assigned to, issue an unchecked warning if its aoqi@0: * type changes under erasure. aoqi@0: * (5) if symbol is an instance method of a raw type, issue an aoqi@0: * unchecked warning if its argument types change under erasure. aoqi@0: * If checks succeed: aoqi@0: * If symbol is a constant, return its constant type aoqi@0: * else if symbol is a method, return its result type aoqi@0: * otherwise return its type. aoqi@0: * Otherwise return errType. aoqi@0: * aoqi@0: * @param tree The syntax tree representing the identifier aoqi@0: * @param site If this is a select, the type of the selected aoqi@0: * expression, otherwise the type of the current class. aoqi@0: * @param sym The symbol representing the identifier. aoqi@0: * @param env The current environment. aoqi@0: * @param resultInfo The expected result aoqi@0: */ aoqi@0: Type checkId(JCTree tree, aoqi@0: Type site, aoqi@0: Symbol sym, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? aoqi@0: checkMethodId(tree, site, sym, env, resultInfo) : aoqi@0: checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); aoqi@0: } aoqi@0: aoqi@0: Type checkMethodId(JCTree tree, aoqi@0: Type site, aoqi@0: Symbol sym, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: boolean isPolymorhicSignature = aoqi@0: (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0; aoqi@0: return isPolymorhicSignature ? aoqi@0: checkSigPolyMethodId(tree, site, sym, env, resultInfo) : aoqi@0: checkMethodIdInternal(tree, site, sym, env, resultInfo); aoqi@0: } aoqi@0: aoqi@0: Type checkSigPolyMethodId(JCTree tree, aoqi@0: Type site, aoqi@0: Symbol sym, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: //recover original symbol for signature polymorphic methods aoqi@0: checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); aoqi@0: env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; aoqi@0: return sym.type; aoqi@0: } aoqi@0: aoqi@0: Type checkMethodIdInternal(JCTree tree, aoqi@0: Type site, aoqi@0: Symbol sym, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: if ((resultInfo.pkind & POLY) != 0) { aoqi@0: Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); aoqi@0: Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); aoqi@0: resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); aoqi@0: return owntype; aoqi@0: } else { aoqi@0: return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: Type checkIdInternal(JCTree tree, aoqi@0: Type site, aoqi@0: Symbol sym, aoqi@0: Type pt, aoqi@0: Env env, aoqi@0: ResultInfo resultInfo) { aoqi@0: if (pt.isErroneous()) { aoqi@0: return types.createErrorType(site); aoqi@0: } aoqi@0: Type owntype; // The computed type of this identifier occurrence. aoqi@0: switch (sym.kind) { aoqi@0: case TYP: aoqi@0: // For types, the computed type equals the symbol's type, aoqi@0: // except for two situations: aoqi@0: owntype = sym.type; aoqi@0: if (owntype.hasTag(CLASS)) { aoqi@0: chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); aoqi@0: Type ownOuter = owntype.getEnclosingType(); aoqi@0: aoqi@0: // (a) If the symbol's type is parameterized, erase it aoqi@0: // because no type parameters were given. aoqi@0: // We recover generic outer type later in visitTypeApply. aoqi@0: if (owntype.tsym.type.getTypeArguments().nonEmpty()) { aoqi@0: owntype = types.erasure(owntype); aoqi@0: } aoqi@0: aoqi@0: // (b) If the symbol's type is an inner class, then aoqi@0: // we have to interpret its outer type as a superclass aoqi@0: // of the site type. Example: aoqi@0: // aoqi@0: // class Tree { class Visitor { ... } } aoqi@0: // class PointTree extends Tree { ... } aoqi@0: // ...PointTree.Visitor... aoqi@0: // aoqi@0: // Then the type of the last expression above is aoqi@0: // Tree.Visitor. aoqi@0: else if (ownOuter.hasTag(CLASS) && site != ownOuter) { aoqi@0: Type normOuter = site; aoqi@0: if (normOuter.hasTag(CLASS)) { aoqi@0: normOuter = types.asEnclosingSuper(site, ownOuter.tsym); aoqi@0: } aoqi@0: if (normOuter == null) // perhaps from an import aoqi@0: normOuter = types.erasure(ownOuter); aoqi@0: if (normOuter != ownOuter) aoqi@0: owntype = new ClassType( aoqi@0: normOuter, List.nil(), owntype.tsym); aoqi@0: } aoqi@0: } aoqi@0: break; aoqi@0: case VAR: aoqi@0: VarSymbol v = (VarSymbol)sym; aoqi@0: // Test (4): if symbol is an instance field of a raw type, aoqi@0: // which is being assigned to, issue an unchecked warning if aoqi@0: // its type changes under erasure. aoqi@0: if (allowGenerics && aoqi@0: resultInfo.pkind == VAR && aoqi@0: v.owner.kind == TYP && aoqi@0: (v.flags() & STATIC) == 0 && aoqi@0: (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { aoqi@0: Type s = types.asOuterSuper(site, v.owner); aoqi@0: if (s != null && aoqi@0: s.isRaw() && aoqi@0: !types.isSameType(v.type, v.erasure(types))) { aoqi@0: chk.warnUnchecked(tree.pos(), aoqi@0: "unchecked.assign.to.var", aoqi@0: v, s); aoqi@0: } aoqi@0: } aoqi@0: // The computed type of a variable is the type of the aoqi@0: // variable symbol, taken as a member of the site type. aoqi@0: owntype = (sym.owner.kind == TYP && aoqi@0: sym.name != names._this && sym.name != names._super) aoqi@0: ? types.memberType(site, sym) aoqi@0: : sym.type; aoqi@0: aoqi@0: // If the variable is a constant, record constant value in aoqi@0: // computed type. aoqi@0: if (v.getConstValue() != null && isStaticReference(tree)) aoqi@0: owntype = owntype.constType(v.getConstValue()); aoqi@0: aoqi@0: if (resultInfo.pkind == VAL) { aoqi@0: owntype = capture(owntype); // capture "names as expressions" aoqi@0: } aoqi@0: break; aoqi@0: case MTH: { aoqi@0: owntype = checkMethod(site, sym, aoqi@0: new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext), aoqi@0: env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), aoqi@0: resultInfo.pt.getTypeArguments()); aoqi@0: break; aoqi@0: } aoqi@0: case PCK: case ERR: aoqi@0: owntype = sym.type; aoqi@0: break; aoqi@0: default: aoqi@0: throw new AssertionError("unexpected kind: " + sym.kind + aoqi@0: " in tree " + tree); aoqi@0: } aoqi@0: aoqi@0: // Test (1): emit a `deprecation' warning if symbol is deprecated. aoqi@0: // (for constructors, the error was given when the constructor was aoqi@0: // resolved) aoqi@0: aoqi@0: if (sym.name != names.init) { aoqi@0: chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); aoqi@0: chk.checkSunAPI(tree.pos(), sym); aoqi@0: chk.checkProfile(tree.pos(), sym); aoqi@0: } aoqi@0: aoqi@0: // Test (3): if symbol is a variable, check that its type and aoqi@0: // kind are compatible with the prototype and protokind. aoqi@0: return check(tree, owntype, sym.kind, resultInfo); aoqi@0: } aoqi@0: aoqi@0: /** Check that variable is initialized and evaluate the variable's aoqi@0: * initializer, if not yet done. Also check that variable is not aoqi@0: * referenced before it is defined. aoqi@0: * @param tree The tree making up the variable reference. aoqi@0: * @param env The current environment. aoqi@0: * @param v The variable's symbol. aoqi@0: */ aoqi@0: private void checkInit(JCTree tree, aoqi@0: Env env, aoqi@0: VarSymbol v, aoqi@0: boolean onlyWarning) { aoqi@0: // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + aoqi@0: // tree.pos + " " + v.pos + " " + aoqi@0: // Resolve.isStatic(env));//DEBUG aoqi@0: aoqi@0: // A forward reference is diagnosed if the declaration position aoqi@0: // of the variable is greater than the current tree position aoqi@0: // and the tree and variable definition occur in the same class aoqi@0: // definition. Note that writes don't count as references. aoqi@0: // This check applies only to class and instance aoqi@0: // variables. Local variables follow different scope rules, aoqi@0: // and are subject to definite assignment checking. aoqi@0: if ((env.info.enclVar == v || v.pos > tree.pos) && aoqi@0: v.owner.kind == TYP && mcimadamore@2558: enclosingInitEnv(env) != null && aoqi@0: v.owner == env.info.scope.owner.enclClass() && aoqi@0: ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && aoqi@0: (!env.tree.hasTag(ASSIGN) || aoqi@0: TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { aoqi@0: String suffix = (env.info.enclVar == v) ? aoqi@0: "self.ref" : "forward.ref"; aoqi@0: if (!onlyWarning || isStaticEnumField(v)) { aoqi@0: log.error(tree.pos(), "illegal." + suffix); aoqi@0: } else if (useBeforeDeclarationWarning) { aoqi@0: log.warning(tree.pos(), suffix, v); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: v.getConstValue(); // ensure initializer is evaluated aoqi@0: aoqi@0: checkEnumInitializer(tree, env, v); aoqi@0: } aoqi@0: aoqi@0: /** mcimadamore@2558: * Returns the enclosing init environment associated with this env (if any). An init env mcimadamore@2558: * can be either a field declaration env or a static/instance initializer env. mcimadamore@2558: */ mcimadamore@2558: Env enclosingInitEnv(Env env) { mcimadamore@2558: while (true) { mcimadamore@2558: switch (env.tree.getTag()) { mcimadamore@2558: case VARDEF: mcimadamore@2558: JCVariableDecl vdecl = (JCVariableDecl)env.tree; mcimadamore@2558: if (vdecl.sym.owner.kind == TYP) { mcimadamore@2558: //field mcimadamore@2558: return env; mcimadamore@2558: } mcimadamore@2558: break; mcimadamore@2558: case BLOCK: mcimadamore@2558: if (env.next.tree.hasTag(CLASSDEF)) { mcimadamore@2558: //instance/static initializer mcimadamore@2558: return env; mcimadamore@2558: } mcimadamore@2558: break; mcimadamore@2558: case METHODDEF: mcimadamore@2558: case CLASSDEF: mcimadamore@2558: case TOPLEVEL: mcimadamore@2558: return null; mcimadamore@2558: } mcimadamore@2558: Assert.checkNonNull(env.next); mcimadamore@2558: env = env.next; mcimadamore@2558: } mcimadamore@2558: } mcimadamore@2558: mcimadamore@2558: /** aoqi@0: * Check for illegal references to static members of enum. In aoqi@0: * an enum type, constructors and initializers may not aoqi@0: * reference its static members unless they are constant. aoqi@0: * aoqi@0: * @param tree The tree making up the variable reference. aoqi@0: * @param env The current environment. aoqi@0: * @param v The variable's symbol. aoqi@0: * @jls section 8.9 Enums aoqi@0: */ aoqi@0: private void checkEnumInitializer(JCTree tree, Env env, VarSymbol v) { aoqi@0: // JLS: aoqi@0: // aoqi@0: // "It is a compile-time error to reference a static field aoqi@0: // of an enum type that is not a compile-time constant aoqi@0: // (15.28) from constructors, instance initializer blocks, aoqi@0: // or instance variable initializer expressions of that aoqi@0: // type. It is a compile-time error for the constructors, aoqi@0: // instance initializer blocks, or instance variable aoqi@0: // initializer expressions of an enum constant e to refer aoqi@0: // to itself or to an enum constant of the same type that aoqi@0: // is declared to the right of e." aoqi@0: if (isStaticEnumField(v)) { aoqi@0: ClassSymbol enclClass = env.info.scope.owner.enclClass(); aoqi@0: aoqi@0: if (enclClass == null || enclClass.owner == null) aoqi@0: return; aoqi@0: aoqi@0: // See if the enclosing class is the enum (or a aoqi@0: // subclass thereof) declaring v. If not, this aoqi@0: // reference is OK. aoqi@0: if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) aoqi@0: return; aoqi@0: aoqi@0: // If the reference isn't from an initializer, then aoqi@0: // the reference is OK. aoqi@0: if (!Resolve.isInitializer(env)) aoqi@0: return; aoqi@0: aoqi@0: log.error(tree.pos(), "illegal.enum.static.ref"); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Is the given symbol a static, non-constant field of an Enum? aoqi@0: * Note: enum literals should not be regarded as such aoqi@0: */ aoqi@0: private boolean isStaticEnumField(VarSymbol v) { aoqi@0: return Flags.isEnum(v.owner) && aoqi@0: Flags.isStatic(v) && aoqi@0: !Flags.isConstant(v) && aoqi@0: v.name != names._class; aoqi@0: } aoqi@0: aoqi@0: Warner noteWarner = new Warner(); aoqi@0: aoqi@0: /** aoqi@0: * Check that method arguments conform to its instantiation. aoqi@0: **/ aoqi@0: public Type checkMethod(Type site, aoqi@0: final Symbol sym, aoqi@0: ResultInfo resultInfo, aoqi@0: Env env, aoqi@0: final List argtrees, aoqi@0: List argtypes, aoqi@0: List typeargtypes) { aoqi@0: // Test (5): if symbol is an instance method of a raw type, issue aoqi@0: // an unchecked warning if its argument types change under erasure. aoqi@0: if (allowGenerics && aoqi@0: (sym.flags() & STATIC) == 0 && aoqi@0: (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { aoqi@0: Type s = types.asOuterSuper(site, sym.owner); aoqi@0: if (s != null && s.isRaw() && aoqi@0: !types.isSameTypes(sym.type.getParameterTypes(), aoqi@0: sym.erasure(types).getParameterTypes())) { aoqi@0: chk.warnUnchecked(env.tree.pos(), aoqi@0: "unchecked.call.mbr.of.raw.type", aoqi@0: sym, s); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (env.info.defaultSuperCallSite != null) { aoqi@0: for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { aoqi@0: if (!sup.tsym.isSubClass(sym.enclClass(), types) || aoqi@0: types.isSameType(sup, env.info.defaultSuperCallSite)) continue; aoqi@0: List icand_sup = aoqi@0: types.interfaceCandidates(sup, (MethodSymbol)sym); aoqi@0: if (icand_sup.nonEmpty() && aoqi@0: icand_sup.head != sym && aoqi@0: icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { aoqi@0: log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, aoqi@0: diags.fragment("overridden.default", sym, sup)); aoqi@0: break; aoqi@0: } aoqi@0: } aoqi@0: env.info.defaultSuperCallSite = null; aoqi@0: } aoqi@0: aoqi@0: if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { aoqi@0: JCMethodInvocation app = (JCMethodInvocation)env.tree; aoqi@0: if (app.meth.hasTag(SELECT) && aoqi@0: !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { aoqi@0: log.error(env.tree.pos(), "illegal.static.intf.meth.call", site); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Compute the identifier's instantiated type. aoqi@0: // For methods, we need to compute the instance type by aoqi@0: // Resolve.instantiate from the symbol's type as well as aoqi@0: // any type arguments and value arguments. aoqi@0: noteWarner.clear(); aoqi@0: try { aoqi@0: Type owntype = rs.checkMethod( aoqi@0: env, aoqi@0: site, aoqi@0: sym, aoqi@0: resultInfo, aoqi@0: argtypes, aoqi@0: typeargtypes, aoqi@0: noteWarner); aoqi@0: aoqi@0: DeferredAttr.DeferredTypeMap checkDeferredMap = aoqi@0: deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase); aoqi@0: aoqi@0: argtypes = Type.map(argtypes, checkDeferredMap); aoqi@0: aoqi@0: if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { aoqi@0: chk.warnUnchecked(env.tree.pos(), aoqi@0: "unchecked.meth.invocation.applied", aoqi@0: kindName(sym), aoqi@0: sym.name, aoqi@0: rs.methodArguments(sym.type.getParameterTypes()), aoqi@0: rs.methodArguments(Type.map(argtypes, checkDeferredMap)), aoqi@0: kindName(sym.location()), aoqi@0: sym.location()); aoqi@0: owntype = new MethodType(owntype.getParameterTypes(), aoqi@0: types.erasure(owntype.getReturnType()), aoqi@0: types.erasure(owntype.getThrownTypes()), aoqi@0: syms.methodClass); aoqi@0: } aoqi@0: aoqi@0: return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), aoqi@0: resultInfo.checkContext.inferenceContext()); aoqi@0: } catch (Infer.InferenceException ex) { aoqi@0: //invalid target type - propagate exception outwards or report error aoqi@0: //depending on the current check context aoqi@0: resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); aoqi@0: return types.createErrorType(site); aoqi@0: } catch (Resolve.InapplicableMethodException ex) { aoqi@0: final JCDiagnostic diag = ex.getDiagnostic(); aoqi@0: Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) { aoqi@0: @Override aoqi@0: protected Pair errCandidate() { aoqi@0: return new Pair(sym, diag); aoqi@0: } aoqi@0: }; aoqi@0: List argtypes2 = Type.map(argtypes, aoqi@0: rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); aoqi@0: JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, aoqi@0: env.tree, sym, site, sym.name, argtypes2, typeargtypes); aoqi@0: log.report(errDiag); aoqi@0: return types.createErrorType(site); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitLiteral(JCLiteral tree) { aoqi@0: result = check( aoqi@0: tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo); aoqi@0: } aoqi@0: //where aoqi@0: /** Return the type of a literal with given type tag. aoqi@0: */ aoqi@0: Type litType(TypeTag tag) { aoqi@0: return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; aoqi@0: } aoqi@0: aoqi@0: public void visitTypeIdent(JCPrimitiveTypeTree tree) { aoqi@0: result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitTypeArray(JCArrayTypeTree tree) { aoqi@0: Type etype = attribType(tree.elemtype, env); aoqi@0: Type type = new ArrayType(etype, syms.arrayClass); aoqi@0: result = check(tree, type, TYP, resultInfo); aoqi@0: } aoqi@0: aoqi@0: /** Visitor method for parameterized types. aoqi@0: * Bound checking is left until later, since types are attributed aoqi@0: * before supertype structure is completely known aoqi@0: */ aoqi@0: public void visitTypeApply(JCTypeApply tree) { aoqi@0: Type owntype = types.createErrorType(tree.type); aoqi@0: aoqi@0: // Attribute functor part of application and make sure it's a class. aoqi@0: Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); aoqi@0: aoqi@0: // Attribute type parameters aoqi@0: List actuals = attribTypes(tree.arguments, env); aoqi@0: aoqi@0: if (clazztype.hasTag(CLASS)) { aoqi@0: List formals = clazztype.tsym.type.getTypeArguments(); aoqi@0: if (actuals.isEmpty()) //diamond aoqi@0: actuals = formals; aoqi@0: aoqi@0: if (actuals.length() == formals.length()) { aoqi@0: List a = actuals; aoqi@0: List f = formals; aoqi@0: while (a.nonEmpty()) { aoqi@0: a.head = a.head.withTypeVar(f.head); aoqi@0: a = a.tail; aoqi@0: f = f.tail; aoqi@0: } aoqi@0: // Compute the proper generic outer aoqi@0: Type clazzOuter = clazztype.getEnclosingType(); aoqi@0: if (clazzOuter.hasTag(CLASS)) { aoqi@0: Type site; aoqi@0: JCExpression clazz = TreeInfo.typeIn(tree.clazz); aoqi@0: if (clazz.hasTag(IDENT)) { aoqi@0: site = env.enclClass.sym.type; aoqi@0: } else if (clazz.hasTag(SELECT)) { aoqi@0: site = ((JCFieldAccess) clazz).selected.type; aoqi@0: } else throw new AssertionError(""+tree); aoqi@0: if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { aoqi@0: if (site.hasTag(CLASS)) aoqi@0: site = types.asOuterSuper(site, clazzOuter.tsym); aoqi@0: if (site == null) aoqi@0: site = types.erasure(clazzOuter); aoqi@0: clazzOuter = site; aoqi@0: } aoqi@0: } aoqi@0: owntype = new ClassType(clazzOuter, actuals, clazztype.tsym); aoqi@0: } else { aoqi@0: if (formals.length() != 0) { aoqi@0: log.error(tree.pos(), "wrong.number.type.args", aoqi@0: Integer.toString(formals.length())); aoqi@0: } else { aoqi@0: log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); aoqi@0: } aoqi@0: owntype = types.createErrorType(tree.type); aoqi@0: } aoqi@0: } aoqi@0: result = check(tree, owntype, TYP, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitTypeUnion(JCTypeUnion tree) { aoqi@0: ListBuffer multicatchTypes = new ListBuffer<>(); aoqi@0: ListBuffer all_multicatchTypes = null; // lazy, only if needed aoqi@0: for (JCExpression typeTree : tree.alternatives) { aoqi@0: Type ctype = attribType(typeTree, env); aoqi@0: ctype = chk.checkType(typeTree.pos(), aoqi@0: chk.checkClassType(typeTree.pos(), ctype), aoqi@0: syms.throwableType); aoqi@0: if (!ctype.isErroneous()) { aoqi@0: //check that alternatives of a union type are pairwise aoqi@0: //unrelated w.r.t. subtyping aoqi@0: if (chk.intersects(ctype, multicatchTypes.toList())) { aoqi@0: for (Type t : multicatchTypes) { aoqi@0: boolean sub = types.isSubtype(ctype, t); aoqi@0: boolean sup = types.isSubtype(t, ctype); aoqi@0: if (sub || sup) { aoqi@0: //assume 'a' <: 'b' aoqi@0: Type a = sub ? ctype : t; aoqi@0: Type b = sub ? t : ctype; aoqi@0: log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: multicatchTypes.append(ctype); aoqi@0: if (all_multicatchTypes != null) aoqi@0: all_multicatchTypes.append(ctype); aoqi@0: } else { aoqi@0: if (all_multicatchTypes == null) { aoqi@0: all_multicatchTypes = new ListBuffer<>(); aoqi@0: all_multicatchTypes.appendList(multicatchTypes); aoqi@0: } aoqi@0: all_multicatchTypes.append(ctype); aoqi@0: } aoqi@0: } aoqi@0: Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo); aoqi@0: if (t.hasTag(CLASS)) { aoqi@0: List alternatives = aoqi@0: ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); aoqi@0: t = new UnionClassType((ClassType) t, alternatives); aoqi@0: } aoqi@0: tree.type = result = t; aoqi@0: } aoqi@0: aoqi@0: public void visitTypeIntersection(JCTypeIntersection tree) { aoqi@0: attribTypes(tree.bounds, env); aoqi@0: tree.type = result = checkIntersection(tree, tree.bounds); aoqi@0: } aoqi@0: aoqi@0: public void visitTypeParameter(JCTypeParameter tree) { aoqi@0: TypeVar typeVar = (TypeVar) tree.type; aoqi@0: aoqi@0: if (tree.annotations != null && tree.annotations.nonEmpty()) { aoqi@0: annotateType(tree, tree.annotations); aoqi@0: } aoqi@0: aoqi@0: if (!typeVar.bound.isErroneous()) { aoqi@0: //fixup type-parameter bound computed in 'attribTypeVariables' aoqi@0: typeVar.bound = checkIntersection(tree, tree.bounds); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: Type checkIntersection(JCTree tree, List bounds) { aoqi@0: Set boundSet = new HashSet(); aoqi@0: if (bounds.nonEmpty()) { aoqi@0: // accept class or interface or typevar as first bound. aoqi@0: bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); aoqi@0: boundSet.add(types.erasure(bounds.head.type)); aoqi@0: if (bounds.head.type.isErroneous()) { aoqi@0: return bounds.head.type; aoqi@0: } aoqi@0: else if (bounds.head.type.hasTag(TYPEVAR)) { aoqi@0: // if first bound was a typevar, do not accept further bounds. aoqi@0: if (bounds.tail.nonEmpty()) { aoqi@0: log.error(bounds.tail.head.pos(), aoqi@0: "type.var.may.not.be.followed.by.other.bounds"); aoqi@0: return bounds.head.type; aoqi@0: } aoqi@0: } else { aoqi@0: // if first bound was a class or interface, accept only interfaces aoqi@0: // as further bounds. aoqi@0: for (JCExpression bound : bounds.tail) { aoqi@0: bound.type = checkBase(bound.type, bound, env, false, true, false); aoqi@0: if (bound.type.isErroneous()) { aoqi@0: bounds = List.of(bound); aoqi@0: } aoqi@0: else if (bound.type.hasTag(CLASS)) { aoqi@0: chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (bounds.length() == 0) { aoqi@0: return syms.objectType; aoqi@0: } else if (bounds.length() == 1) { aoqi@0: return bounds.head.type; aoqi@0: } else { aoqi@0: Type owntype = types.makeCompoundType(TreeInfo.types(bounds)); aoqi@0: // ... the variable's bound is a class type flagged COMPOUND aoqi@0: // (see comment for TypeVar.bound). aoqi@0: // In this case, generate a class tree that represents the aoqi@0: // bound class, ... aoqi@0: JCExpression extending; aoqi@0: List implementing; aoqi@0: if (!bounds.head.type.isInterface()) { aoqi@0: extending = bounds.head; aoqi@0: implementing = bounds.tail; aoqi@0: } else { aoqi@0: extending = null; aoqi@0: implementing = bounds; aoqi@0: } aoqi@0: JCClassDecl cd = make.at(tree).ClassDef( aoqi@0: make.Modifiers(PUBLIC | ABSTRACT), aoqi@0: names.empty, List.nil(), aoqi@0: extending, implementing, List.nil()); aoqi@0: aoqi@0: ClassSymbol c = (ClassSymbol)owntype.tsym; aoqi@0: Assert.check((c.flags() & COMPOUND) != 0); aoqi@0: cd.sym = c; aoqi@0: c.sourcefile = env.toplevel.sourcefile; aoqi@0: aoqi@0: // ... and attribute the bound class aoqi@0: c.flags_field |= UNATTRIBUTED; aoqi@0: Env cenv = enter.classEnv(cd, env); aoqi@0: typeEnvs.put(c, cenv); aoqi@0: attribClass(c); aoqi@0: return owntype; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitWildcard(JCWildcard tree) { aoqi@0: //- System.err.println("visitWildcard("+tree+");");//DEBUG aoqi@0: Type type = (tree.kind.kind == BoundKind.UNBOUND) aoqi@0: ? syms.objectType aoqi@0: : attribType(tree.inner, env); aoqi@0: result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), aoqi@0: tree.kind.kind, aoqi@0: syms.boundClass), aoqi@0: TYP, resultInfo); aoqi@0: } aoqi@0: aoqi@0: public void visitAnnotation(JCAnnotation tree) { aoqi@0: Assert.error("should be handled in Annotate"); aoqi@0: } aoqi@0: aoqi@0: public void visitAnnotatedType(JCAnnotatedType tree) { aoqi@0: Type underlyingType = attribType(tree.getUnderlyingType(), env); aoqi@0: this.attribAnnotationTypes(tree.annotations, env); aoqi@0: annotateType(tree, tree.annotations); aoqi@0: result = tree.type = underlyingType; aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Apply the annotations to the particular type. aoqi@0: */ aoqi@0: public void annotateType(final JCTree tree, final List annotations) { aoqi@0: annotate.typeAnnotation(new Annotate.Worker() { aoqi@0: @Override aoqi@0: public String toString() { aoqi@0: return "annotate " + annotations + " onto " + tree; aoqi@0: } aoqi@0: @Override aoqi@0: public void run() { aoqi@0: List compounds = fromAnnotations(annotations); aoqi@0: if (annotations.size() == compounds.size()) { aoqi@0: // All annotations were successfully converted into compounds aoqi@0: tree.type = tree.type.unannotatedType().annotatedType(compounds); aoqi@0: } aoqi@0: } aoqi@0: }); aoqi@0: } aoqi@0: aoqi@0: private static List fromAnnotations(List annotations) { aoqi@0: if (annotations.isEmpty()) { aoqi@0: return List.nil(); aoqi@0: } aoqi@0: aoqi@0: ListBuffer buf = new ListBuffer<>(); aoqi@0: for (JCAnnotation anno : annotations) { aoqi@0: if (anno.attribute != null) { aoqi@0: // TODO: this null-check is only needed for an obscure aoqi@0: // ordering issue, where annotate.flush is called when aoqi@0: // the attribute is not set yet. For an example failure aoqi@0: // try the referenceinfos/NestedTypes.java test. aoqi@0: // Any better solutions? aoqi@0: buf.append((Attribute.TypeCompound) anno.attribute); aoqi@0: } aoqi@0: // Eventually we will want to throw an exception here, but aoqi@0: // we can't do that just yet, because it gets triggered aoqi@0: // when attempting to attach an annotation that isn't aoqi@0: // defined. aoqi@0: } aoqi@0: return buf.toList(); aoqi@0: } aoqi@0: aoqi@0: public void visitErroneous(JCErroneous tree) { aoqi@0: if (tree.errs != null) aoqi@0: for (JCTree err : tree.errs) aoqi@0: attribTree(err, env, new ResultInfo(ERR, pt())); aoqi@0: result = tree.type = syms.errType; aoqi@0: } aoqi@0: aoqi@0: /** Default visitor method for all other trees. aoqi@0: */ aoqi@0: public void visitTree(JCTree tree) { aoqi@0: throw new AssertionError(); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Attribute an env for either a top level tree or class declaration. aoqi@0: */ aoqi@0: public void attrib(Env env) { aoqi@0: if (env.tree.hasTag(TOPLEVEL)) aoqi@0: attribTopLevel(env); aoqi@0: else aoqi@0: attribClass(env.tree.pos(), env.enclClass.sym); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Attribute a top level tree. These trees are encountered when the aoqi@0: * package declaration has annotations. aoqi@0: */ aoqi@0: public void attribTopLevel(Env env) { aoqi@0: JCCompilationUnit toplevel = env.toplevel; aoqi@0: try { aoqi@0: annotate.flush(); aoqi@0: } catch (CompletionFailure ex) { aoqi@0: chk.completionError(toplevel.pos(), ex); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Main method: attribute class definition associated with given class symbol. aoqi@0: * reporting completion failures at the given position. aoqi@0: * @param pos The source position at which completion errors are to be aoqi@0: * reported. aoqi@0: * @param c The class symbol whose definition will be attributed. aoqi@0: */ aoqi@0: public void attribClass(DiagnosticPosition pos, ClassSymbol c) { aoqi@0: try { aoqi@0: annotate.flush(); aoqi@0: attribClass(c); aoqi@0: } catch (CompletionFailure ex) { aoqi@0: chk.completionError(pos, ex); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /** Attribute class definition associated with given class symbol. aoqi@0: * @param c The class symbol whose definition will be attributed. aoqi@0: */ aoqi@0: void attribClass(ClassSymbol c) throws CompletionFailure { aoqi@0: if (c.type.hasTag(ERROR)) return; aoqi@0: aoqi@0: // Check for cycles in the inheritance graph, which can arise from aoqi@0: // ill-formed class files. aoqi@0: chk.checkNonCyclic(null, c.type); aoqi@0: aoqi@0: Type st = types.supertype(c.type); aoqi@0: if ((c.flags_field & Flags.COMPOUND) == 0) { aoqi@0: // First, attribute superclass. aoqi@0: if (st.hasTag(CLASS)) aoqi@0: attribClass((ClassSymbol)st.tsym); aoqi@0: aoqi@0: // Next attribute owner, if it is a class. aoqi@0: if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) aoqi@0: attribClass((ClassSymbol)c.owner); aoqi@0: } aoqi@0: aoqi@0: // The previous operations might have attributed the current class aoqi@0: // if there was a cycle. So we test first whether the class is still aoqi@0: // UNATTRIBUTED. aoqi@0: if ((c.flags_field & UNATTRIBUTED) != 0) { aoqi@0: c.flags_field &= ~UNATTRIBUTED; aoqi@0: aoqi@0: // Get environment current at the point of class definition. aoqi@0: Env env = typeEnvs.get(c); aoqi@0: aoqi@0: // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized, aoqi@0: // because the annotations were not available at the time the env was created. Therefore, aoqi@0: // we look up the environment chain for the first enclosing environment for which the aoqi@0: // lint value is set. Typically, this is the parent env, but might be further if there aoqi@0: // are any envs created as a result of TypeParameter nodes. aoqi@0: Env lintEnv = env; aoqi@0: while (lintEnv.info.lint == null) aoqi@0: lintEnv = lintEnv.next; aoqi@0: aoqi@0: // Having found the enclosing lint value, we can initialize the lint value for this class aoqi@0: env.info.lint = lintEnv.info.lint.augment(c); aoqi@0: aoqi@0: Lint prevLint = chk.setLint(env.info.lint); aoqi@0: JavaFileObject prev = log.useSource(c.sourcefile); aoqi@0: ResultInfo prevReturnRes = env.info.returnResult; aoqi@0: aoqi@0: try { aoqi@0: deferredLintHandler.flush(env.tree); aoqi@0: env.info.returnResult = null; aoqi@0: // java.lang.Enum may not be subclassed by a non-enum aoqi@0: if (st.tsym == syms.enumSym && aoqi@0: ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) aoqi@0: log.error(env.tree.pos(), "enum.no.subclassing"); aoqi@0: aoqi@0: // Enums may not be extended by source-level classes aoqi@0: if (st.tsym != null && aoqi@0: ((st.tsym.flags_field & Flags.ENUM) != 0) && aoqi@0: ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { aoqi@0: log.error(env.tree.pos(), "enum.types.not.extensible"); aoqi@0: } aoqi@0: aoqi@0: if (isSerializable(c.type)) { aoqi@0: env.info.isSerializable = true; aoqi@0: } aoqi@0: aoqi@0: attribClassBody(env, c); aoqi@0: aoqi@0: chk.checkDeprecatedAnnotation(env.tree.pos(), c); aoqi@0: chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); aoqi@0: chk.checkFunctionalInterface((JCClassDecl) env.tree, c); aoqi@0: } finally { aoqi@0: env.info.returnResult = prevReturnRes; aoqi@0: log.useSource(prev); aoqi@0: chk.setLint(prevLint); aoqi@0: } aoqi@0: aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public void visitImport(JCImport tree) { aoqi@0: // nothing to do aoqi@0: } aoqi@0: aoqi@0: /** Finish the attribution of a class. */ aoqi@0: private void attribClassBody(Env env, ClassSymbol c) { aoqi@0: JCClassDecl tree = (JCClassDecl)env.tree; aoqi@0: Assert.check(c == tree.sym); aoqi@0: aoqi@0: // Validate type parameters, supertype and interfaces. aoqi@0: attribStats(tree.typarams, env); aoqi@0: if (!c.isAnonymous()) { aoqi@0: //already checked if anonymous aoqi@0: chk.validate(tree.typarams, env); aoqi@0: chk.validate(tree.extending, env); aoqi@0: chk.validate(tree.implementing, env); aoqi@0: } aoqi@0: aoqi@0: // If this is a non-abstract class, check that it has no abstract aoqi@0: // methods or unimplemented methods of an implemented interface. aoqi@0: if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { aoqi@0: if (!relax) aoqi@0: chk.checkAllDefined(tree.pos(), c); aoqi@0: } aoqi@0: aoqi@0: if ((c.flags() & ANNOTATION) != 0) { aoqi@0: if (tree.implementing.nonEmpty()) aoqi@0: log.error(tree.implementing.head.pos(), aoqi@0: "cant.extend.intf.annotation"); aoqi@0: if (tree.typarams.nonEmpty()) aoqi@0: log.error(tree.typarams.head.pos(), aoqi@0: "intf.annotation.cant.have.type.params"); aoqi@0: aoqi@0: // If this annotation has a @Repeatable, validate aoqi@0: Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym); aoqi@0: if (repeatable != null) { aoqi@0: // get diagnostic position for error reporting aoqi@0: DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); aoqi@0: Assert.checkNonNull(cbPos); aoqi@0: aoqi@0: chk.validateRepeatable(c, repeatable, cbPos); aoqi@0: } aoqi@0: } else { aoqi@0: // Check that all extended classes and interfaces aoqi@0: // are compatible (i.e. no two define methods with same arguments aoqi@0: // yet different return types). (JLS 8.4.6.3) aoqi@0: chk.checkCompatibleSupertypes(tree.pos(), c.type); aoqi@0: if (allowDefaultMethods) { aoqi@0: chk.checkDefaultMethodClashes(tree.pos(), c.type); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Check that class does not import the same parameterized interface aoqi@0: // with two different argument lists. aoqi@0: chk.checkClassBounds(tree.pos(), c.type); aoqi@0: aoqi@0: tree.type = c.type; aoqi@0: aoqi@0: for (List l = tree.typarams; aoqi@0: l.nonEmpty(); l = l.tail) { aoqi@0: Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope); aoqi@0: } aoqi@0: aoqi@0: // Check that a generic class doesn't extend Throwable aoqi@0: if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) aoqi@0: log.error(tree.extending.pos(), "generic.throwable"); aoqi@0: aoqi@0: // Check that all methods which implement some aoqi@0: // method conform to the method they implement. aoqi@0: chk.checkImplementations(tree); aoqi@0: aoqi@0: //check that a resource implementing AutoCloseable cannot throw InterruptedException aoqi@0: checkAutoCloseable(tree.pos(), env, c.type); aoqi@0: aoqi@0: for (List l = tree.defs; l.nonEmpty(); l = l.tail) { aoqi@0: // Attribute declaration aoqi@0: attribStat(l.head, env); aoqi@0: // Check that declarations in inner classes are not static (JLS 8.1.2) aoqi@0: // Make an exception for static constants. aoqi@0: if (c.owner.kind != PCK && aoqi@0: ((c.flags() & STATIC) == 0 || c.name == names.empty) && aoqi@0: (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { aoqi@0: Symbol sym = null; aoqi@0: if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; aoqi@0: if (sym == null || aoqi@0: sym.kind != VAR || aoqi@0: ((VarSymbol) sym).getConstValue() == null) aoqi@0: log.error(l.head.pos(), "icls.cant.have.static.decl", c); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Check for cycles among non-initial constructors. aoqi@0: chk.checkCyclicConstructors(tree); aoqi@0: aoqi@0: // Check for cycles among annotation elements. aoqi@0: chk.checkNonCyclicElements(tree); aoqi@0: aoqi@0: // Check for proper use of serialVersionUID aoqi@0: if (env.info.lint.isEnabled(LintCategory.SERIAL) && aoqi@0: isSerializable(c.type) && aoqi@0: (c.flags() & Flags.ENUM) == 0 && aoqi@0: checkForSerial(c)) { aoqi@0: checkSerialVersionUID(tree, c); aoqi@0: } aoqi@0: if (allowTypeAnnos) { aoqi@0: // Correctly organize the postions of the type annotations aoqi@0: typeAnnotations.organizeTypeAnnotationsBodies(tree); aoqi@0: aoqi@0: // Check type annotations applicability rules aoqi@0: validateTypeAnnotations(tree, false); aoqi@0: } aoqi@0: } aoqi@0: // where aoqi@0: boolean checkForSerial(ClassSymbol c) { aoqi@0: if ((c.flags() & ABSTRACT) == 0) { aoqi@0: return true; aoqi@0: } else { aoqi@0: return c.members().anyMatch(anyNonAbstractOrDefaultMethod); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: public static final Filter anyNonAbstractOrDefaultMethod = new Filter() { aoqi@0: @Override aoqi@0: public boolean accepts(Symbol s) { aoqi@0: return s.kind == Kinds.MTH && aoqi@0: (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT; aoqi@0: } aoqi@0: }; aoqi@0: aoqi@0: /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ aoqi@0: private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { aoqi@0: for(List al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { aoqi@0: if (types.isSameType(al.head.annotationType.type, t)) aoqi@0: return al.head.pos(); aoqi@0: } aoqi@0: aoqi@0: return null; aoqi@0: } aoqi@0: aoqi@0: /** check if a type is a subtype of Serializable, if that is available. */ aoqi@0: boolean isSerializable(Type t) { aoqi@0: try { aoqi@0: syms.serializableType.complete(); aoqi@0: } aoqi@0: catch (CompletionFailure e) { aoqi@0: return false; aoqi@0: } aoqi@0: return types.isSubtype(t, syms.serializableType); aoqi@0: } aoqi@0: aoqi@0: /** Check that an appropriate serialVersionUID member is defined. */ aoqi@0: private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { aoqi@0: aoqi@0: // check for presence of serialVersionUID aoqi@0: Scope.Entry e = c.members().lookup(names.serialVersionUID); aoqi@0: while (e.scope != null && e.sym.kind != VAR) e = e.next(); aoqi@0: if (e.scope == null) { aoqi@0: log.warning(LintCategory.SERIAL, aoqi@0: tree.pos(), "missing.SVUID", c); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // check that it is static final aoqi@0: VarSymbol svuid = (VarSymbol)e.sym; aoqi@0: if ((svuid.flags() & (STATIC | FINAL)) != aoqi@0: (STATIC | FINAL)) aoqi@0: log.warning(LintCategory.SERIAL, aoqi@0: TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); aoqi@0: aoqi@0: // check that it is long aoqi@0: else if (!svuid.type.hasTag(LONG)) aoqi@0: log.warning(LintCategory.SERIAL, aoqi@0: TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); aoqi@0: aoqi@0: // check constant aoqi@0: else if (svuid.getConstValue() == null) aoqi@0: log.warning(LintCategory.SERIAL, aoqi@0: TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); aoqi@0: } aoqi@0: aoqi@0: private Type capture(Type type) { aoqi@0: return types.capture(type); aoqi@0: } aoqi@0: aoqi@0: public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { aoqi@0: tree.accept(new TypeAnnotationsValidator(sigOnly)); aoqi@0: } aoqi@0: //where aoqi@0: private final class TypeAnnotationsValidator extends TreeScanner { aoqi@0: aoqi@0: private final boolean sigOnly; aoqi@0: public TypeAnnotationsValidator(boolean sigOnly) { aoqi@0: this.sigOnly = sigOnly; aoqi@0: } aoqi@0: aoqi@0: public void visitAnnotation(JCAnnotation tree) { aoqi@0: chk.validateTypeAnnotation(tree, false); aoqi@0: super.visitAnnotation(tree); aoqi@0: } aoqi@0: public void visitAnnotatedType(JCAnnotatedType tree) { aoqi@0: if (!tree.underlyingType.type.isErroneous()) { aoqi@0: super.visitAnnotatedType(tree); aoqi@0: } aoqi@0: } aoqi@0: public void visitTypeParameter(JCTypeParameter tree) { aoqi@0: chk.validateTypeAnnotations(tree.annotations, true); aoqi@0: scan(tree.bounds); aoqi@0: // Don't call super. aoqi@0: // This is needed because above we call validateTypeAnnotation with aoqi@0: // false, which would forbid annotations on type parameters. aoqi@0: // super.visitTypeParameter(tree); aoqi@0: } aoqi@0: public void visitMethodDef(JCMethodDecl tree) { aoqi@0: if (tree.recvparam != null && aoqi@0: !tree.recvparam.vartype.type.isErroneous()) { aoqi@0: checkForDeclarationAnnotations(tree.recvparam.mods.annotations, aoqi@0: tree.recvparam.vartype.type.tsym); aoqi@0: } aoqi@0: if (tree.restype != null && tree.restype.type != null) { aoqi@0: validateAnnotatedType(tree.restype, tree.restype.type); aoqi@0: } aoqi@0: if (sigOnly) { aoqi@0: scan(tree.mods); aoqi@0: scan(tree.restype); aoqi@0: scan(tree.typarams); aoqi@0: scan(tree.recvparam); aoqi@0: scan(tree.params); aoqi@0: scan(tree.thrown); aoqi@0: } else { aoqi@0: scan(tree.defaultValue); aoqi@0: scan(tree.body); aoqi@0: } aoqi@0: } aoqi@0: public void visitVarDef(final JCVariableDecl tree) { aoqi@0: if (tree.sym != null && tree.sym.type != null) aoqi@0: validateAnnotatedType(tree.vartype, tree.sym.type); aoqi@0: scan(tree.mods); aoqi@0: scan(tree.vartype); aoqi@0: if (!sigOnly) { aoqi@0: scan(tree.init); aoqi@0: } aoqi@0: } aoqi@0: public void visitTypeCast(JCTypeCast tree) { aoqi@0: if (tree.clazz != null && tree.clazz.type != null) aoqi@0: validateAnnotatedType(tree.clazz, tree.clazz.type); aoqi@0: super.visitTypeCast(tree); aoqi@0: } aoqi@0: public void visitTypeTest(JCInstanceOf tree) { aoqi@0: if (tree.clazz != null && tree.clazz.type != null) aoqi@0: validateAnnotatedType(tree.clazz, tree.clazz.type); aoqi@0: super.visitTypeTest(tree); aoqi@0: } aoqi@0: public void visitNewClass(JCNewClass tree) { jfranck@2615: if (tree.clazz != null && tree.clazz.type != null) { jfranck@2615: if (tree.clazz.hasTag(ANNOTATED_TYPE)) { jfranck@2615: checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations, jfranck@2615: tree.clazz.type.tsym); jfranck@2615: } jfranck@2615: if (tree.def != null) { jfranck@2615: checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym); jfranck@2615: } jfranck@2615: aoqi@0: validateAnnotatedType(tree.clazz, tree.clazz.type); aoqi@0: } aoqi@0: super.visitNewClass(tree); aoqi@0: } aoqi@0: public void visitNewArray(JCNewArray tree) { aoqi@0: if (tree.elemtype != null && tree.elemtype.type != null) { aoqi@0: if (tree.elemtype.hasTag(ANNOTATED_TYPE)) { aoqi@0: checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations, aoqi@0: tree.elemtype.type.tsym); aoqi@0: } aoqi@0: validateAnnotatedType(tree.elemtype, tree.elemtype.type); aoqi@0: } aoqi@0: super.visitNewArray(tree); aoqi@0: } aoqi@0: public void visitClassDef(JCClassDecl tree) { aoqi@0: if (sigOnly) { aoqi@0: scan(tree.mods); aoqi@0: scan(tree.typarams); aoqi@0: scan(tree.extending); aoqi@0: scan(tree.implementing); aoqi@0: } aoqi@0: for (JCTree member : tree.defs) { aoqi@0: if (member.hasTag(Tag.CLASSDEF)) { aoqi@0: continue; aoqi@0: } aoqi@0: scan(member); aoqi@0: } aoqi@0: } aoqi@0: public void visitBlock(JCBlock tree) { aoqi@0: if (!sigOnly) { aoqi@0: scan(tree.stats); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /* I would want to model this after aoqi@0: * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) aoqi@0: * and override visitSelect and visitTypeApply. aoqi@0: * However, we only set the annotated type in the top-level type aoqi@0: * of the symbol. aoqi@0: * Therefore, we need to override each individual location where a type aoqi@0: * can occur. aoqi@0: */ aoqi@0: private void validateAnnotatedType(final JCTree errtree, final Type type) { aoqi@0: // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type); aoqi@0: aoqi@0: if (type.isPrimitiveOrVoid()) { aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: JCTree enclTr = errtree; aoqi@0: Type enclTy = type; aoqi@0: aoqi@0: boolean repeat = true; aoqi@0: while (repeat) { aoqi@0: if (enclTr.hasTag(TYPEAPPLY)) { aoqi@0: List tyargs = enclTy.getTypeArguments(); aoqi@0: List trargs = ((JCTypeApply)enclTr).getTypeArguments(); aoqi@0: if (trargs.length() > 0) { aoqi@0: // Nothing to do for diamonds aoqi@0: if (tyargs.length() == trargs.length()) { aoqi@0: for (int i = 0; i < tyargs.length(); ++i) { aoqi@0: validateAnnotatedType(trargs.get(i), tyargs.get(i)); aoqi@0: } aoqi@0: } aoqi@0: // If the lengths don't match, it's either a diamond aoqi@0: // or some nested type that redundantly provides aoqi@0: // type arguments in the tree. aoqi@0: } aoqi@0: aoqi@0: // Look at the clazz part of a generic type aoqi@0: enclTr = ((JCTree.JCTypeApply)enclTr).clazz; aoqi@0: } aoqi@0: aoqi@0: if (enclTr.hasTag(SELECT)) { aoqi@0: enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression(); aoqi@0: if (enclTy != null && aoqi@0: !enclTy.hasTag(NONE)) { aoqi@0: enclTy = enclTy.getEnclosingType(); aoqi@0: } aoqi@0: } else if (enclTr.hasTag(ANNOTATED_TYPE)) { aoqi@0: JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; aoqi@0: if (enclTy == null || aoqi@0: enclTy.hasTag(NONE)) { aoqi@0: if (at.getAnnotations().size() == 1) { aoqi@0: log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute); aoqi@0: } else { aoqi@0: ListBuffer comps = new ListBuffer(); aoqi@0: for (JCAnnotation an : at.getAnnotations()) { aoqi@0: comps.add(an.attribute); aoqi@0: } aoqi@0: log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList()); aoqi@0: } aoqi@0: repeat = false; aoqi@0: } aoqi@0: enclTr = at.underlyingType; aoqi@0: // enclTy doesn't need to be changed aoqi@0: } else if (enclTr.hasTag(IDENT)) { aoqi@0: repeat = false; aoqi@0: } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) { aoqi@0: JCWildcard wc = (JCWildcard) enclTr; aoqi@0: if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) { aoqi@0: validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound()); aoqi@0: } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) { aoqi@0: validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound()); aoqi@0: } else { aoqi@0: // Nothing to do for UNBOUND aoqi@0: } aoqi@0: repeat = false; aoqi@0: } else if (enclTr.hasTag(TYPEARRAY)) { aoqi@0: JCArrayTypeTree art = (JCArrayTypeTree) enclTr; aoqi@0: validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType()); aoqi@0: repeat = false; aoqi@0: } else if (enclTr.hasTag(TYPEUNION)) { aoqi@0: JCTypeUnion ut = (JCTypeUnion) enclTr; aoqi@0: for (JCTree t : ut.getTypeAlternatives()) { aoqi@0: validateAnnotatedType(t, t.type); aoqi@0: } aoqi@0: repeat = false; aoqi@0: } else if (enclTr.hasTag(TYPEINTERSECTION)) { aoqi@0: JCTypeIntersection it = (JCTypeIntersection) enclTr; aoqi@0: for (JCTree t : it.getBounds()) { aoqi@0: validateAnnotatedType(t, t.type); aoqi@0: } aoqi@0: repeat = false; aoqi@0: } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE || aoqi@0: enclTr.getKind() == JCTree.Kind.ERRONEOUS) { aoqi@0: repeat = false; aoqi@0: } else { aoqi@0: Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() + aoqi@0: " within: "+ errtree + " with kind: " + errtree.getKind()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: private void checkForDeclarationAnnotations(List annotations, aoqi@0: Symbol sym) { aoqi@0: // Ensure that no declaration annotations are present. aoqi@0: // Note that a tree type might be an AnnotatedType with aoqi@0: // empty annotations, if only declaration annotations were given. aoqi@0: // This method will raise an error for such a type. aoqi@0: for (JCAnnotation ai : annotations) { aoqi@0: if (!ai.type.isErroneous() && aoqi@0: typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) { aoqi@0: log.error(ai.pos(), "annotation.type.not.applicable"); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: }; aoqi@0: aoqi@0: // aoqi@0: aoqi@0: /** aoqi@0: * Handle missing types/symbols in an AST. This routine is useful when aoqi@0: * the compiler has encountered some errors (which might have ended up aoqi@0: * terminating attribution abruptly); if the compiler is used in fail-over aoqi@0: * mode (e.g. by an IDE) and the AST contains semantic errors, this routine aoqi@0: * prevents NPE to be progagated during subsequent compilation steps. aoqi@0: */ aoqi@0: public void postAttr(JCTree tree) { aoqi@0: new PostAttrAnalyzer().scan(tree); aoqi@0: } aoqi@0: aoqi@0: class PostAttrAnalyzer extends TreeScanner { aoqi@0: aoqi@0: private void initTypeIfNeeded(JCTree that) { aoqi@0: if (that.type == null) { aoqi@0: if (that.hasTag(METHODDEF)) { aoqi@0: that.type = dummyMethodType((JCMethodDecl)that); aoqi@0: } else { aoqi@0: that.type = syms.unknownType; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: /* Construct a dummy method type. If we have a method declaration, aoqi@0: * and the declared return type is void, then use that return type aoqi@0: * instead of UNKNOWN to avoid spurious error messages in lambda aoqi@0: * bodies (see:JDK-8041704). aoqi@0: */ aoqi@0: private Type dummyMethodType(JCMethodDecl md) { aoqi@0: Type restype = syms.unknownType; aoqi@0: if (md != null && md.restype.hasTag(TYPEIDENT)) { aoqi@0: JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; aoqi@0: if (prim.typetag == VOID) aoqi@0: restype = syms.voidType; aoqi@0: } aoqi@0: return new MethodType(List.nil(), restype, aoqi@0: List.nil(), syms.methodClass); aoqi@0: } aoqi@0: private Type dummyMethodType() { aoqi@0: return dummyMethodType(null); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void scan(JCTree tree) { aoqi@0: if (tree == null) return; aoqi@0: if (tree instanceof JCExpression) { aoqi@0: initTypeIfNeeded(tree); aoqi@0: } aoqi@0: super.scan(tree); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitIdent(JCIdent that) { aoqi@0: if (that.sym == null) { aoqi@0: that.sym = syms.unknownSymbol; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitSelect(JCFieldAccess that) { aoqi@0: if (that.sym == null) { aoqi@0: that.sym = syms.unknownSymbol; aoqi@0: } aoqi@0: super.visitSelect(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitClassDef(JCClassDecl that) { aoqi@0: initTypeIfNeeded(that); aoqi@0: if (that.sym == null) { aoqi@0: that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); aoqi@0: } aoqi@0: super.visitClassDef(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitMethodDef(JCMethodDecl that) { aoqi@0: initTypeIfNeeded(that); aoqi@0: if (that.sym == null) { aoqi@0: that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); aoqi@0: } aoqi@0: super.visitMethodDef(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitVarDef(JCVariableDecl that) { aoqi@0: initTypeIfNeeded(that); aoqi@0: if (that.sym == null) { aoqi@0: that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); aoqi@0: that.sym.adr = 0; aoqi@0: } aoqi@0: super.visitVarDef(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitNewClass(JCNewClass that) { aoqi@0: if (that.constructor == null) { aoqi@0: that.constructor = new MethodSymbol(0, names.init, aoqi@0: dummyMethodType(), syms.noSymbol); aoqi@0: } aoqi@0: if (that.constructorType == null) { aoqi@0: that.constructorType = syms.unknownType; aoqi@0: } aoqi@0: super.visitNewClass(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitAssignop(JCAssignOp that) { aoqi@0: if (that.operator == null) { aoqi@0: that.operator = new OperatorSymbol(names.empty, dummyMethodType(), aoqi@0: -1, syms.noSymbol); aoqi@0: } aoqi@0: super.visitAssignop(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitBinary(JCBinary that) { aoqi@0: if (that.operator == null) { aoqi@0: that.operator = new OperatorSymbol(names.empty, dummyMethodType(), aoqi@0: -1, syms.noSymbol); aoqi@0: } aoqi@0: super.visitBinary(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitUnary(JCUnary that) { aoqi@0: if (that.operator == null) { aoqi@0: that.operator = new OperatorSymbol(names.empty, dummyMethodType(), aoqi@0: -1, syms.noSymbol); aoqi@0: } aoqi@0: super.visitUnary(that); aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitLambda(JCLambda that) { aoqi@0: super.visitLambda(that); aoqi@0: if (that.targets == null) { aoqi@0: that.targets = List.nil(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: @Override aoqi@0: public void visitReference(JCMemberReference that) { aoqi@0: super.visitReference(that); aoqi@0: if (that.sym == null) { aoqi@0: that.sym = new MethodSymbol(0, names.empty, dummyMethodType(), aoqi@0: syms.noSymbol); aoqi@0: } aoqi@0: if (that.targets == null) { aoqi@0: that.targets = List.nil(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: // aoqi@0: }