package com.sun.tools.javac.comp;
import com.sun.source.tree.LambdaExpressionTree.BodyKind;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
import com.sun.tools.javac.comp.Attr.ResultInfo;
import com.sun.tools.javac.comp.Attr.TargetInfo;
import com.sun.tools.javac.comp.Check.CheckContext;
import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
import com.sun.tools.javac.comp.DeferredAttr.DeferredTypeCompleter;
import com.sun.tools.javac.comp.DeferredAttr.LambdaReturnScanner;
import com.sun.tools.javac.comp.Infer.PartiallyInferredMethodType;
import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLambda.ParameterKind;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.TreeCopier;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.util.Assert;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DiagnosticSource;
import com.sun.tools.javac.util.JCDiagnostic;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import static com.sun.tools.javac.code.TypeTag.ARRAY;
import static com.sun.tools.javac.code.TypeTag.DEFERRED;
import static com.sun.tools.javac.code.TypeTag.FORALL;
import static com.sun.tools.javac.code.TypeTag.METHOD;
import static com.sun.tools.javac.code.TypeTag.VOID;
public class ArgumentAttr extends JCTree.Visitor {
protected static final Context.Key<ArgumentAttr> methodAttrKey = new Context.Key<>();
private final DeferredAttr deferredAttr;
private final JCDiagnostic.Factory diags;
private final Attr attr;
private final Symtab syms;
private final Log log;
private Env<AttrContext> env;
Type result;
Map<UniquePos, ArgumentType<?>> argumentTypeCache = new LinkedHashMap<>();
public static ArgumentAttr instance(Context context) {
ArgumentAttr instance = context.get(methodAttrKey);
if (instance == null)
instance = new ArgumentAttr(context);
return instance;
}
protected ArgumentAttr(Context context) {
context.put(methodAttrKey, this);
deferredAttr = DeferredAttr.instance(context);
diags = JCDiagnostic.Factory.instance(context);
attr = Attr.instance(context);
syms = Symtab.instance(context);
log = Log.instance(context);
}
void setResult(JCExpression tree, Type type) {
result = type;
if (env.info.isSpeculative) {
tree.type = result;
}
}
Type checkSpeculative(JCExpression expr, ResultInfo resultInfo) {
return checkSpeculative(expr, expr.type, resultInfo);
}
Type checkSpeculative(DiagnosticPosition pos, Type t, ResultInfo resultInfo) {
if (t.hasTag(DEFERRED)) {
return ((DeferredType)t).check(resultInfo);
} else {
return resultInfo.check(pos, t);
}
}
LocalCacheContext withLocalCacheContext() {
return new LocalCacheContext();
}
class LocalCacheContext {
Map<UniquePos, ArgumentType<?>> prevCache;
public LocalCacheContext() {
this.prevCache = argumentTypeCache;
argumentTypeCache = new HashMap<>();
}
public void leave() {
argumentTypeCache = prevCache;
}
}
Type attribArg(JCTree tree, Env<AttrContext> env) {
Env<AttrContext> prevEnv = this.env;
try {
this.env = env;
tree.accept(this);
return result;
} finally {
this.env = prevEnv;
}
}
@Override
public void visitTree(JCTree that) {
that.accept(attr);
result = attr.result;
}
@SuppressWarnings("unchecked")
<T extends JCExpression, Z extends ArgumentType<T>> void processArg(T that, Function<T, Z> argumentTypeFactory) {
UniquePos pos = new UniquePos(that);
processArg(that, () -> {
T speculativeTree = (T)deferredAttr.attribSpeculative(that, env, attr.new MethodAttrInfo() {
@Override
protected boolean needsArgumentAttr(JCTree tree) {
return !new UniquePos(tree).equals(pos);
}
});
return argumentTypeFactory.apply(speculativeTree);
});
}
@SuppressWarnings("unchecked")
<T extends JCExpression, Z extends ArgumentType<T>> void processArg(T that, Supplier<Z> argumentTypeFactory) {
UniquePos pos = new UniquePos(that);
Z cached = (Z)argumentTypeCache.get(pos);
if (cached != null) {
setResult(that, cached.dup(that, env));
} else {
Z res = argumentTypeFactory.get();
argumentTypeCache.put(pos, res);
setResult(that, res);
}
}
@Override
public void visitParens(JCParens that) {
processArg(that, speculativeTree -> new ParensType(that, env, speculativeTree));
}
@Override
public void visitConditional(JCConditional that) {
processArg(that, speculativeTree -> new ConditionalType(that, env, speculativeTree));
}
@Override
public void visitReference(JCMemberReference tree) {
Env<AttrContext> localEnv = env.dup(tree);
JCExpression exprTree;
exprTree = (JCExpression)deferredAttr.attribSpeculative(tree.getQualifierExpression(), localEnv,
attr.memberReferenceQualifierResult(tree),
withLocalCacheContext());
JCMemberReference mref2 = new TreeCopier<Void>(attr.make).copy(tree);
mref2.expr = exprTree;
Symbol lhsSym = TreeInfo.symbol(exprTree);
localEnv.info.selectSuper = lhsSym != null && lhsSym.name == lhsSym.name.table.names._super;
Symbol res =
attr.rs.getMemberReference(tree, localEnv, mref2,
exprTree.type, tree.name);
if (!res.kind.isResolutionError()) {
tree.sym = res;
}
if (res.kind.isResolutionTargetError()) {
tree.setOverloadKind(JCMemberReference.OverloadKind.ERROR);
} else if (res.type != null && res.type.hasTag(FORALL) ||
(res.flags() & Flags.VARARGS) != 0 ||
(TreeInfo.isStaticSelector(exprTree, tree.name.table.names) &&
exprTree.type.isRaw() && !exprTree.type.hasTag(ARRAY))) {
tree.setOverloadKind(JCMemberReference.OverloadKind.OVERLOADED);
} else {
tree.setOverloadKind(JCMemberReference.OverloadKind.UNOVERLOADED);
}
setResult(tree, deferredAttr.new DeferredType(tree, env));
}
@Override
public void visitLambda(JCLambda that) {
if (that.paramKind == ParameterKind.EXPLICIT) {
processArg(that, () -> {
JCLambda speculativeLambda =
deferredAttr.attribSpeculativeLambda(that, env, attr.methodAttrInfo);
return new ExplicitLambdaType(that, env, speculativeLambda);
});
} else {
setResult(that, deferredAttr.new DeferredType(that, env));
}
}
@Override
public void visitApply(JCMethodInvocation that) {
if (that.getTypeArguments().isEmpty()) {
processArg(that, speculativeTree -> new ResolvedMethodType(that, env, speculativeTree));
} else {
setResult(that, attr.attribTree(that, env, attr.unknownExprInfo));
}
}
@Override
public void visitNewClass(JCNewClass that) {
if (TreeInfo.isDiamond(that)) {
processArg(that, speculativeTree -> new ResolvedConstructorType(that, env, speculativeTree));
} else {
setResult(that, attr.attribTree(that, env, attr.unknownExprInfo));
}
}
abstract class ArgumentType<T extends JCExpression> extends DeferredType implements DeferredTypeCompleter {
T speculativeTree;
Map<ResultInfo, Type> speculativeTypes;
public ArgumentType(JCExpression tree, Env<AttrContext> env, T speculativeTree, Map<ResultInfo, Type> speculativeTypes) {
deferredAttr.super(tree, env);
this.speculativeTree = speculativeTree;
this.speculativeTypes = speculativeTypes;
}
@Override
final DeferredTypeCompleter completer() {
return this;
}
@Override
final public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
Assert.check(dt == this);
if (deferredAttrContext.mode == AttrMode.SPECULATIVE) {
Type t = (resultInfo.pt == Type.recoveryType) ?
deferredAttr.basicCompleter.complete(dt, resultInfo, deferredAttrContext) :
overloadCheck(resultInfo, deferredAttrContext);
speculativeTypes.put(resultInfo, t);
return t;
} else {
if (!env.info.isSpeculative) {
argumentTypeCache.remove(new UniquePos(dt.tree));
}
return deferredAttr.basicCompleter.complete(dt, resultInfo, deferredAttrContext);
}
}
@Override
Type speculativeType(Symbol msym, MethodResolutionPhase phase) {
if (notPertinentToApplicability.contains(msym)) {
return super.speculativeType(msym, phase);
} else {
for (Map.Entry<ResultInfo, Type> _entry : speculativeTypes.entrySet()) {
DeferredAttrContext deferredAttrContext = _entry.getKey().checkContext.deferredAttrContext();
if (deferredAttrContext.phase == phase && deferredAttrContext.msym == msym) {
return _entry.getValue();
}
}
return Type.noType;
}
}
@Override
JCTree speculativeTree(DeferredAttrContext deferredAttrContext) {
return notPertinentToApplicability.contains(deferredAttrContext.msym) ?
super.speculativeTree(deferredAttrContext) :
speculativeTree;
}
abstract Type overloadCheck(ResultInfo resultInfo, DeferredAttrContext deferredAttrContext);
abstract ArgumentType<T> dup(T tree, Env<AttrContext> env);
}
class ParensType extends ArgumentType<JCParens> {
ParensType(JCExpression tree, Env<AttrContext> env, JCParens speculativeParens) {
this(tree, env, speculativeParens, new HashMap<>());
}
ParensType(JCExpression tree, Env<AttrContext> env, JCParens speculativeParens, Map<ResultInfo, Type> speculativeTypes) {
super(tree, env, speculativeParens, speculativeTypes);
}
@Override
Type overloadCheck(ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
return checkSpeculative(speculativeTree.expr, resultInfo);
}
@Override
ArgumentType<JCParens> dup(JCParens tree, Env<AttrContext> env) {
return new ParensType(tree, env, speculativeTree, speculativeTypes);
}
}
class ConditionalType extends ArgumentType<JCConditional> {
ConditionalType(JCExpression tree, Env<AttrContext> env, JCConditional speculativeCond) {
this(tree, env, speculativeCond, new HashMap<>());
}
ConditionalType(JCExpression tree, Env<AttrContext> env, JCConditional speculativeCond, Map<ResultInfo, Type> speculativeTypes) {
super(tree, env, speculativeCond, speculativeTypes);
}
@Override
Type overloadCheck(ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
ResultInfo localInfo = resultInfo.dup(attr.conditionalContext(resultInfo.checkContext));
if (speculativeTree.isStandalone()) {
return localInfo.check(speculativeTree, speculativeTree.type);
} else if (resultInfo.pt.hasTag(VOID)) {
resultInfo.checkContext.report(tree, attr.diags.fragment(Fragments.ConditionalTargetCantBeVoid));
return attr.types.createErrorType(resultInfo.pt);
} else {
checkSpeculative(speculativeTree.truepart, localInfo);
checkSpeculative(speculativeTree.falsepart, localInfo);
return localInfo.pt;
}
}
@Override
ArgumentType<JCConditional> dup(JCConditional tree, Env<AttrContext> env) {
return new ConditionalType(tree, env, speculativeTree, speculativeTypes);
}
}
class ExplicitLambdaType extends ArgumentType<JCLambda> {
Optional<List<Type>> argtypes = Optional.empty();
Optional<List<JCReturn>> returnExpressions = Optional.empty();
ExplicitLambdaType(JCLambda originalLambda, Env<AttrContext> env, JCLambda speculativeLambda) {
this(originalLambda, env, speculativeLambda, new HashMap<>());
}
ExplicitLambdaType(JCLambda originalLambda, Env<AttrContext> env, JCLambda speculativeLambda, Map<ResultInfo, Type> speculativeTypes) {
super(originalLambda, env, speculativeLambda, speculativeTypes);
}
List<Type> argtypes() {
return argtypes.orElseGet(() -> {
List<Type> res = TreeInfo.types(speculativeTree.params);
argtypes = Optional.of(res);
return res;
});
}
List<JCReturn> returnExpressions() {
return returnExpressions.orElseGet(() -> {
final List<JCReturn> res;
ListBuffer<JCReturn> buf = new ListBuffer<>();
new LambdaReturnScanner() {
@Override
public void visitReturn(JCReturn tree) {
buf.add(tree);
}
}.scan(speculativeTree.body);
res = buf.toList();
returnExpressions = Optional.of(res);
return res;
});
}
@Override
Type overloadCheck(ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
try {
TargetInfo targetInfo = attr.getTargetInfo(speculativeTree, resultInfo, argtypes());
Type lambdaType = targetInfo.descriptor;
Type currentTarget = targetInfo.target;
checkLambdaCompatible(lambdaType, resultInfo);
return currentTarget;
} catch (FunctionDescriptorLookupError ex) {
resultInfo.checkContext.report(null, ex.getDiagnostic());
return null;
}
}
private void checkLambdaCompatible(Type descriptor, ResultInfo resultInfo) {
CheckContext checkContext = resultInfo.checkContext;
ResultInfo bodyResultInfo = attr.lambdaBodyResult(speculativeTree, descriptor, resultInfo);
switch (speculativeTree.getBodyKind()) {
case EXPRESSION:
checkSpeculative(speculativeTree.body, speculativeTree.body.type, bodyResultInfo);
break;
case STATEMENT:
for (JCReturn ret : returnExpressions()) {
checkReturnInStatementLambda(ret, bodyResultInfo);
}
break;
}
attr.checkLambdaCompatible(speculativeTree, descriptor, checkContext);
}
void checkReturnInStatementLambda(JCReturn ret, ResultInfo resultInfo) {
if (resultInfo.pt.hasTag(VOID) && ret.expr != null) {
resultInfo.checkContext.report(speculativeTree.pos(),
diags.fragment("unexpected.ret.val"));
} else if (!resultInfo.pt.hasTag(VOID)) {
if (ret.expr == null) {
resultInfo.checkContext.report(speculativeTree.pos(),
diags.fragment("missing.ret.val"));
}
checkSpeculative(ret.expr, ret.expr.type, resultInfo);
}
}
Type getReturnType(JCReturn ret) {
if (ret.expr == null) {
return syms.voidType;
} else {
return ret.expr.type;
}
}
@Override
ArgumentType<JCLambda> dup(JCLambda tree, Env<AttrContext> env) {
return new ExplicitLambdaType(tree, env, speculativeTree, speculativeTypes);
}
}
abstract class ResolvedMemberType<E extends JCExpression> extends ArgumentType<E> {
public ResolvedMemberType(JCExpression tree, Env<AttrContext> env, E speculativeMethod, Map<ResultInfo, Type> speculativeTypes) {
super(tree, env, speculativeMethod, speculativeTypes);
}
@Override
Type overloadCheck(ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
Type mtype = methodType();
ResultInfo localInfo = resultInfo(resultInfo);
Type t;
if (mtype != null && mtype.hasTag(METHOD) && mtype.isPartial()) {
t = ((PartiallyInferredMethodType)mtype).check(localInfo);
} else {
t = localInfo.check(tree.pos(), speculativeTree.type);
}
speculativeTypes.put(localInfo, t);
return t;
}
abstract ResultInfo resultInfo(ResultInfo resultInfo);
abstract Type methodType();
}
class ResolvedMethodType extends ResolvedMemberType<JCMethodInvocation> {
public ResolvedMethodType(JCExpression tree, Env<AttrContext> env, JCMethodInvocation speculativeTree) {
this(tree, env, speculativeTree, new HashMap<>());
}
public ResolvedMethodType(JCExpression tree, Env<AttrContext> env, JCMethodInvocation speculativeTree, Map<ResultInfo, Type> speculativeTypes) {
super(tree, env, speculativeTree, speculativeTypes);
}
@Override
ResultInfo resultInfo(ResultInfo resultInfo) {
return resultInfo;
}
@Override
Type methodType() {
return speculativeTree.meth.type;
}
@Override
ArgumentType<JCMethodInvocation> dup(JCMethodInvocation tree, Env<AttrContext> env) {
return new ResolvedMethodType(tree, env, speculativeTree, speculativeTypes);
}
}
class ResolvedConstructorType extends ResolvedMemberType<JCNewClass> {
public ResolvedConstructorType(JCExpression tree, Env<AttrContext> env, JCNewClass speculativeTree) {
this(tree, env, speculativeTree, new HashMap<>());
}
public ResolvedConstructorType(JCExpression tree, Env<AttrContext> env, JCNewClass speculativeTree, Map<ResultInfo, Type> speculativeTypes) {
super(tree, env, speculativeTree, speculativeTypes);
}
@Override
ResultInfo resultInfo(ResultInfo resultInfo) {
return resultInfo.dup(attr.diamondContext(speculativeTree, speculativeTree.clazz.type.tsym, resultInfo.checkContext));
}
@Override
Type methodType() {
return (speculativeTree.constructorType != null) ?
speculativeTree.constructorType.baseType() : syms.errType;
}
@Override
ArgumentType<JCNewClass> dup(JCNewClass tree, Env<AttrContext> env) {
return new ResolvedConstructorType(tree, env, speculativeTree, speculativeTypes);
}
}
class UniquePos {
int pos;
DiagnosticSource source;
UniquePos(JCTree tree) {
this.pos = tree.pos;
this.source = log.currentSource();
}
@Override
public int hashCode() {
return pos << 16 + source.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof UniquePos) {
UniquePos that = (UniquePos)obj;
return pos == that.pos && source == that.source;
} else {
return false;
}
}
@Override
public String toString() {
return source.getFile().getName() + " @ " + source.getLineNumber(pos);
}
}
}