From f7d8b62015f700f98ca0d3638c326dd60be9fc66 Mon Sep 17 00:00:00 2001 From: tschoemaker Date: Tue, 28 May 2024 15:57:27 +0200 Subject: [PATCH 1/5] refactor data clumps --- .../main/java/com/uber/nullaway/NullAway.java | 14 ++- .../AbstractFieldContractHandler.java | 105 ++++++++++-------- .../nullaway/handlers/BaseNoOpHandler.java | 24 +--- .../nullaway/handlers/CompositeHandler.java | 34 ++---- .../com/uber/nullaway/handlers/Handler.java | 44 ++------ .../handlers/LibraryModelsHandler.java | 16 +-- .../handlers/MethodAnalysisContext.java | 43 +++++++ .../handlers/StreamNullabilityPropagator.java | 56 +++++----- .../contract/ContractCheckHandler.java | 34 ++++-- .../fieldcontract/EnsuresNonNullHandler.java | 39 ++++--- .../fieldcontract/RequiresNonNullHandler.java | 53 +++++---- 11 files changed, 254 insertions(+), 208 deletions(-) create mode 100644 nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index e5de3a9e1b..111a593b2f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -98,6 +98,7 @@ import com.uber.nullaway.generics.GenericsChecks; import com.uber.nullaway.handlers.Handler; import com.uber.nullaway.handlers.Handlers; +import com.uber.nullaway.handlers.MethodAnalysisContext; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -402,7 +403,7 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState return Description.NO_MATCH; } Symbol.MethodSymbol methodSymbol = getSymbolForMethodInvocation(tree); - handler.onMatchMethodInvocation(this, tree, state, methodSymbol); + handler.onMatchMethodInvocation(tree, new MethodAnalysisContext(this, state, methodSymbol)); // assuming this list does not include the receiver List actualParams = tree.getArguments(); return handleInvocation(tree, state, methodSymbol, actualParams); @@ -671,7 +672,7 @@ public Description matchMethod(MethodTree tree, VisitorState state) { // overridden method (if overridden method is in an annotated // package) Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree); - handler.onMatchMethod(this, tree, state, methodSymbol); + handler.onMatchMethod(tree, new MethodAnalysisContext(this, state, methodSymbol)); boolean isOverriding = ASTHelpers.hasAnnotation(methodSymbol, "java.lang.Override", state); boolean exhaustiveOverride = config.exhaustiveOverride(); if (isOverriding || !exhaustiveOverride) { @@ -979,7 +980,8 @@ public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState // we need to update environment mapping before running the handler, as some handlers // (like Rx nullability) run dataflow analysis updateEnvironmentMapping(state.getPath(), state); - handler.onMatchLambdaExpression(this, tree, state, funcInterfaceMethod); + handler.onMatchLambdaExpression( + tree, new MethodAnalysisContext(this, state, funcInterfaceMethod)); if (codeAnnotationInfo.isSymbolUnannotated(funcInterfaceMethod, config, handler)) { return Description.NO_MATCH; } @@ -1023,7 +1025,7 @@ public Description matchMemberReference(MemberReferenceTree tree, VisitorState s Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(tree); Symbol.MethodSymbol funcInterfaceSymbol = NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes()); - handler.onMatchMethodReference(this, tree, state, referencedMethod); + handler.onMatchMethodReference(tree, new MethodAnalysisContext(this, state, referencedMethod)); return checkOverriding(funcInterfaceSymbol, referencedMethod, tree, state); } @@ -1467,7 +1469,7 @@ private boolean okToReadBeforeInitialized(TreePath path, VisitorState state) { } else { castToNonNullArg = handler.castToNonNullArgumentPositionsForMethod( - this, state, methodSymbol, arguments, null); + arguments, null, new MethodAnalysisContext(this, state, methodSymbol)); } if (castToNonNullArg != null && leaf.equals(arguments.get(castToNonNullArg))) { return true; @@ -1840,7 +1842,7 @@ private Description checkCastToNonNullTakesNullable( } else { castToNonNullPosition = handler.castToNonNullArgumentPositionsForMethod( - this, state, methodSymbol, actualParams, null); + actualParams, null, new MethodAnalysisContext(this, state, methodSymbol)); } if (castToNonNullPosition != null) { ExpressionTree actual = actualParams.get(castToNonNullPosition); diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java index d90cc80e88..eb7d29f7e8 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java @@ -60,27 +60,26 @@ protected AbstractFieldContractHandler(String annotName) { /** * Verifies that the method being processed adheres to the annotation specifications. * - * @param analysis NullAway instance. * @param tree Method tree under processing. - * @param state Error Prone {@link VisitorState}. - * @param methodSymbol Processing method symbol. + * @param methodAnalysisContext The MethodAnalysisContext object */ @Override - public void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { + public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { Set annotationContent = - NullabilityUtil.getAnnotationValueArray(methodSymbol, annotName, false); + NullabilityUtil.getAnnotationValueArray( + methodAnalysisContext.getMethodSymbol(), annotName, false); boolean isAnnotated = annotationContent != null; boolean isValid = isAnnotated && validateAnnotationSyntax( - castToNonNull(annotationContent), analysis, tree, state, methodSymbol) - && validateAnnotationSemantics(analysis, state, tree, methodSymbol); + castToNonNull(annotationContent), tree, methodAnalysisContext) + && validateAnnotationSemantics(tree, methodAnalysisContext); if (isAnnotated && !isValid) { return; } Symbol.MethodSymbol closestOverriddenMethod = - NullabilityUtil.getClosestOverriddenMethod(methodSymbol, state.getTypes()); + NullabilityUtil.getClosestOverriddenMethod( + methodAnalysisContext.getMethodSymbol(), methodAnalysisContext.getState().getTypes()); if (closestOverriddenMethod == null) { return; } @@ -90,8 +89,13 @@ && validateAnnotationSyntax( } else { fieldNames = Collections.emptySet(); } - validateOverridingRules(fieldNames, analysis, state, tree, closestOverriddenMethod); - super.onMatchMethod(analysis, tree, state, methodSymbol); + validateOverridingRules( + fieldNames, + methodAnalysisContext.getAnalysis(), + methodAnalysisContext.getState(), + tree, + closestOverriddenMethod); + super.onMatchMethod(tree, methodAnalysisContext); } /** @@ -117,9 +121,10 @@ protected abstract void validateOverridingRules( * Validates that a method implementation matches the semantics of the annotation. * * @return Returns true, if the annotation conforms to the semantic rules. + * @param methodAnalysisContext The MethodAnalysisContext object */ protected abstract boolean validateAnnotationSemantics( - NullAway analysis, VisitorState state, MethodTree tree, Symbol.MethodSymbol methodSymbol); + MethodTree tree, MethodAnalysisContext methodAnalysisContext); /** * Validates whether the parameter inside annotation conforms to the syntax rules. Parameters must @@ -137,13 +142,10 @@ protected abstract boolean validateAnnotationSemantics( *

