Skip to content

Commit

Permalink
Suppress boxed Boolean warnings on @nonnull parameters.
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasz-tylenda-sonarsource committed Nov 19, 2024
1 parent 708fe30 commit 1049b38
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package checks;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
Expand Down Expand Up @@ -725,4 +727,52 @@ void testBoxedValue(Boolean value) {
}
}

// Allow suppressing warnings caused by generic parameters,
// see SONARJAVA-5184.
public void lambdaParameterAnnotations() {
List<Boolean> xs = new ArrayList<>();
xs.add(true);

xs.forEach(b -> {
if (b) { // Noncompliant
foo();
} else {
bar();
}
});

xs.forEach((Boolean b) -> {
if (b) { // Noncompliant
foo();
} else {
bar();
}
});

xs.forEach((@NonNull Boolean b) -> {
if (b) {
foo();
} else {
bar();
}
});

// Suppressing warnings on @NonNull Booleans works too and we like it.

Boolean badBoolean = getSurprizeBoxedBoolean();

if(badBoolean) { // Noncompliant
foo();
} else {
bar();
}

@NonNull Boolean goodBoolean = getSurprizeBoxedBoolean();

if(goodBoolean) {
foo();
} else {
bar();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private static Optional<IfStatementTree> getParentConditionalBranch(Tree tree) {

@CheckForNull
private static ExpressionTree findBoxedBoolean(ExpressionTree tree) {
if (tree.symbolType().is(BOOLEAN) && !isValidMethodInvocation(tree)) {
if (tree.symbolType().is(BOOLEAN) && !isValidMethodInvocation(tree) && !isNonnullIdentifier(tree)) {
return tree;
}
if (tree.is(Kind.LOGICAL_COMPLEMENT)) {
Expand Down Expand Up @@ -245,7 +245,7 @@ private static boolean isNullCheck(ExpressionTree tree) {
private static boolean isValidMethodInvocation(ExpressionTree tree) {
if (tree.is(Kind.METHOD_INVOCATION)) {
MethodInvocationTree mit = (MethodInvocationTree) tree;
return isOptionalInvocation(mit) || isAnnotatedNonnull(mit);
return isOptionalInvocation(mit) || isAnnotatedNonnull(mit.methodSymbol());
}
return false;
}
Expand All @@ -254,8 +254,12 @@ private static boolean isOptionalInvocation(MethodInvocationTree mit) {
return OPTIONAL_OR_ELSE.matches(mit) && !mit.arguments().get(0).is(Kind.NULL_LITERAL);
}

private static boolean isAnnotatedNonnull(MethodInvocationTree mit) {
return mit.methodSymbol().metadata()
private static boolean isNonnullIdentifier(ExpressionTree tree) {
return (tree instanceof IdentifierTree it) && isAnnotatedNonnull(it.symbol());
}

private static boolean isAnnotatedNonnull(Symbol symbol) {
return symbol.metadata()
.annotations()
.stream()
.map(SymbolMetadata.AnnotationInstance::symbol)
Expand Down

0 comments on commit 1049b38

Please sign in to comment.