Skip to content

Commit 6a14272

Browse files
committed
Improve comparison-or-equality-test-with-negative-zero.ql
Tested query with Variant Analysis and had multiple results.
1 parent dbc957b commit 6a14272

File tree

2 files changed

+49
-38
lines changed

2 files changed

+49
-38
lines changed

codeql-custom-queries-java/not-tested-queries/comparison-or-equality-test-with-negative-zero.ql

Lines changed: 0 additions & 38 deletions
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Finds comparison expressions and equality tests for which one operand is
3+
* a positive or negative 0 floating point literal, i.e. `-0.0f` or `+0.0d`.
4+
* These comparison expressions do not differentiate between negative and
5+
* positive 0 and therefore a 0 without any explicit sign should be preferred
6+
* to not irritate the reader. For example:
7+
* ```java
8+
* boolean isZero = d == +0.0 || d == -0.0;
9+
*
10+
* // Is the same as
11+
* boolean isZero = d == 0.0;
12+
* ```
13+
*
14+
* Use the static `compare` method or the `equals` method of the wrapper class
15+
* (e.g. `java.lang.Float`) methods to differentiate between those two types of 0.
16+
*
17+
* See also [JLS 17 §4.2.3. Floating-Point Types and Values](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.2.3).
18+
*
19+
* @kind problem
20+
*/
21+
22+
import java
23+
import lib.Literals
24+
25+
class ZeroFloatingPointLiteral extends FloatingPointLiteral_ {
26+
ZeroFloatingPointLiteral() {
27+
getValue().toFloat() = 0
28+
}
29+
}
30+
31+
class SignedZero extends UnaryExpr {
32+
SignedZero() {
33+
(this instanceof MinusExpr or this instanceof PlusExpr)
34+
and getExpr() instanceof ZeroFloatingPointLiteral
35+
}
36+
}
37+
38+
from BinaryExpr expr
39+
where
40+
(
41+
expr instanceof ComparisonExpr
42+
or expr instanceof EqualityTest
43+
)
44+
and (
45+
expr.getAnOperand() instanceof SignedZero
46+
// Or reading variable whose constant value is -0.0 or +0.0
47+
or expr.getAnOperand().(CompileTimeConstantExpr).(RValue).getVariable().getInitializer() instanceof SignedZero
48+
)
49+
select expr, "Comparison with -0.0 is same as comparison with +0.0"

0 commit comments

Comments
 (0)