Repository navigation
Description
Affects PMD Version: 7.28.0 (also 7.29.0-SNAPSHOT)
Description:
javac rejects Runnable r = () -> (str()); with lambda body is not compatible with a void functional interface. PMD accepts the lambda for Runnable. In the sample, javac compiles line 10 to g(int, Supplier), where PMD selects g(Object, Runnable).
LambdaMirrorImpl.isExpressionStatement tests the body node with instanceof:
Lines 153 to 160 in 5c9271c
| private static boolean isExpressionStatement(ASTExpression body) { | |
| // statement expression | |
| return body instanceof ASTMethodCall | |
| || body instanceof ASTConstructorCall | |
| || body instanceof ASTAssignmentExpression | |
| || body instanceof ASTUnaryExpression && !((ASTUnaryExpression) body).getOperator().isPure(); | |
| } |
PMD has no node for parentheses. The body of () -> (str()) is an ASTMethodCall with getParenthesisDepth() == 1, so the test passes and isVoidCompatible returns true. A parenthesized expression is not a statement expression (JLS 14.8), and an expression body is compatible with a void function type only if it is one (JLS 15.27.3). The method does not test ASTExpression.isParenthesized().
Found while working on #7136.
Code Sample demonstrating the issue:
import java.util.function.Supplier;
public class ParenBody {
static String str() { return "s"; }
static void g(int x, Supplier<String> s) { }
static void g(Object x, Runnable r) { }
void t(Integer i) {
g(i, () -> (str()));
g(i, () -> str());
}
}Steps to reproduce:
javac ParenBody.java, also with--release 8, thenjavap -c -p ParenBody.ParenBody.tcallsg:(ILjava/util/function/Supplier;)Von line 10 andg:(Ljava/lang/Object;Ljava/lang/Runnable;)Von line 11.- Run PMD on the file with the XPath rule
//MethodCall[pmd-java:matchesSig("ParenBody#g(java.lang.Object,java.lang.Runnable)")]. It reports lines 10 and 11. javac agrees with line 11 only.
Running PMD through: Other (PmdAnalysis API)
Activity
[java] UnnecessaryBoxing: rerun the overload resolution without the u…
[java] UnnecessaryBoxing: enable the test case for pmd#7145