* * @return Returns true, if the annotation conforms to the syntax rules. + * @param methodAnalysisContext The MethodAnalysisContext object */ protected boolean validateAnnotationSyntax( - Set content, - NullAway analysis, - MethodTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + Set content, MethodTree tree, MethodAnalysisContext methodAnalysisContext) { String message; if (content.isEmpty()) { // we should not allow useless annotations. @@ -151,15 +153,18 @@ protected boolean validateAnnotationSyntax( "empty @" + annotName + " is the default precondition for every method, please remove it."; - state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - analysis.buildDescription(tree), - state, - null)); + methodAnalysisContext + .getState() + .reportMatch( + methodAnalysisContext + .getAnalysis() + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + methodAnalysisContext.getAnalysis().buildDescription(tree), + methodAnalysisContext.getState(), + null)); return false; } else { for (String fieldName : content) { @@ -172,22 +177,26 @@ protected boolean validateAnnotationSyntax( + fieldName + " is not supported"; - state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage( - ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - analysis.buildDescription(tree), - state, - null)); + methodAnalysisContext + .getState() + .reportMatch( + methodAnalysisContext + .getAnalysis() + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage( + ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + methodAnalysisContext.getAnalysis().buildDescription(tree), + methodAnalysisContext.getState(), + null)); return false; } else { fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1); } } - Symbol.ClassSymbol classSymbol = castToNonNull(ASTHelpers.enclosingClass(methodSymbol)); + Symbol.ClassSymbol classSymbol = + castToNonNull(ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol())); VariableElement field = getInstanceFieldOfClass(classSymbol, fieldName); if (field == null) { message = @@ -197,15 +206,19 @@ protected boolean validateAnnotationSyntax( + fieldName + " in class " + classSymbol.getSimpleName(); - state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - analysis.buildDescription(tree), - state, - null)); + methodAnalysisContext + .getState() + .reportMatch( + methodAnalysisContext + .getAnalysis() + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage( + ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + methodAnalysisContext.getAnalysis().buildDescription(tree), + methodAnalysisContext.getState(), + null)); return false; } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/BaseNoOpHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/BaseNoOpHandler.java index 171836276b..4656031de9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/BaseNoOpHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/BaseNoOpHandler.java @@ -73,35 +73,25 @@ public void onMatchTopLevelClass( } @Override - public void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { + public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { // NoOp } @Override public void onMatchMethodInvocation( - NullAway analysis, - MethodInvocationTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { // NoOp } @Override public void onMatchLambdaExpression( - NullAway analysis, - LambdaExpressionTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext) { // NoOp } @Override public void onMatchMethodReference( - NullAway analysis, - MemberReferenceTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext) { // NoOp } @@ -238,11 +228,9 @@ public MethodInvocationNode onCFGBuildPhase1AfterVisitMethodInvocation( @Override @Nullable public Integer castToNonNullArgumentPositionsForMethod( - NullAway analysis, - VisitorState state, - Symbol.MethodSymbol methodSymbol, List actualParams, - @Nullable Integer previousArgumentPosition) { + @Nullable Integer previousArgumentPosition, + MethodAnalysisContext methodAnalysisContext) { // NoOp return previousArgumentPosition; } 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 b05128a00a..afe0cb5074 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/CompositeHandler.java @@ -80,43 +80,33 @@ public void onMatchTopLevelClass( } @Override - public void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { + public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { for (Handler h : handlers) { - h.onMatchMethod(analysis, tree, state, methodSymbol); + h.onMatchMethod(tree, methodAnalysisContext); } } @Override public void onMatchLambdaExpression( - NullAway analysis, - LambdaExpressionTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext) { for (Handler h : handlers) { - h.onMatchLambdaExpression(analysis, tree, state, methodSymbol); + h.onMatchLambdaExpression(tree, methodAnalysisContext); } } @Override public void onMatchMethodReference( - NullAway analysis, - MemberReferenceTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext) { for (Handler h : handlers) { - h.onMatchMethodReference(analysis, tree, state, methodSymbol); + h.onMatchMethodReference(tree, methodAnalysisContext); } } @Override public void onMatchMethodInvocation( - NullAway analysis, - MethodInvocationTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { for (Handler h : handlers) { - h.onMatchMethodInvocation(analysis, tree, state, methodSymbol); + h.onMatchMethodInvocation(tree, methodAnalysisContext); } } @@ -310,15 +300,13 @@ public MethodInvocationNode onCFGBuildPhase1AfterVisitMethodInvocation( @Override @Nullable public Integer castToNonNullArgumentPositionsForMethod( - NullAway analysis, - VisitorState state, - Symbol.MethodSymbol methodSymbol, List actualParams, - @Nullable Integer previousArgumentPosition) { + @Nullable Integer previousArgumentPosition, + MethodAnalysisContext methodAnalysisContext) { for (Handler h : handlers) { previousArgumentPosition = h.castToNonNullArgumentPositionsForMethod( - analysis, state, methodSymbol, actualParams, previousArgumentPosition); + actualParams, previousArgumentPosition, methodAnalysisContext); } return previousArgumentPosition; } 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 08477a056f..538c587e95 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/Handler.java @@ -78,55 +78,37 @@ void onMatchTopLevelClass( /** * Called when NullAway first matches a particular method node. * - * @param analysis A reference to the running NullAway analysis. * @param tree The AST node for the method being matched. - * @param state The current visitor state. - * @param methodSymbol The method symbol for the method being matched. + * @param methodAnalysisContext The MethodAnalysisContext object */ - void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol); + void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext); /** * Called when NullAway first matches a particular method call-site. * - * @param analysis A reference to the running NullAway analysis. * @param tree The AST node for the method invocation (call-site) being matched. - * @param state The current visitor state. - * @param methodSymbol The method symbol for the method being called. + * @param methodAnalysisContext The MethodAnalysisContext object */ void onMatchMethodInvocation( - NullAway analysis, - MethodInvocationTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol); + MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext); /** * Called when NullAway first matches a particular lambda expression. * - * @param analysis A reference to the running NullAway analysis. * @param tree The AST node for the lambda expression being matched. - * @param state The current visitor state. - * @param methodSymbol The method symbol for the functional interface of the lambda being matched. + * @param methodAnalysisContext The MethodAnalysisContext object */ void onMatchLambdaExpression( - NullAway analysis, - LambdaExpressionTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol); + LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext); /** * Called when NullAway first matches a particular method reference expression * - * @param analysis A reference to the running NullAway analysis. * @param tree The AST node for the method reference expression being matched. - * @param state The current visitor state. - * @param methodSymbol The method symbol for the reference being matched. + * @param methodAnalysisContext The MethodAnalysisContext object */ void onMatchMethodReference( - NullAway analysis, - MemberReferenceTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol); + MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext); /** * Called when NullAway first matches a return statement. @@ -386,9 +368,6 @@ MethodInvocationNode onCFGBuildPhase1AfterVisitMethodInvocation( *

See {@link LibraryModels#castToNonNullMethods()} for more information about general * configuration of castToNonNull methods. * - * @param analysis A reference to the running NullAway analysis. - * @param state The current visitor state. - * @param methodSymbol The method symbol for the potential castToNonNull method. * @param actualParams The actual parameters from the invocation node * @param previousArgumentPosition The result computed by the previous handler in the chain, if * any. @@ -396,14 +375,13 @@ MethodInvocationNode onCFGBuildPhase1AfterVisitMethodInvocation( * value can be set only once through the full chain of handlers, with each handler deciding * whether to propagate or override the value previousArgumentPosition passed by the previous * handler in the chain. + * @param methodAnalysisContext The MethodAnalysisContext object */ @Nullable Integer castToNonNullArgumentPositionsForMethod( - NullAway analysis, - VisitorState state, - Symbol.MethodSymbol methodSymbol, List actualParams, - @Nullable Integer previousArgumentPosition); + @Nullable Integer previousArgumentPosition, + MethodAnalysisContext methodAnalysisContext); /** * Method to override the nullability of the upper bound for a generic type variable on a class. 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 7b5676984c..51d6f24b04 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java @@ -186,17 +186,19 @@ public boolean onOverrideMayBeNullExpr( @Override @Nullable public Integer castToNonNullArgumentPositionsForMethod( - NullAway analysis, - VisitorState state, - Symbol.MethodSymbol methodSymbol, List actualParams, - @Nullable Integer previousArgumentPosition) { - OptimizedLibraryModels optLibraryModels = getOptLibraryModels(state.context); - ImmutableSet newPositions = optLibraryModels.castToNonNullMethod(methodSymbol); + @Nullable Integer previousArgumentPosition, + MethodAnalysisContext methodAnalysisContext) { + OptimizedLibraryModels optLibraryModels = + getOptLibraryModels(methodAnalysisContext.getState().context); + ImmutableSet newPositions = + optLibraryModels.castToNonNullMethod(methodAnalysisContext.getMethodSymbol()); if (newPositions.size() > 1) { // Library models sanity check String qualifiedName = - ASTHelpers.enclosingClass(methodSymbol) + "." + methodSymbol.getSimpleName().toString(); + ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol()) + + "." + + methodAnalysisContext.getMethodSymbol().getSimpleName().toString(); throw new IllegalStateException( "Found multiple applicable castToNonNull library models for the same method signature: " + qualifiedName); diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java new file mode 100644 index 0000000000..5c1a9159a1 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java @@ -0,0 +1,43 @@ +package com.uber.nullaway.handlers; + +import com.google.errorprone.VisitorState; +import com.sun.tools.javac.code.Symbol.MethodSymbol; +import com.uber.nullaway.NullAway; + +public class MethodAnalysisContext { + private NullAway analysis; + + public NullAway getAnalysis() { + return analysis; + } + + public void setAnalysis(NullAway analysis) { + this.analysis = analysis; + } + + private VisitorState state; + + public VisitorState getState() { + return state; + } + + public void setState(VisitorState state) { + this.state = state; + } + + private MethodSymbol methodSymbol; + + public MethodSymbol getMethodSymbol() { + return methodSymbol; + } + + public void setMethodSymbol(MethodSymbol methodSymbol) { + this.methodSymbol = methodSymbol; + } + + public MethodAnalysisContext(NullAway analysis, VisitorState state, MethodSymbol methodSymbol) { + this.analysis = analysis; + this.state = state; + this.methodSymbol = 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 59ef183b29..43ae0be2bd 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java @@ -208,18 +208,16 @@ public void onMatchTopLevelClass( @Override public void onMatchMethodInvocation( - NullAway analysis, - MethodInvocationTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { Type receiverType = ASTHelpers.getReceiverType(tree); for (StreamTypeRecord streamType : models) { - if (streamType.matchesType(receiverType, state)) { + if (streamType.matchesType(receiverType, methodAnalysisContext.getState())) { // Build observable call chain buildObservableCallChain(tree); // Dispatch to code handling specific observer methods - if (streamType.isFilterMethod(methodSymbol) && methodSymbol.getParameters().length() == 1) { + if (streamType.isFilterMethod(methodAnalysisContext.getMethodSymbol()) + && methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { ExpressionTree argTree = tree.getArguments().get(0); if (argTree instanceof NewClassTree) { ClassTree annonClassBody = ((NewClassTree) argTree).getClassBody(); @@ -228,20 +226,22 @@ public void onMatchMethodInvocation( // for // filters. if (annonClassBody != null) { - handleFilterAnonClass(streamType, tree, annonClassBody, state); + handleFilterAnonClass( + streamType, tree, annonClassBody, methodAnalysisContext.getState()); } } else if (argTree instanceof LambdaExpressionTree) { LambdaExpressionTree lambdaTree = (LambdaExpressionTree) argTree; - handleFilterLambda(streamType, tree, lambdaTree, state); + handleFilterLambda(streamType, tree, lambdaTree, methodAnalysisContext.getState()); } - } else if (streamType.isMapMethod(methodSymbol) - && methodSymbol.getParameters().length() == 1) { + } else if (streamType.isMapMethod(methodAnalysisContext.getMethodSymbol()) + && methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { ExpressionTree argTree = tree.getArguments().get(0); if (argTree instanceof NewClassTree) { ClassTree annonClassBody = ((NewClassTree) argTree).getClassBody(); // Ensure that this `new B() ...` has a custom class body, otherwise, we skip for now. if (annonClassBody != null) { - MapLikeMethodRecord methodRecord = streamType.getMaplikeMethodRecord(methodSymbol); + MapLikeMethodRecord methodRecord = + streamType.getMaplikeMethodRecord(methodAnalysisContext.getMethodSymbol()); handleMapOrCollectAnonClassBody( methodRecord, annonClassBody, @@ -253,14 +253,14 @@ public void onMatchMethodInvocation( observableCallToInnerMethodOrLambda.put(tree, argTree); } } else { - if (methodSymbol.getParameters().length() == 1) { + if (methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { // We can have multiple CollectLikeMethodRecords for a single collect method, reflecting // the different possible collector factory methods whose result may be passed to a // collect call. At a single collect call site, at most one of these records will be // relevant. So, we loop through them all, but break out of the loop as soon as we find // one that matches. for (CollectLikeMethodRecord collectlikeMethodRecord : - streamType.getCollectlikeMethodRecords(methodSymbol)) { + streamType.getCollectlikeMethodRecords(methodAnalysisContext.getMethodSymbol())) { boolean handled = handleCollectCall(tree, collectlikeMethodRecord); if (handled) { break; @@ -415,8 +415,7 @@ private void handleMapOrCollectAnonClassBody( } @Override - public void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { + public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { if (mapOrCollectRecordToFilterMap.containsKey(tree)) { bodyToMethodOrLambda.put(tree.getBody(), tree); } @@ -424,17 +423,16 @@ public void onMatchMethod( @Override public void onMatchLambdaExpression( - NullAway analysis, - LambdaExpressionTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext) { if (filterMethodOrLambdaSet.contains(tree) && tree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) { expressionBodyToFilterLambda.put((ExpressionTree) tree.getBody(), tree); // Single expression lambda, onMatchReturn will not be triggered, force the dataflow analysis // here - AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state); - nullnessAnalysis.forceRunOnMethod(state.getPath(), state.context); + AccessPathNullnessAnalysis nullnessAnalysis = + methodAnalysisContext.getAnalysis().getNullnessAnalysis(methodAnalysisContext.getState()); + nullnessAnalysis.forceRunOnMethod( + methodAnalysisContext.getState().getPath(), methodAnalysisContext.getState().context); } if (mapOrCollectRecordToFilterMap.containsKey(tree)) { bodyToMethodOrLambda.put(tree.getBody(), tree); @@ -443,10 +441,7 @@ public void onMatchLambdaExpression( @Override public void onMatchMethodReference( - NullAway analysis, - MemberReferenceTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { + MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext) { MapOrCollectMethodToFilterInstanceRecord callInstanceRecord = mapOrCollectRecordToFilterMap.get(tree); if (callInstanceRecord != null && ((JCTree.JCMemberReference) tree).kind.isUnbound()) { @@ -458,12 +453,13 @@ public void onMatchMethodReference( "unexpected filterTree type " + filterTree.getClass() + " " - + state.getSourceForNode(filterTree)); + + methodAnalysisContext.getState().getSourceForNode(filterTree)); } NullnessStore filterNullnessStore = filterToNSMap.get(filterTree); if (filterNullnessStore == null) { throw new IllegalStateException( - "null filterNullStore for tree " + state.getSourceForNode(filterTree)); + "null filterNullStore for tree " + + methodAnalysisContext.getState().getSourceForNode(filterTree)); } for (AccessPath ap : filterNullnessStore.getAccessPathsWithValue(Nullness.NONNULL)) { // Find the access path corresponding to the current unbound method reference after binding @@ -475,7 +471,9 @@ public void onMatchMethodReference( // We are only looking for method APs continue; } - if (!element.getSimpleName().equals(methodSymbol.getSimpleName())) { + if (!element + .getSimpleName() + .equals(methodAnalysisContext.getMethodSymbol().getSimpleName())) { // Check for the name match continue; } @@ -487,7 +485,7 @@ public void onMatchMethodReference( // We found our method, and it was non-null when called inside the filter, so we mark the // return of the // method reference as non-null here - analysis.setComputedNullness(tree, Nullness.NONNULL); + methodAnalysisContext.getAnalysis().setComputedNullness(tree, Nullness.NONNULL); } } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java index d0386909d6..fa27e005a7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java @@ -35,9 +35,9 @@ import com.sun.tools.javac.code.Symbol; import com.uber.nullaway.Config; import com.uber.nullaway.ErrorMessage; -import com.uber.nullaway.NullAway; import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.BaseNoOpHandler; +import com.uber.nullaway.handlers.MethodAnalysisContext; /** * This Handler parses the jetbrains @Contract annotation and tries to check if the contract is @@ -58,8 +58,7 @@ public ContractCheckHandler(Config config) { } @Override - public void onMatchMethod( - NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { + public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { Symbol.MethodSymbol callee = ASTHelpers.getSymbol(tree); Preconditions.checkNotNull(callee); // Check to see if this method has an @Contract annotation @@ -73,8 +72,20 @@ public void onMatchMethod( String clause = clauses[0]; String[] antecedent = - getAntecedent(clause, tree, analysis, state, callee, tree.getParameters().size()); - String consequent = getConsequent(clause, tree, analysis, state, callee); + getAntecedent( + clause, + tree, + methodAnalysisContext.getAnalysis(), + methodAnalysisContext.getState(), + callee, + tree.getParameters().size()); + String consequent = + getConsequent( + clause, + tree, + methodAnalysisContext.getAnalysis(), + methodAnalysisContext.getState(), + callee); boolean supported = true; @@ -100,9 +111,11 @@ public void onMatchMethod( @Override public Void visitReturn(ReturnTree returnTree, Void unused) { - final VisitorState returnState = state.withPath(getCurrentPath()); + final VisitorState returnState = + methodAnalysisContext.getState().withPath(getCurrentPath()); final Nullness nullness = - analysis + methodAnalysisContext + .getAnalysis() .getNullnessAnalysis(returnState) .getNullnessForContractDataflow( new TreePath(returnState.getPath(), returnTree.getExpression()), @@ -146,19 +159,20 @@ public Void visitReturn(ReturnTree returnTree, Void unused) { } returnState.reportMatch( - analysis + methodAnalysisContext + .getAnalysis() .getErrorBuilder() .createErrorDescription( new ErrorMessage( ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, errorMessage), returnTree, - analysis.buildDescription(returnTree), + methodAnalysisContext.getAnalysis().buildDescription(returnTree), returnState, null)); } return super.visitReturn(returnTree, null); } - }.scan(state.getPath(), null); + }.scan(methodAnalysisContext.getState().getPath(), null); } } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java index bf2767c876..b669cc98a0 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java @@ -37,6 +37,7 @@ import com.uber.nullaway.dataflow.AccessPath; import com.uber.nullaway.dataflow.AccessPathNullnessPropagation; import com.uber.nullaway.handlers.AbstractFieldContractHandler; +import com.uber.nullaway.handlers.MethodAnalysisContext; import com.uber.nullaway.handlers.contract.ContractUtils; import java.util.Collections; import java.util.Iterator; @@ -70,19 +71,23 @@ public EnsuresNonNullHandler() { */ @Override protected boolean validateAnnotationSemantics( - NullAway analysis, VisitorState state, MethodTree tree, Symbol.MethodSymbol methodSymbol) { + MethodTree tree, MethodAnalysisContext methodAnalysisContext) { String message; if (tree.getBody() == null) { return true; } Set nonnullFieldsOfReceiverAtExit = - analysis - .getNullnessAnalysis(state) - .getNonnullFieldsOfReceiverAtExit(new TreePath(state.getPath(), tree), state.context) + methodAnalysisContext + .getAnalysis() + .getNullnessAnalysis(methodAnalysisContext.getState()) + .getNonnullFieldsOfReceiverAtExit( + new TreePath(methodAnalysisContext.getState().getPath(), tree), + methodAnalysisContext.getState().context) .stream() .map(e -> e.getSimpleName().toString()) .collect(Collectors.toSet()); - Set fieldNames = getAnnotationValueArray(methodSymbol, annotName, false); + Set fieldNames = + getAnnotationValueArray(methodAnalysisContext.getMethodSymbol(), annotName, false); if (fieldNames == null) { fieldNames = Collections.emptySet(); } @@ -92,20 +97,24 @@ protected boolean validateAnnotationSemantics( fieldNames.removeAll(nonnullFieldsOfReceiverAtExit); message = "method: " - + methodSymbol + + methodAnalysisContext.getMethodSymbol() + " is annotated with @EnsuresNonNull annotation, it indicates that all fields in the annotation parameter" + " must be guaranteed to be nonnull at exit point. However, the method's body fails to ensure this for the following fields: " + fieldNames; - state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(ErrorMessage.MessageTypes.POSTCONDITION_NOT_SATISFIED, message), - tree, - analysis.buildDescription(tree), - state, - null)); + methodAnalysisContext + .getState() + .reportMatch( + methodAnalysisContext + .getAnalysis() + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage( + ErrorMessage.MessageTypes.POSTCONDITION_NOT_SATISFIED, message), + tree, + methodAnalysisContext.getAnalysis().buildDescription(tree), + methodAnalysisContext.getState(), + null)); return false; } return true; diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java index 9c6e0206e4..263288009a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java @@ -40,6 +40,7 @@ import com.uber.nullaway.dataflow.AccessPath; import com.uber.nullaway.dataflow.NullnessStore; import com.uber.nullaway.handlers.AbstractFieldContractHandler; +import com.uber.nullaway.handlers.MethodAnalysisContext; import com.uber.nullaway.handlers.contract.ContractUtils; import java.util.Collections; import java.util.Iterator; @@ -71,7 +72,7 @@ public RequiresNonNullHandler() { /** All methods can add the precondition of {@code RequiresNonNull}. */ @Override protected boolean validateAnnotationSemantics( - NullAway analysis, VisitorState state, MethodTree tree, Symbol.MethodSymbol methodSymbol) { + MethodTree tree, MethodAnalysisContext methodAnalysisContext) { return true; } @@ -129,20 +130,21 @@ protected void validateOverridingRules( */ @Override public void onMatchMethodInvocation( - NullAway analysis, - MethodInvocationTree tree, - VisitorState state, - Symbol.MethodSymbol methodSymbol) { - Set fieldNames = getAnnotationValueArray(methodSymbol, annotName, false); + MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { + Set fieldNames = + getAnnotationValueArray(methodAnalysisContext.getMethodSymbol(), annotName, false); if (fieldNames == null) { - super.onMatchMethodInvocation(analysis, tree, state, methodSymbol); + super.onMatchMethodInvocation(tree, methodAnalysisContext); return; } fieldNames = ContractUtils.trimReceivers(fieldNames); for (String fieldName : fieldNames) { - Symbol.ClassSymbol classSymbol = ASTHelpers.enclosingClass(methodSymbol); + Symbol.ClassSymbol classSymbol = + ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol()); Preconditions.checkNotNull( - classSymbol, "Could not find the enclosing class for method symbol: " + methodSymbol); + classSymbol, + "Could not find the enclosing class for method symbol: " + + methodAnalysisContext.getMethodSymbol()); VariableElement field = getInstanceFieldOfClass(classSymbol, fieldName); if (field == null) { // we will report an error on the method declaration @@ -150,22 +152,31 @@ public void onMatchMethodInvocation( } ExpressionTree methodSelectTree = tree.getMethodSelect(); Nullness nullness = - analysis - .getNullnessAnalysis(state) + methodAnalysisContext + .getAnalysis() + .getNullnessAnalysis(methodAnalysisContext.getState()) .getNullnessOfFieldForReceiverTree( - state.getPath(), state.context, methodSelectTree, field, true); + methodAnalysisContext.getState().getPath(), + methodAnalysisContext.getState().context, + methodSelectTree, + field, + true); if (NullabilityUtil.nullnessToBool(nullness)) { String message = "Expected field " + fieldName + " to be non-null at call site"; - state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(ErrorMessage.MessageTypes.PRECONDITION_NOT_SATISFIED, message), - tree, - analysis.buildDescription(tree), - state, - null)); + methodAnalysisContext + .getState() + .reportMatch( + methodAnalysisContext + .getAnalysis() + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage( + ErrorMessage.MessageTypes.PRECONDITION_NOT_SATISFIED, message), + tree, + methodAnalysisContext.getAnalysis().buildDescription(tree), + methodAnalysisContext.getState(), + null)); } } } From c6c924e85437b566e384067eeccab32b1f8e1d11 Mon Sep 17 00:00:00 2001 From: tschoemaker Date: Wed, 12 Jun 2024 00:47:25 +0200 Subject: [PATCH 2/5] simplified multiple getter calls, renaming of getters, and added equals, hashCode, and toString --- .../AbstractFieldContractHandler.java | 86 ++++++++----------- .../handlers/LibraryModelsHandler.java | 10 +-- .../handlers/MethodAnalysisContext.java | 72 ++++++++++++---- .../handlers/StreamNullabilityPropagator.java | 40 ++++----- .../contract/ContractCheckHandler.java | 32 +++---- .../fieldcontract/EnsuresNonNullHandler.java | 38 ++++---- .../fieldcontract/RequiresNonNullHandler.java | 47 ++++------ 7 files changed, 164 insertions(+), 161 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java index eb7d29f7e8..18095f68ac 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java @@ -65,9 +65,11 @@ protected AbstractFieldContractHandler(String annotName) { */ @Override public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { + + Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); + VisitorState visitorState = methodAnalysisContext.state(); Set annotationContent = - NullabilityUtil.getAnnotationValueArray( - methodAnalysisContext.getMethodSymbol(), annotName, false); + NullabilityUtil.getAnnotationValueArray(methodSymbol, annotName, false); boolean isAnnotated = annotationContent != null; boolean isValid = isAnnotated @@ -78,8 +80,7 @@ && validateAnnotationSyntax( return; } Symbol.MethodSymbol closestOverriddenMethod = - NullabilityUtil.getClosestOverriddenMethod( - methodAnalysisContext.getMethodSymbol(), methodAnalysisContext.getState().getTypes()); + NullabilityUtil.getClosestOverriddenMethod(methodSymbol, visitorState.getTypes()); if (closestOverriddenMethod == null) { return; } @@ -90,11 +91,7 @@ && validateAnnotationSyntax( fieldNames = Collections.emptySet(); } validateOverridingRules( - fieldNames, - methodAnalysisContext.getAnalysis(), - methodAnalysisContext.getState(), - tree, - closestOverriddenMethod); + fieldNames, methodAnalysisContext.analysis(), visitorState, tree, closestOverriddenMethod); super.onMatchMethod(tree, methodAnalysisContext); } @@ -147,24 +144,23 @@ protected abstract boolean validateAnnotationSemantics( protected boolean validateAnnotationSyntax( Set content, MethodTree tree, MethodAnalysisContext methodAnalysisContext) { String message; + VisitorState visitorState = methodAnalysisContext.state(); + NullAway analysis = methodAnalysisContext.analysis(); if (content.isEmpty()) { // we should not allow useless annotations. message = "empty @" + annotName + " is the default precondition for every method, please remove it."; - methodAnalysisContext - .getState() - .reportMatch( - methodAnalysisContext - .getAnalysis() - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - methodAnalysisContext.getAnalysis().buildDescription(tree), - methodAnalysisContext.getState(), - null)); + visitorState.reportMatch( + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + analysis.buildDescription(tree), + visitorState, + null)); return false; } else { for (String fieldName : content) { @@ -177,26 +173,23 @@ protected boolean validateAnnotationSyntax( + fieldName + " is not supported"; - methodAnalysisContext - .getState() - .reportMatch( - methodAnalysisContext - .getAnalysis() - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage( - ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - methodAnalysisContext.getAnalysis().buildDescription(tree), - methodAnalysisContext.getState(), - null)); + visitorState.reportMatch( + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage( + ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + analysis.buildDescription(tree), + visitorState, + null)); return false; } else { fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1); } } Symbol.ClassSymbol classSymbol = - castToNonNull(ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol())); + castToNonNull(ASTHelpers.enclosingClass(methodAnalysisContext.methodSymbol())); VariableElement field = getInstanceFieldOfClass(classSymbol, fieldName); if (field == null) { message = @@ -206,19 +199,16 @@ protected boolean validateAnnotationSyntax( + fieldName + " in class " + classSymbol.getSimpleName(); - methodAnalysisContext - .getState() - .reportMatch( - methodAnalysisContext - .getAnalysis() - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage( - ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), - tree, - methodAnalysisContext.getAnalysis().buildDescription(tree), - methodAnalysisContext.getState(), - null)); + + visitorState.reportMatch( + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), + tree, + analysis.buildDescription(tree), + visitorState, + null)); return false; } } 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 51d6f24b04..3ac3347a77 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java @@ -189,16 +189,14 @@ public Integer castToNonNullArgumentPositionsForMethod( List actualParams, @Nullable Integer previousArgumentPosition, MethodAnalysisContext methodAnalysisContext) { + Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); OptimizedLibraryModels optLibraryModels = - getOptLibraryModels(methodAnalysisContext.getState().context); - ImmutableSet newPositions = - optLibraryModels.castToNonNullMethod(methodAnalysisContext.getMethodSymbol()); + getOptLibraryModels(methodAnalysisContext.state().context); + ImmutableSet newPositions = optLibraryModels.castToNonNullMethod(methodSymbol); if (newPositions.size() > 1) { // Library models sanity check String qualifiedName = - ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol()) - + "." - + methodAnalysisContext.getMethodSymbol().getSimpleName().toString(); + ASTHelpers.enclosingClass(methodSymbol) + "." + methodSymbol.getSimpleName().toString(); throw new IllegalStateException( "Found multiple applicable castToNonNull library models for the same method signature: " + qualifiedName); diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java index 5c1a9159a1..0ab8c32096 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java @@ -1,38 +1,78 @@ +/* + * Copyright (c) 2024 Uber Technologies, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.uber.nullaway.handlers; import com.google.errorprone.VisitorState; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.uber.nullaway.NullAway; +import java.util.Objects; public class MethodAnalysisContext { - private NullAway analysis; + private final NullAway analysis; + private final MethodSymbol methodSymbol; + private final VisitorState state; - public NullAway getAnalysis() { + public NullAway analysis() { return analysis; } - public void setAnalysis(NullAway analysis) { - this.analysis = analysis; - } - - private VisitorState state; - - public VisitorState getState() { + public VisitorState state() { return state; } - public void setState(VisitorState state) { - this.state = state; + public MethodSymbol methodSymbol() { + return methodSymbol; } - private MethodSymbol methodSymbol; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || !(o instanceof MethodAnalysisContext)) { + return false; + } + MethodAnalysisContext that = (MethodAnalysisContext) o; + return Objects.equals(analysis, that.analysis) + && Objects.equals(state, that.state) + && Objects.equals(methodSymbol, that.methodSymbol); + } - public MethodSymbol getMethodSymbol() { - return methodSymbol; + @Override + public int hashCode() { + return Objects.hash(analysis, state, methodSymbol); } - public void setMethodSymbol(MethodSymbol methodSymbol) { - this.methodSymbol = methodSymbol; + @Override + public String toString() { + return "MethodAnalysisContext{" + + "analysis=" + + analysis + + ", state=" + + state + + ", methodSymbol=" + + methodSymbol + + '}'; } public MethodAnalysisContext(NullAway analysis, VisitorState state, MethodSymbol 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 43ae0be2bd..f43a543db3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java @@ -209,15 +209,17 @@ public void onMatchTopLevelClass( @Override public void onMatchMethodInvocation( MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { + + Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); + VisitorState visitorState = methodAnalysisContext.state(); Type receiverType = ASTHelpers.getReceiverType(tree); for (StreamTypeRecord streamType : models) { - if (streamType.matchesType(receiverType, methodAnalysisContext.getState())) { + if (streamType.matchesType(receiverType, visitorState)) { // Build observable call chain buildObservableCallChain(tree); // Dispatch to code handling specific observer methods - if (streamType.isFilterMethod(methodAnalysisContext.getMethodSymbol()) - && methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { + if (streamType.isFilterMethod(methodSymbol) && methodSymbol.getParameters().length() == 1) { ExpressionTree argTree = tree.getArguments().get(0); if (argTree instanceof NewClassTree) { ClassTree annonClassBody = ((NewClassTree) argTree).getClassBody(); @@ -226,22 +228,20 @@ public void onMatchMethodInvocation( // for // filters. if (annonClassBody != null) { - handleFilterAnonClass( - streamType, tree, annonClassBody, methodAnalysisContext.getState()); + handleFilterAnonClass(streamType, tree, annonClassBody, visitorState); } } else if (argTree instanceof LambdaExpressionTree) { LambdaExpressionTree lambdaTree = (LambdaExpressionTree) argTree; - handleFilterLambda(streamType, tree, lambdaTree, methodAnalysisContext.getState()); + handleFilterLambda(streamType, tree, lambdaTree, visitorState); } - } else if (streamType.isMapMethod(methodAnalysisContext.getMethodSymbol()) - && methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { + } else if (streamType.isMapMethod(methodSymbol) + && methodSymbol.getParameters().length() == 1) { ExpressionTree argTree = tree.getArguments().get(0); if (argTree instanceof NewClassTree) { ClassTree annonClassBody = ((NewClassTree) argTree).getClassBody(); // Ensure that this `new B() ...` has a custom class body, otherwise, we skip for now. if (annonClassBody != null) { - MapLikeMethodRecord methodRecord = - streamType.getMaplikeMethodRecord(methodAnalysisContext.getMethodSymbol()); + MapLikeMethodRecord methodRecord = streamType.getMaplikeMethodRecord(methodSymbol); handleMapOrCollectAnonClassBody( methodRecord, annonClassBody, @@ -253,14 +253,14 @@ public void onMatchMethodInvocation( observableCallToInnerMethodOrLambda.put(tree, argTree); } } else { - if (methodAnalysisContext.getMethodSymbol().getParameters().length() == 1) { + if (methodSymbol.getParameters().length() == 1) { // We can have multiple CollectLikeMethodRecords for a single collect method, reflecting // the different possible collector factory methods whose result may be passed to a // collect call. At a single collect call site, at most one of these records will be // relevant. So, we loop through them all, but break out of the loop as soon as we find // one that matches. for (CollectLikeMethodRecord collectlikeMethodRecord : - streamType.getCollectlikeMethodRecords(methodAnalysisContext.getMethodSymbol())) { + streamType.getCollectlikeMethodRecords(methodSymbol)) { boolean handled = handleCollectCall(tree, collectlikeMethodRecord); if (handled) { break; @@ -424,15 +424,15 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC @Override public void onMatchLambdaExpression( LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext) { + VisitorState visitorState = methodAnalysisContext.state(); if (filterMethodOrLambdaSet.contains(tree) && tree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) { expressionBodyToFilterLambda.put((ExpressionTree) tree.getBody(), tree); // Single expression lambda, onMatchReturn will not be triggered, force the dataflow analysis // here AccessPathNullnessAnalysis nullnessAnalysis = - methodAnalysisContext.getAnalysis().getNullnessAnalysis(methodAnalysisContext.getState()); - nullnessAnalysis.forceRunOnMethod( - methodAnalysisContext.getState().getPath(), methodAnalysisContext.getState().context); + methodAnalysisContext.analysis().getNullnessAnalysis(visitorState); + nullnessAnalysis.forceRunOnMethod(visitorState.getPath(), visitorState.context); } if (mapOrCollectRecordToFilterMap.containsKey(tree)) { bodyToMethodOrLambda.put(tree.getBody(), tree); @@ -442,6 +442,7 @@ public void onMatchLambdaExpression( @Override public void onMatchMethodReference( MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext) { + VisitorState visitorState = methodAnalysisContext.state(); MapOrCollectMethodToFilterInstanceRecord callInstanceRecord = mapOrCollectRecordToFilterMap.get(tree); if (callInstanceRecord != null && ((JCTree.JCMemberReference) tree).kind.isUnbound()) { @@ -453,13 +454,12 @@ public void onMatchMethodReference( "unexpected filterTree type " + filterTree.getClass() + " " - + methodAnalysisContext.getState().getSourceForNode(filterTree)); + + visitorState.getSourceForNode(filterTree)); } NullnessStore filterNullnessStore = filterToNSMap.get(filterTree); if (filterNullnessStore == null) { throw new IllegalStateException( - "null filterNullStore for tree " - + methodAnalysisContext.getState().getSourceForNode(filterTree)); + "null filterNullStore for tree " + visitorState.getSourceForNode(filterTree)); } for (AccessPath ap : filterNullnessStore.getAccessPathsWithValue(Nullness.NONNULL)) { // Find the access path corresponding to the current unbound method reference after binding @@ -473,7 +473,7 @@ public void onMatchMethodReference( } if (!element .getSimpleName() - .equals(methodAnalysisContext.getMethodSymbol().getSimpleName())) { + .equals(methodAnalysisContext.methodSymbol().getSimpleName())) { // Check for the name match continue; } @@ -485,7 +485,7 @@ public void onMatchMethodReference( // We found our method, and it was non-null when called inside the filter, so we mark the // return of the // method reference as non-null here - methodAnalysisContext.getAnalysis().setComputedNullness(tree, Nullness.NONNULL); + methodAnalysisContext.analysis().setComputedNullness(tree, Nullness.NONNULL); } } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java index fa27e005a7..581f0e2777 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java @@ -35,6 +35,7 @@ import com.sun.tools.javac.code.Symbol; import com.uber.nullaway.Config; import com.uber.nullaway.ErrorMessage; +import com.uber.nullaway.NullAway; import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.BaseNoOpHandler; import com.uber.nullaway.handlers.MethodAnalysisContext; @@ -71,21 +72,11 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC } String clause = clauses[0]; + NullAway analysis = methodAnalysisContext.analysis(); + VisitorState visitorState = methodAnalysisContext.state(); String[] antecedent = - getAntecedent( - clause, - tree, - methodAnalysisContext.getAnalysis(), - methodAnalysisContext.getState(), - callee, - tree.getParameters().size()); - String consequent = - getConsequent( - clause, - tree, - methodAnalysisContext.getAnalysis(), - methodAnalysisContext.getState(), - callee); + getAntecedent(clause, tree, analysis, visitorState, callee, tree.getParameters().size()); + String consequent = getConsequent(clause, tree, analysis, visitorState, callee); boolean supported = true; @@ -111,11 +102,9 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC @Override public Void visitReturn(ReturnTree returnTree, Void unused) { - final VisitorState returnState = - methodAnalysisContext.getState().withPath(getCurrentPath()); + final VisitorState returnState = visitorState.withPath(getCurrentPath()); final Nullness nullness = - methodAnalysisContext - .getAnalysis() + analysis .getNullnessAnalysis(returnState) .getNullnessForContractDataflow( new TreePath(returnState.getPath(), returnTree.getExpression()), @@ -159,20 +148,19 @@ public Void visitReturn(ReturnTree returnTree, Void unused) { } returnState.reportMatch( - methodAnalysisContext - .getAnalysis() + analysis .getErrorBuilder() .createErrorDescription( new ErrorMessage( ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, errorMessage), returnTree, - methodAnalysisContext.getAnalysis().buildDescription(returnTree), + analysis.buildDescription(returnTree), returnState, null)); } return super.visitReturn(returnTree, null); } - }.scan(methodAnalysisContext.getState().getPath(), null); + }.scan(visitorState.getPath(), null); } } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java index b669cc98a0..d56afa1b0f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java @@ -72,22 +72,22 @@ public EnsuresNonNullHandler() { @Override protected boolean validateAnnotationSemantics( MethodTree tree, MethodAnalysisContext methodAnalysisContext) { + NullAway analysis = methodAnalysisContext.analysis(); + VisitorState visitorState = methodAnalysisContext.state(); + Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); String message; if (tree.getBody() == null) { return true; } Set nonnullFieldsOfReceiverAtExit = - methodAnalysisContext - .getAnalysis() - .getNullnessAnalysis(methodAnalysisContext.getState()) + analysis + .getNullnessAnalysis(visitorState) .getNonnullFieldsOfReceiverAtExit( - new TreePath(methodAnalysisContext.getState().getPath(), tree), - methodAnalysisContext.getState().context) + new TreePath(visitorState.getPath(), tree), visitorState.context) .stream() .map(e -> e.getSimpleName().toString()) .collect(Collectors.toSet()); - Set fieldNames = - getAnnotationValueArray(methodAnalysisContext.getMethodSymbol(), annotName, false); + Set fieldNames = getAnnotationValueArray(methodSymbol, annotName, false); if (fieldNames == null) { fieldNames = Collections.emptySet(); } @@ -97,24 +97,20 @@ protected boolean validateAnnotationSemantics( fieldNames.removeAll(nonnullFieldsOfReceiverAtExit); message = "method: " - + methodAnalysisContext.getMethodSymbol() + + methodSymbol + " is annotated with @EnsuresNonNull annotation, it indicates that all fields in the annotation parameter" + " must be guaranteed to be nonnull at exit point. However, the method's body fails to ensure this for the following fields: " + fieldNames; - methodAnalysisContext - .getState() - .reportMatch( - methodAnalysisContext - .getAnalysis() - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage( - ErrorMessage.MessageTypes.POSTCONDITION_NOT_SATISFIED, message), - tree, - methodAnalysisContext.getAnalysis().buildDescription(tree), - methodAnalysisContext.getState(), - null)); + visitorState.reportMatch( + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(ErrorMessage.MessageTypes.POSTCONDITION_NOT_SATISFIED, message), + tree, + analysis.buildDescription(tree), + visitorState, + null)); return false; } return true; diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java index 263288009a..aad86678c6 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java @@ -131,20 +131,20 @@ protected void validateOverridingRules( @Override public void onMatchMethodInvocation( MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { - Set fieldNames = - getAnnotationValueArray(methodAnalysisContext.getMethodSymbol(), annotName, false); + + VisitorState visitorState = methodAnalysisContext.state(); + Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); + NullAway analysis = methodAnalysisContext.analysis(); + Set fieldNames = getAnnotationValueArray(methodSymbol, annotName, false); if (fieldNames == null) { super.onMatchMethodInvocation(tree, methodAnalysisContext); return; } fieldNames = ContractUtils.trimReceivers(fieldNames); for (String fieldName : fieldNames) { - Symbol.ClassSymbol classSymbol = - ASTHelpers.enclosingClass(methodAnalysisContext.getMethodSymbol()); + Symbol.ClassSymbol classSymbol = ASTHelpers.enclosingClass(methodSymbol); Preconditions.checkNotNull( - classSymbol, - "Could not find the enclosing class for method symbol: " - + methodAnalysisContext.getMethodSymbol()); + classSymbol, "Could not find the enclosing class for method symbol: " + methodSymbol); VariableElement field = getInstanceFieldOfClass(classSymbol, fieldName); if (field == null) { // we will report an error on the method declaration @@ -152,31 +152,22 @@ public void onMatchMethodInvocation( } ExpressionTree methodSelectTree = tree.getMethodSelect(); Nullness nullness = - methodAnalysisContext - .getAnalysis() - .getNullnessAnalysis(methodAnalysisContext.getState()) + analysis + .getNullnessAnalysis(visitorState) .getNullnessOfFieldForReceiverTree( - methodAnalysisContext.getState().getPath(), - methodAnalysisContext.getState().context, - methodSelectTree, - field, - true); + visitorState.getPath(), visitorState.context, methodSelectTree, field, true); if (NullabilityUtil.nullnessToBool(nullness)) { String message = "Expected field " + fieldName + " to be non-null at call site"; - methodAnalysisContext - .getState() - .reportMatch( - methodAnalysisContext - .getAnalysis() - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage( - ErrorMessage.MessageTypes.PRECONDITION_NOT_SATISFIED, message), - tree, - methodAnalysisContext.getAnalysis().buildDescription(tree), - methodAnalysisContext.getState(), - null)); + visitorState.reportMatch( + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(ErrorMessage.MessageTypes.PRECONDITION_NOT_SATISFIED, message), + tree, + analysis.buildDescription(tree), + visitorState, + null)); } } } From 8186a8845da384445443a7f1fce5f694e3ae4c04 Mon Sep 17 00:00:00 2001 From: tschoemaker Date: Mon, 17 Jun 2024 11:13:39 +0200 Subject: [PATCH 3/5] renamed visitorState to state and used better equals operation --- .../AbstractFieldContractHandler.java | 20 +++++++++---------- .../handlers/MethodAnalysisContext.java | 2 +- .../handlers/StreamNullabilityPropagator.java | 20 +++++++++---------- .../contract/ContractCheckHandler.java | 10 +++++----- .../fieldcontract/EnsuresNonNullHandler.java | 11 +++++----- .../fieldcontract/RequiresNonNullHandler.java | 10 +++++----- 6 files changed, 36 insertions(+), 37 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java index 18095f68ac..831d633359 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/AbstractFieldContractHandler.java @@ -67,7 +67,7 @@ protected AbstractFieldContractHandler(String annotName) { public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisContext) { Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); Set annotationContent = NullabilityUtil.getAnnotationValueArray(methodSymbol, annotName, false); boolean isAnnotated = annotationContent != null; @@ -80,7 +80,7 @@ && validateAnnotationSyntax( return; } Symbol.MethodSymbol closestOverriddenMethod = - NullabilityUtil.getClosestOverriddenMethod(methodSymbol, visitorState.getTypes()); + NullabilityUtil.getClosestOverriddenMethod(methodSymbol, state.getTypes()); if (closestOverriddenMethod == null) { return; } @@ -91,7 +91,7 @@ && validateAnnotationSyntax( fieldNames = Collections.emptySet(); } validateOverridingRules( - fieldNames, methodAnalysisContext.analysis(), visitorState, tree, closestOverriddenMethod); + fieldNames, methodAnalysisContext.analysis(), state, tree, closestOverriddenMethod); super.onMatchMethod(tree, methodAnalysisContext); } @@ -144,7 +144,7 @@ protected abstract boolean validateAnnotationSemantics( protected boolean validateAnnotationSyntax( Set content, MethodTree tree, MethodAnalysisContext methodAnalysisContext) { String message; - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); NullAway analysis = methodAnalysisContext.analysis(); if (content.isEmpty()) { // we should not allow useless annotations. @@ -152,14 +152,14 @@ protected boolean validateAnnotationSyntax( "empty @" + annotName + " is the default precondition for every method, please remove it."; - visitorState.reportMatch( + state.reportMatch( analysis .getErrorBuilder() .createErrorDescription( new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), tree, analysis.buildDescription(tree), - visitorState, + state, null)); return false; } else { @@ -173,7 +173,7 @@ protected boolean validateAnnotationSyntax( + fieldName + " is not supported"; - visitorState.reportMatch( + state.reportMatch( analysis .getErrorBuilder() .createErrorDescription( @@ -181,7 +181,7 @@ protected boolean validateAnnotationSyntax( ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), tree, analysis.buildDescription(tree), - visitorState, + state, null)); return false; } else { @@ -200,14 +200,14 @@ protected boolean validateAnnotationSyntax( + " in class " + classSymbol.getSimpleName(); - visitorState.reportMatch( + state.reportMatch( analysis .getErrorBuilder() .createErrorDescription( new ErrorMessage(ErrorMessage.MessageTypes.ANNOTATION_VALUE_INVALID, message), tree, analysis.buildDescription(tree), - visitorState, + state, null)); return false; } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java index 0ab8c32096..e8455ddb76 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java @@ -53,7 +53,7 @@ public boolean equals(Object o) { return false; } MethodAnalysisContext that = (MethodAnalysisContext) o; - return Objects.equals(analysis, that.analysis) + return analysis.equals(that.analysis) && Objects.equals(state, that.state) && Objects.equals(methodSymbol, that.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 f43a543db3..4d7b702e48 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/StreamNullabilityPropagator.java @@ -211,10 +211,10 @@ public void onMatchMethodInvocation( MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); Type receiverType = ASTHelpers.getReceiverType(tree); for (StreamTypeRecord streamType : models) { - if (streamType.matchesType(receiverType, visitorState)) { + if (streamType.matchesType(receiverType, state)) { // Build observable call chain buildObservableCallChain(tree); @@ -228,11 +228,11 @@ public void onMatchMethodInvocation( // for // filters. if (annonClassBody != null) { - handleFilterAnonClass(streamType, tree, annonClassBody, visitorState); + handleFilterAnonClass(streamType, tree, annonClassBody, state); } } else if (argTree instanceof LambdaExpressionTree) { LambdaExpressionTree lambdaTree = (LambdaExpressionTree) argTree; - handleFilterLambda(streamType, tree, lambdaTree, visitorState); + handleFilterLambda(streamType, tree, lambdaTree, state); } } else if (streamType.isMapMethod(methodSymbol) && methodSymbol.getParameters().length() == 1) { @@ -424,15 +424,15 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC @Override public void onMatchLambdaExpression( LambdaExpressionTree tree, MethodAnalysisContext methodAnalysisContext) { - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); if (filterMethodOrLambdaSet.contains(tree) && tree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) { expressionBodyToFilterLambda.put((ExpressionTree) tree.getBody(), tree); // Single expression lambda, onMatchReturn will not be triggered, force the dataflow analysis // here AccessPathNullnessAnalysis nullnessAnalysis = - methodAnalysisContext.analysis().getNullnessAnalysis(visitorState); - nullnessAnalysis.forceRunOnMethod(visitorState.getPath(), visitorState.context); + methodAnalysisContext.analysis().getNullnessAnalysis(state); + nullnessAnalysis.forceRunOnMethod(state.getPath(), state.context); } if (mapOrCollectRecordToFilterMap.containsKey(tree)) { bodyToMethodOrLambda.put(tree.getBody(), tree); @@ -442,7 +442,7 @@ public void onMatchLambdaExpression( @Override public void onMatchMethodReference( MemberReferenceTree tree, MethodAnalysisContext methodAnalysisContext) { - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); MapOrCollectMethodToFilterInstanceRecord callInstanceRecord = mapOrCollectRecordToFilterMap.get(tree); if (callInstanceRecord != null && ((JCTree.JCMemberReference) tree).kind.isUnbound()) { @@ -454,12 +454,12 @@ public void onMatchMethodReference( "unexpected filterTree type " + filterTree.getClass() + " " - + visitorState.getSourceForNode(filterTree)); + + state.getSourceForNode(filterTree)); } NullnessStore filterNullnessStore = filterToNSMap.get(filterTree); if (filterNullnessStore == null) { throw new IllegalStateException( - "null filterNullStore for tree " + visitorState.getSourceForNode(filterTree)); + "null filterNullStore for tree " + state.getSourceForNode(filterTree)); } for (AccessPath ap : filterNullnessStore.getAccessPathsWithValue(Nullness.NONNULL)) { // Find the access path corresponding to the current unbound method reference after binding diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java index 581f0e2777..20a4b9190b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/ContractCheckHandler.java @@ -73,10 +73,10 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC String clause = clauses[0]; NullAway analysis = methodAnalysisContext.analysis(); - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); String[] antecedent = - getAntecedent(clause, tree, analysis, visitorState, callee, tree.getParameters().size()); - String consequent = getConsequent(clause, tree, analysis, visitorState, callee); + getAntecedent(clause, tree, analysis, state, callee, tree.getParameters().size()); + String consequent = getConsequent(clause, tree, analysis, state, callee); boolean supported = true; @@ -102,7 +102,7 @@ public void onMatchMethod(MethodTree tree, MethodAnalysisContext methodAnalysisC @Override public Void visitReturn(ReturnTree returnTree, Void unused) { - final VisitorState returnState = visitorState.withPath(getCurrentPath()); + final VisitorState returnState = state.withPath(getCurrentPath()); final Nullness nullness = analysis .getNullnessAnalysis(returnState) @@ -160,7 +160,7 @@ public Void visitReturn(ReturnTree returnTree, Void unused) { } return super.visitReturn(returnTree, null); } - }.scan(visitorState.getPath(), null); + }.scan(state.getPath(), null); } } } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java index d56afa1b0f..106abd949e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/EnsuresNonNullHandler.java @@ -73,7 +73,7 @@ public EnsuresNonNullHandler() { protected boolean validateAnnotationSemantics( MethodTree tree, MethodAnalysisContext methodAnalysisContext) { NullAway analysis = methodAnalysisContext.analysis(); - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); String message; if (tree.getBody() == null) { @@ -81,9 +81,8 @@ protected boolean validateAnnotationSemantics( } Set nonnullFieldsOfReceiverAtExit = analysis - .getNullnessAnalysis(visitorState) - .getNonnullFieldsOfReceiverAtExit( - new TreePath(visitorState.getPath(), tree), visitorState.context) + .getNullnessAnalysis(state) + .getNonnullFieldsOfReceiverAtExit(new TreePath(state.getPath(), tree), state.context) .stream() .map(e -> e.getSimpleName().toString()) .collect(Collectors.toSet()); @@ -102,14 +101,14 @@ protected boolean validateAnnotationSemantics( + " must be guaranteed to be nonnull at exit point. However, the method's body fails to ensure this for the following fields: " + fieldNames; - visitorState.reportMatch( + state.reportMatch( analysis .getErrorBuilder() .createErrorDescription( new ErrorMessage(ErrorMessage.MessageTypes.POSTCONDITION_NOT_SATISFIED, message), tree, analysis.buildDescription(tree), - visitorState, + state, null)); return false; } diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java index aad86678c6..113318ef3f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/contract/fieldcontract/RequiresNonNullHandler.java @@ -132,7 +132,7 @@ protected void validateOverridingRules( public void onMatchMethodInvocation( MethodInvocationTree tree, MethodAnalysisContext methodAnalysisContext) { - VisitorState visitorState = methodAnalysisContext.state(); + VisitorState state = methodAnalysisContext.state(); Symbol.MethodSymbol methodSymbol = methodAnalysisContext.methodSymbol(); NullAway analysis = methodAnalysisContext.analysis(); Set fieldNames = getAnnotationValueArray(methodSymbol, annotName, false); @@ -153,20 +153,20 @@ public void onMatchMethodInvocation( ExpressionTree methodSelectTree = tree.getMethodSelect(); Nullness nullness = analysis - .getNullnessAnalysis(visitorState) + .getNullnessAnalysis(state) .getNullnessOfFieldForReceiverTree( - visitorState.getPath(), visitorState.context, methodSelectTree, field, true); + state.getPath(), state.context, methodSelectTree, field, true); if (NullabilityUtil.nullnessToBool(nullness)) { String message = "Expected field " + fieldName + " to be non-null at call site"; - visitorState.reportMatch( + state.reportMatch( analysis .getErrorBuilder() .createErrorDescription( new ErrorMessage(ErrorMessage.MessageTypes.PRECONDITION_NOT_SATISFIED, message), tree, analysis.buildDescription(tree), - visitorState, + state, null)); } } From d976096cc45791d257906c90b855a45098683d7f Mon Sep 17 00:00:00 2001 From: tschoemaker Date: Mon, 17 Jun 2024 11:17:18 +0200 Subject: [PATCH 4/5] applied better equal operation on other fields --- .../com/uber/nullaway/handlers/MethodAnalysisContext.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java index e8455ddb76..38de586199 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java @@ -54,8 +54,8 @@ public boolean equals(Object o) { } MethodAnalysisContext that = (MethodAnalysisContext) o; return analysis.equals(that.analysis) - && Objects.equals(state, that.state) - && Objects.equals(methodSymbol, that.methodSymbol); + && state.equals(that.state) + && methodSymbol.equals(that.methodSymbol); } @Override From bbedf7b4b728bb01c9d23e71a15272e321871647 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Mon, 17 Jun 2024 10:48:49 -0700 Subject: [PATCH 5/5] javadoc --- .../com/uber/nullaway/handlers/MethodAnalysisContext.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java index 38de586199..63a9e46a26 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/MethodAnalysisContext.java @@ -27,6 +27,10 @@ import com.uber.nullaway.NullAway; import java.util.Objects; +/** + * Context object for checks on methods. Contains the {@link NullAway} instance, the {@link + * MethodSymbol} for the method being analyzed, and the {@link VisitorState} for the analysis. + */ public class MethodAnalysisContext { private final NullAway analysis; private final MethodSymbol methodSymbol;