Repository navigation
Description
Affects PMD Version: 7.29.0 (also 7.30.0-SNAPSHOT at 4a1d37d)
Description:
getConstValue() returns null and isCompileTimeConstant() returns false for (boolean) true, ON == true and ON != false, where ON is a static final boolean set to true. JLS 15.29 allows casts to primitive types and the equality operators == and != in constant expressions. ConstantFolder folds a cast only to a numeric type or String, and == and != only for numeric and char operands:
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ConstantFolder.java
Lines 189 to 195 in 4a1d37d
| if (t.isNumeric()) { | |
| res = numericCoercion(castValue.getValue(), t); | |
| } else if (TypeTestUtil.isExactlyA(String.class, node.getCastType())) { | |
| res = stringCoercion(castValue.getValue()); | |
| } else { | |
| return ConstResult.NO_CONST_VALUE; | |
| } |
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ConstantFolder.java
Lines 540 to 547 in 4a1d37d
| private static @Nullable Boolean eqResult(Object left, Object right) { | |
| if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { | |
| Pair<Object, Object> promoted = binaryNumericPromotion(left, right); | |
| return promoted.getLeft().equals(promoted.getRight()); // fixme Double.NaN | |
| } else { | |
| return null; // not a constant expr on reference types | |
| } | |
| } |
Since #7218, LambdaMirrorImpl uses getConstValue() of a loop condition to decide whether a block lambda body can complete normally. On main, the three lambdas below are not value-compatible, and PMD selects submit(Runnable) where javac selects submit(Callable). PMD 7.29.0 also selects submit(Runnable) for them, because of #7144.
Found while working on #7136.
Code Sample demonstrating the issue:
import java.util.concurrent.ExecutorService;
public class Submit {
static final boolean ON = true;
void t(ExecutorService pool) {
pool.submit(() -> { while ((boolean) true) { } });
pool.submit(() -> { while (ON == true) { } });
pool.submit(() -> { while (ON != false) { } });
}
}Steps to reproduce:
javac Submit.java, also with--release 8, thenjavap -c -p Submit. The three calls inSubmit.taresubmit:(Ljava/util/concurrent/Callable;).- Run PMD on the file with the XPath rule
//WhileStatement/*[1][@CompileTimeConstant = false()]. It reports lines 7, 8 and 9. - The XPath rule
//MethodCall[pmd-java:matchesSig("java.util.concurrent.ExecutorService#submit(java.lang.Runnable)")]reports lines 7, 8 and 9 too.
Running PMD through: Other (PmdAnalysis API)
Activity
[java] UnnecessaryBoxing: enable the test case for pmd#7144
[java] Fix pmd#7313: Fold casts to boolean and boolean equality (pmd#…
[java] UnnecessaryBoxing: enable the test case for pmd#7313