[java] InvalidLogMessageFormat: False positive with message and exception in a block inside a lambda

This commit is contained in:
Nicolas Filotto
2021-10-15 16:02:57 +02:00
parent c9077e19ea
commit afab7d7881
2 changed files with 30 additions and 5 deletions

View File

@ -35,6 +35,7 @@ import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.Scope;
public class InvalidLogMessageFormatRule extends AbstractJavaRule {
@ -217,14 +218,17 @@ public class InvalidLogMessageFormatRule extends AbstractJavaRule {
varName = name.getImage();
}
}
for (NameDeclaration decl : prefix.getScope().getDeclarations().keySet()) {
if (decl.getName().equals(varName)) {
if (decl.getNode().getParent() instanceof ASTLambdaExpression) {
Scope scope = prefix == null ? null : prefix.getScope();
while (scope != null) {
// Try recursively to find the expected NameDeclaration
for (NameDeclaration decl : scope.getDeclarations().keySet()) {
if (decl.getName().equals(varName)) {
// If the last parameter is a lambda parameter, then we also ignore it - regardless of the type.
// This is actually a workaround, since type resolution doesn't resolve the types of lambda parameters.
return true;
return decl.getNode().getParent() instanceof ASTLambdaExpression;
}
}
scope = scope.getParent();
}
return false;
}

View File

@ -175,6 +175,27 @@ public class InvalidSl4jExceptionBug1541 {
}
]]></code>
</test-code>
<test-code>
<description>#3560 [java] InvalidLogMessageFormat: False positive with message and exception in a block inside a lambda</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Consumer;
public class InvalidSl4jExceptionBug3560 {
private static final Logger LOGGER = LoggerFactory.getLogger(InvalidSl4jExceptionBug3560.class);
public static Consumer<Throwable> build() {
return e -> {
if (e instanceof RuntimeException) {
LOGGER.warn("Unexpected RuntimeException", e);
}
};
}
}
]]></code>
</test-code>
<test-code>
<description>#1551 [java] InvalidSlf4jMessageFormat: fails with NPE</description>
@ -868,7 +889,7 @@ class InvalidLogMessageFormatTest {
}
]]></code>
</test-code>
<test-code>
<description>#2431 IndexOutOfBoundsException when only logging exception message</description>
<expected-problems>0</expected-problems>