Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ private AccessPathNullnessAnalysis(VisitorState state, NullAway analysis) {
.build();
this.nullnessPropagation =
new AccessPathNullnessPropagation(
Nullness.NONNULL, state, apContext, analysis, new CoreNullnessStoreInitializer());
Nullness.NONNULL,
state,
apContext,
analysis,
new CoreNullnessStoreInitializer(analysis.getGenericsChecks()));
this.dataFlow = new DataFlow(config.assertsEnabled(), handler);

if (config.checkContracts()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.uber.nullaway.Config;
import com.uber.nullaway.NullabilityUtil;
import com.uber.nullaway.Nullness;
import com.uber.nullaway.generics.GenericsChecks;
import com.uber.nullaway.generics.TypeSubstitutionUtils;
import com.uber.nullaway.handlers.Handler;
import java.util.List;
Expand All @@ -28,6 +29,12 @@

class CoreNullnessStoreInitializer extends NullnessStoreInitializer {

private final GenericsChecks genericsChecks;

public CoreNullnessStoreInitializer(GenericsChecks genericsChecks) {
this.genericsChecks = genericsChecks;
}
Comment thread
msridhar marked this conversation as resolved.
Resolved

@Override
public NullnessStore getInitialStore(
UnderlyingAST underlyingAST,
Expand Down Expand Up @@ -82,7 +89,7 @@ private static NullnessStore methodInitialStore(
return result.build();
}

private static NullnessStore lambdaInitialStore(
private NullnessStore lambdaInitialStore(
UnderlyingAST.CFGLambda underlyingAST,
List<LocalVariableNode> parameters,
Handler handler,
Expand All @@ -103,11 +110,27 @@ private static NullnessStore lambdaInitialStore(
Symbol.MethodSymbol fiMethodSymbol = NullabilityUtil.getFunctionalInterfaceMethod(code, types);
com.sun.tools.javac.util.List<Symbol.VarSymbol> fiMethodParameters =
fiMethodSymbol.getParameters();

/*
* A potential concern here is that this method might return null because we haven't inferred the type
* of the lambda yet.
* However, this is not an issue due to the standard AST traversal order used by Error Prone.
* We currently only infer lambda types when they are passed as a parameter to a generic method.
* The checker is guaranteed to visit the enclosing generic method call (e.g., {@code wrap(s -> ...)})
* and perform type inference for it *before* it descends into the lambda's body to begin dataflow
* analysis. By the time this method is called during the setup for the lambda's analysis, the
* inferred type for the lambda argument will have already been computed and stored.
*/
Type lambdaType = castToNonNull(ASTHelpers.getType(code));
Type inferredType = genericsChecks.getInferredLambdaType(code);
if (inferredType != null) {
lambdaType = inferredType;
}

// This obtains the types of the functional interface method parameters with preserved
// annotations in case of generic type arguments. Only used in JSpecify mode.
List<Type> overridenMethodParamTypeList =
TypeSubstitutionUtils.memberType(
types, castToNonNull(ASTHelpers.getType(code)), fiMethodSymbol, config)
TypeSubstitutionUtils.memberType(types, lambdaType, fiMethodSymbol, config)
.getParameterTypes();
// If fiArgumentPositionNullness[i] == null, parameter position i is unannotated
@Nullable Nullness[] fiArgumentPositionNullness = new Nullness[fiMethodParameters.size()];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
Expand Down Expand Up @@ -98,6 +99,16 @@ private static final class InferenceFailure implements MethodInferenceResult {
private final Map<MethodInvocationTree, MethodInferenceResult>
inferredTypeVarNullabilityForGenericCalls = new LinkedHashMap<>();

/**
* Maps each {@code LambdaExpressionTree} passed as a parameter to a generic method to its
* inferred type, if inference for the generic method call succeeded.
*/
private final Map<LambdaExpressionTree, Type> inferredLambdaTypes = new LinkedHashMap<>();

public @Nullable Type getInferredLambdaType(LambdaExpressionTree tree) {
return inferredLambdaTypes.get(tree);
}

private final NullAway analysis;
private final Config config;
private final Handler handler;
Expand Down Expand Up @@ -615,6 +626,18 @@ private MethodInferenceResult runInferenceForCall(
invocationTree,
allInvocations);
typeVarNullability = solver.solve();

// Store inferred types for lambda arguments
Comment thread
dhruv-agr marked this conversation as resolved.
Resolved
new InvocationArguments(invocationTree, methodSymbol.type.asMethodType())
.forEach(
(argument, argPos, formalParamType, unused) -> {
if (argument instanceof LambdaExpressionTree) {
Type inferredType =
getTypeWithInferredNullability(state, formalParamType, typeVarNullability);
inferredLambdaTypes.put((LambdaExpressionTree) argument, inferredType);
}
});

InferenceSuccess successResult = new InferenceSuccess(typeVarNullability);
for (MethodInvocationTree invTree : allInvocations) {
inferredTypeVarNullabilityForGenericCalls.put(invTree, successResult);
Expand Down Expand Up @@ -715,7 +738,9 @@ private void generateConstraintsForParam(
allInvocations.add(invTree);
generateConstraintsForCall(
state, formalParamType, false, solver, symbol, invTree, allInvocations);
} else {
} else if (!(argument instanceof LambdaExpressionTree)) {
// Skip adding a subtype constraint for lambda arguments; we want to also infer the type of
// the lambda expression
Type argumentType = getTreeType(argument, state);
if (argumentType == null) {
// bail out of any checking involving raw types for now
Expand Down Expand Up @@ -959,7 +984,16 @@ public void compareGenericTypeParameterNullabilityForCall(
// bail out of any checking involving raw types for now
return;
}
Type actualParameterType = getTreeType(currentActualParam, state);

Type actualParameterType = null;
if ((currentActualParam instanceof LambdaExpressionTree)) {
Type lambdaInferredType = inferredLambdaTypes.get(currentActualParam);
if (lambdaInferredType != null) {
actualParameterType = lambdaInferredType;
}
} else {
actualParameterType = getTreeType(currentActualParam, state);
}
if (actualParameterType != null) {
if (isGenericCallNeedingInference(currentActualParam)) {
// infer the type of the method call based on the assignment context
Expand Down Expand Up @@ -1653,6 +1687,7 @@ public boolean passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode(
*/
public void clearCache() {
inferredTypeVarNullabilityForGenericCalls.clear();
inferredLambdaTypes.clear();
}

public boolean isNullableAnnotated(Type type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,33 @@ public void inferenceFromReceiverPassing() {
.doTest();
}

@Test
public void issue1294_lambdaArguments() {
makeHelperWithInferenceFailureWarning()
.addSourceLines(
"Test.java",
"import org.jspecify.annotations.NullMarked;",
"import org.jspecify.annotations.Nullable;",
"@NullMarked",
"class Foo {",
" public interface Callback<T extends @Nullable Object> {",
" void onResult(T thing);",
" }",
" public static <T extends @Nullable Object> Callback<T> wrap(Callback<T> thing) {",
" return thing;",
" }",
" public static void test() {",
" Callback<@Nullable String> ret1 = wrap(s -> {});",
// we should get an error at the s.hashCode() call.
" // BUG: Diagnostic contains: dereferenced expression",
" Callback<@Nullable String> ret2 = wrap(s -> { s.hashCode(); });",
Comment thread
dhruv-agr marked this conversation as resolved.
Resolved
" Callback<@Nullable String> ret3 = wrap(s -> { if (s != null) s.hashCode(); });",
" Callback<String> ret4 = wrap(s -> { s.hashCode(); });",
" }",
"}")
.doTest();
}

private CompilationTestHelper makeHelper() {
return makeTestHelperWithArgs(
Arrays.asList(
Expand Down