diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 400f32431a..8598478b6f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -641,7 +641,8 @@ private void reportInvalidOverridingMethodParamTypeError( TypeSubstitutionUtils.memberType(state.getTypes(), enclosingType, symbol, config); } Type.MethodType methodType = - handler.onOverrideMethodType(symbol, invokedMethodType.asMethodType(), state); + handler.onOverrideMethodType( + symbol, invokedMethodType.asMethodType(), state, invocationTree); // restore explicit annotations from the return type Type returnType = methodType.getReturnType(); result = @@ -1192,7 +1193,8 @@ private void generateConstraintsForCall( boolean calledFromDataflow) throws UnsatisfiableConstraintsException { Type.MethodType methodType = - handler.onOverrideMethodType(methodSymbol, methodSymbol.type.asMethodType(), state); + handler.onOverrideMethodType( + methodSymbol, methodSymbol.type.asMethodType(), state, methodInvocationTree); // first, handle the return type flow if (typeFromAssignmentContext != null) { solver.addSubtypeConstraint( @@ -1411,7 +1413,7 @@ private void handleMethodRefInGenericMethodInference( result = getInferredMethodTypeForGenericMethodReference(result, state); } // finally, run any handlers - return handler.onOverrideMethodType(overridingMethod, result, state); + return handler.onOverrideMethodType(overridingMethod, result, state, null); } /** @@ -1834,7 +1836,13 @@ public void compareGenericTypeParameterNullabilityForCall( } Type.MethodType finalMethodType = - handler.onOverrideMethodType(methodSymbol, invokedMethodType.asMethodType(), state); + handler.onOverrideMethodType( + methodSymbol, + invokedMethodType.asMethodType(), + state, + tree instanceof MethodInvocationTree methodInvocationTree + ? methodInvocationTree + : null); new InvocationArguments(tree, finalMethodType) .forEach( (currentActualParam, argPos, formalParameter, unused) -> { diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java index d127adbb23..eb347e862b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java @@ -354,10 +354,13 @@ public boolean onOverrideNullMarkedClasses(String className) { @Override public Type.MethodType onOverrideMethodType( - Symbol.MethodSymbol methodSymbol, Type.MethodType methodType, VisitorState state) { + Symbol.MethodSymbol methodSymbol, + Type.MethodType methodType, + VisitorState state, + @Nullable MethodInvocationTree invocationTree) { Type.MethodType currentType = methodType; for (Handler h : handlers) { - currentType = h.onOverrideMethodType(methodSymbol, currentType, state); + currentType = h.onOverrideMethodType(methodSymbol, currentType, state, invocationTree); } return currentType; } @@ -372,4 +375,15 @@ public boolean shouldSkipFieldInitializationCheck( } return false; } + + @Override + public boolean isSingleArgNullImpliesFalseMethod( + Symbol.MethodSymbol methodSymbol, VisitorState state) { + for (Handler h : handlers) { + if (h.isSingleArgNullImpliesFalseMethod(methodSymbol, state)) { + return true; + } + } + return false; + } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java index 0cda1db417..0a80ca1811 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java @@ -484,10 +484,14 @@ default boolean onOverrideNullMarkedClasses(String className) { * @param methodSymbol symbol of the method * @param methodType original method type * @param state The current visitor state. + * @param invocationTree the invocation tree for the method, if available * @return the possibly modified method type */ default Type.MethodType onOverrideMethodType( - Symbol.MethodSymbol methodSymbol, Type.MethodType methodType, VisitorState state) { + Symbol.MethodSymbol methodSymbol, + Type.MethodType methodType, + VisitorState state, + @Nullable MethodInvocationTree invocationTree) { return methodType; } @@ -506,6 +510,15 @@ default boolean shouldSkipFieldInitializationCheck( return false; } + /** + * Returns true if the given method takes a single argument and returns {@code false} whenever the + * argument is {@code null}. + */ + default boolean isSingleArgNullImpliesFalseMethod( + Symbol.MethodSymbol methodSymbol, VisitorState state) { + return false; + } + /** * A three value enum for handlers implementing onDataflowVisitMethodInvocation to communicate * their knowledge of the method return nullability to the rest of NullAway. diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/Handlers.java b/nullaway/src/main/java/com/uber/nullaway/handlers/Handlers.java index 8692d0bfa5..c4491b136f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/Handlers.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/Handlers.java @@ -60,7 +60,9 @@ public static Handler buildDefault(Config config) { LibraryModelsHandler libraryModelsHandler = new LibraryModelsHandler(config); handlerListBuilder.add(libraryModelsHandler); handlerListBuilder.add(StreamNullabilityPropagatorFactory.getRxStreamNullabilityPropagator()); - handlerListBuilder.add(StreamNullabilityPropagatorFactory.getJavaStreamNullabilityPropagator()); + StreamNullabilityPropagator javaStreamNullabilityPropagator = + StreamNullabilityPropagatorFactory.getJavaStreamNullabilityPropagator(); + handlerListBuilder.add(javaStreamNullabilityPropagator); handlerListBuilder.add( StreamNullabilityPropagatorFactory.fromSpecs( libraryModelsHandler.getStreamNullabilitySpecs())); @@ -90,6 +92,7 @@ public static Handler buildDefault(Config config) { restrictiveAnnotationHandler.initMainHandler(mainHandler); } libraryModelsHandler.initMainHandler(mainHandler); + javaStreamNullabilityPropagator.initMainHandler(mainHandler); return mainHandler; } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java index 14198e7a75..e22132bbc0 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java @@ -426,11 +426,21 @@ public boolean onOverrideNullMarkedClasses(String className) { return libraryModels.nullMarkedClasses().contains(className); } + @Override + public boolean isSingleArgNullImpliesFalseMethod( + Symbol.MethodSymbol methodSymbol, VisitorState state) { + return methodSymbol.getParameters().size() == 1 + && getOptLibraryModels(state.context).nullImpliesFalseParameters(methodSymbol).contains(0); + } + /** Updates method types based on nested annotation information from library models. */ @Override @SuppressWarnings("ReferenceEquality") public Type.MethodType onOverrideMethodType( - Symbol.MethodSymbol methodSymbol, Type.MethodType methodType, VisitorState state) { + Symbol.MethodSymbol methodSymbol, + Type.MethodType methodType, + VisitorState state, + @Nullable MethodInvocationTree invocationTree) { OptimizedLibraryModels optimizedLibraryModels = getOptLibraryModels(state.context); ImmutableSetMultimap nestedAnnotations = optimizedLibraryModels.nestedAnnotationsForMethods(methodSymbol); diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java b/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java index f1084be80a..1d118543f6 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java @@ -52,11 +52,15 @@ import com.uber.nullaway.dataflow.AccessPathElement; import com.uber.nullaway.dataflow.AccessPathNullnessAnalysis; import com.uber.nullaway.dataflow.NullnessStore; +import com.uber.nullaway.generics.GenericsChecks; +import com.uber.nullaway.generics.TypeMetadataBuilder; +import com.uber.nullaway.generics.TypeSubstitutionUtils; import com.uber.nullaway.handlers.stream.CollectLikeMethodRecord; import com.uber.nullaway.handlers.stream.MapLikeMethodRecord; import com.uber.nullaway.handlers.stream.MapOrCollectLikeMethodRecord; import com.uber.nullaway.handlers.stream.MapOrCollectMethodToFilterInstanceRecord; import com.uber.nullaway.handlers.stream.StreamTypeRecord; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -68,6 +72,7 @@ import javax.lang.model.element.ExecutableElement; import org.checkerframework.nullaway.dataflow.cfg.UnderlyingAST; import org.checkerframework.nullaway.dataflow.cfg.node.LocalVariableNode; +import org.jspecify.annotations.Nullable; /** * This Handler transfers nullability info through chains of calls to methods of @@ -183,14 +188,23 @@ static CollectRecordAndInnerMethod create( new LinkedHashMap<>(); private final ImmutableList models; + private @Nullable NullAway analysis; + + private @Nullable Handler mainHandler; + StreamNullabilityPropagator(ImmutableList models) { super(); this.models = models; } + void initMainHandler(Handler mainHandler) { + this.mainHandler = mainHandler; + } + @Override public void onMatchTopLevelClass( NullAway analysis, ClassTree tree, VisitorState state, Symbol.ClassSymbol classSymbol) { + this.analysis = analysis; // Clear compilation unit specific state this.filterMethodOrLambdaSet.clear(); this.observableOuterCallInChain.clear(); @@ -281,6 +295,84 @@ private void handleMapMethod( } } + /** + * If the invocation is a call of the form {@code s.filter(meth)}, where {@code s} has type {@code + * Stream<@Nullable Foo>} and {@code meth} is a null-filtering method like {@code + * Objects::nonNull}, updates the return type of the invocation to be {@code Stream<@NonNull + * Foo>}. + */ + @Override + @SuppressWarnings("ReferenceEquality") // reference equality check on types ok in this case + public Type.MethodType onOverrideMethodType( + Symbol.MethodSymbol methodSymbol, + Type.MethodType methodType, + VisitorState state, + @Nullable MethodInvocationTree invocationTree) { + if (invocationTree == null) { + return methodType; + } + if (isNullRejectingFilterInvocation(invocationTree, state)) { + Type returnType = methodType.getReturnType(); + Type updatedReturnType = updateFilterTypeArgToNonNull(returnType, state); + if (updatedReturnType != returnType) { + return new Type.MethodType( + methodType.argtypes, updatedReturnType, methodType.thrown, methodType.tsym); + } + } + return methodType; + } + + /** + * Checks if invocation tree is of the form {@code s.filter(meth)} where {@code s} has some type + * {@code Stream<@Nullable Foo>} and {@code meth} is a null-filtering method like {@code + * Objects::nonNull} + */ + private boolean isNullRejectingFilterInvocation( + MethodInvocationTree invocationTree, VisitorState state) { + Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(invocationTree); + if (methodSymbol == null + || methodSymbol.isStatic() + || invocationTree.getArguments().size() != 1 + || mainHandler == null) { + return false; + } + Type receiverType = ASTHelpers.getReceiverType(invocationTree); + for (StreamTypeRecord streamType : models) { + if (streamType.matchesType(receiverType, state) && streamType.isFilterMethod(methodSymbol)) { + Symbol predicateMethodSymbol = ASTHelpers.getSymbol(invocationTree.getArguments().get(0)); + if (predicateMethodSymbol instanceof Symbol.MethodSymbol predicateMethod + && mainHandler.isSingleArgNullImpliesFalseMethod(predicateMethod, state)) { + return true; + } + } + } + return false; + } + + private Type updateFilterTypeArgToNonNull(Type type, VisitorState state) { + if (!(type instanceof Type.ClassType classType)) { + return type; + } + List typeArgs = classType.getTypeArguments(); + if (typeArgs.size() != 1) { + return type; + } + Type streamElementType = typeArgs.get(0); + if (!Nullness.hasNullableAnnotation( + streamElementType.getAnnotationMirrors().stream(), castToNonNull(analysis).getConfig())) { + return type; + } + // Rather than just stripping the @Nullable annotation, use an explicit @NonNull annotation, as + // the explicit annotation will override other @Nullable annotations placed by javac + Type updatedElementType = + TypeSubstitutionUtils.typeWithAnnot( + streamElementType, GenericsChecks.getSyntheticNonNullAnnotType(state)); + java.util.List updatedTypeArgs = new ArrayList<>(1); + updatedTypeArgs.add(updatedElementType); + return TypeMetadataBuilder.TYPE_METADATA_BUILDER.createClassType( + classType, classType.getEnclosingType(), updatedTypeArgs); + } + /** * Handles a call to a collect-like method. If the argument to the method is supported, updates * the {@link #collectCallToRecordsAndInnerMethodsOrLambdas} map appropriately. diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractHandler.java index ed8ee5ebc5..1cff57b71a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractHandler.java @@ -97,6 +97,27 @@ public ContractHandler(Config config) { this.config = config; } + @Override + public boolean isSingleArgNullImpliesFalseMethod( + Symbol.MethodSymbol methodSymbol, VisitorState state) { + if (methodSymbol.getParameters().size() != 1) { + return false; + } + for (String clause : ContractUtils.getContractClauses(methodSymbol, config)) { + String[] parts = clause.split("->"); + if (parts.length != 2) { + continue; + } + String[] antecedent = parts[0].trim().isEmpty() ? new String[0] : parts[0].split(","); + if (antecedent.length == 1 + && antecedent[0].trim().equals("null") + && parts[1].trim().equals("false")) { + return true; + } + } + return false; + } + @Override public void onMatchTopLevelClass( NullAway analysis, ClassTree tree, VisitorState state, Symbol.ClassSymbol classSymbol) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java new file mode 100644 index 0000000000..e02761b842 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java @@ -0,0 +1,166 @@ +package com.uber.nullaway.jspecify; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAwayTestsBase; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.Arrays; +import org.junit.Test; + +public class StreamNullabilityPropagatorTests extends NullAwayTestsBase { + + @Test + public void filterRefinesStreamElementType() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Arrays; + import java.util.List; + import java.util.Objects; + import java.util.Optional; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + static Optional sumNumbersAsDoubles(@Nullable Number... numbers) { + return Arrays.stream(numbers) + .filter(Objects::nonNull) + .map(Number::doubleValue) + .reduce(Double::sum); + } + + static Optional sumDoubles(@Nullable Double... doubles) { + return Arrays.stream(doubles) + .filter(Objects::nonNull) + .reduce(Double::sum); + } + + static Optional sumDoublesMissingfilter(@Nullable Double... doubles) { + return Arrays.stream(doubles) + // BUG: Diagnostic contains: incompatible types + .reduce(Double::sum); + } + + static Optional sumDoublesWithExplicitMap(@Nullable Double... doubles) { + return Arrays.stream(doubles) + .filter(Objects::nonNull) + .map(Objects::requireNonNull) + .reduce(Double::sum); + } + + static List nullableStringsToNonNull(List<@Nullable String> values) { + return values.stream().filter(Objects::nonNull).toList(); + } + } + """) + .doTest(); + } + + @Test + public void filterWithStringUtilsHasLength() { + makeHelper() + .addSourceLines( + "org/springframework/util/StringUtils.java", + """ + package org.springframework.util; + // stub for Spring's StringUtils class for which we have a library model + public final class StringUtils { + public static boolean hasLength(String value) { + return value != null && !value.isEmpty(); + } + } + """) + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + import org.springframework.util.StringUtils; + + @NullMarked + class Test { + static List nullableStringsToNonNull(List<@Nullable String> values) { + return values.stream().filter(StringUtils::hasLength).toList(); + } + } + """) + .doTest(); + } + + @Test + public void filterWithContractMethod() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jetbrains.annotations.Contract; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + @Contract("null -> false") + static boolean hasLength(@Nullable String value) { + return value != null && !value.isEmpty(); + } + + static List nullableStringsToNonNull(List<@Nullable String> values) { + return values.stream().filter(Test::hasLength).toList(); + } + } + """) + .doTest(); + } + + @Test + public void unrelatedFilterDoesNotRefineStreamElementType() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.Objects; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + static List filterDoesNotProveNonNull(List<@Nullable String> values) { + // BUG: Diagnostic contains: incompatible types + return values.stream().filter(value -> true).toList(); + } + + static @Nullable String maybeNull(String value) { + return null; + } + + static List<@Nullable String> genericMapAfterNullRejectingFilterUsesCallSiteInference( + List<@Nullable String> values) { + return values.stream() + .filter(Objects::nonNull) + .map(Test::maybeNull) + .toList(); + } + + static List mapAfterNullRejectingFilterCanStillReturnNullable( + List<@Nullable String> values) { + return values.stream() + .filter(Objects::nonNull) + .map(Test::maybeNull) + // BUG: Diagnostic contains: incompatible types + .toList(); + } + } + """) + .doTest(); + } + + private CompilationTestHelper makeHelper() { + return makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + Arrays.asList("-XepOpt:NullAway:OnlyNullMarked=true"))); + } +}