Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
}
}
15 changes: 14 additions & 1 deletion nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -90,6 +92,7 @@ public static Handler buildDefault(Config config) {
restrictiveAnnotationHandler.initMainHandler(mainHandler);
}
libraryModelsHandler.initMainHandler(mainHandler);
javaStreamNullabilityPropagator.initMainHandler(mainHandler);

return mainHandler;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Integer, NestedAnnotationInfo> nestedAnnotations =
optimizedLibraryModels.nestedAnnotationsForMethods(methodSymbol);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -183,14 +188,23 @@ static CollectRecordAndInnerMethod create(
new LinkedHashMap<>();
private final ImmutableList<StreamTypeRecord> models;

private @Nullable NullAway analysis;

private @Nullable Handler mainHandler;

StreamNullabilityPropagator(ImmutableList<StreamTypeRecord> 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();
Expand Down Expand Up @@ -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<Type> 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<Type> 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading
Loading