Skip to content

[java] Lambda with a parenthesized expression body is treated as void-compatible #7145

Closed

Description

@saryn17

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:

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:

  1. javac ParenBody.java, also with --release 8, then javap -c -p ParenBody. ParenBody.t calls g:(ILjava/util/function/Supplier;)V on line 10 and g:(Ljava/lang/Object;Ljava/lang/Runnable;)V on line 11.
  2. 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    in:type-resolution

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions