-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathConstantExpAppearsNonConstant.ql
More file actions
79 lines (74 loc) · 2.48 KB
/
ConstantExpAppearsNonConstant.ql
File metadata and controls
79 lines (74 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* @name Expression always evaluates to the same value
* @description An expression that always evaluates to the same value, but which has a non-constant subexpression, indicates a mistake.
* @kind problem
* @problem.severity warning
* @precision very-high
* @id java/evaluation-to-constant
* @tags maintainability
* useless-code
*/
import java
int integralTypeWidth(IntegralType t) {
if t.hasName("long") or t.hasName("Long") then result = 64 else result = 32
}
int eval(Expr e) { result = e.(CompileTimeConstantExpr).getIntValue() }
predicate isConstantExp(Expr e) {
// A literal is constant.
e instanceof Literal
or
// A parenthesized expression is constant if its proper expression is.
isConstantExp(e.(ParExpr).getProperExpr())
or
e instanceof TypeAccess
or
e instanceof ArrayTypeAccess
or
e instanceof WildcardTypeAccess
or
// A binary expression is constant if both its operands are.
exists(BinaryExpr b | b = e |
isConstantExp(b.getLeftOperand()) and
isConstantExp(b.getRightOperand())
)
or
// A cast expression is constant if its expression is.
exists(CastExpr c | c = e | isConstantExp(c.getExpr().getProperExpr()))
or
// Multiplication by 0 is constant.
exists(MulExpr m | m = e | eval(m.getAnOperand().getProperExpr()) = 0)
or
// Integer remainder by 1 is constant.
exists(RemExpr r | r = e |
r.getLeftOperand().getType() instanceof IntegralType and
eval(r.getRightOperand().getProperExpr()) = 1
)
or
// Left shift by 64 (longs) or 32 (all other integer types) is constant.
exists(LShiftExpr s | s = e |
exists(IntegralType t | t = s.getLeftOperand().getType() |
eval(s.getRightOperand().getProperExpr()) = integralTypeWidth(t)
)
)
or
exists(AndBitwiseExpr a | a = e | eval(a.getAnOperand().getProperExpr()) = 0)
or
exists(AndLogicalExpr a | a = e |
a.getAnOperand().getProperExpr().(BooleanLiteral).getBooleanValue() = false
)
or
exists(OrLogicalExpr o | o = e |
o.getAnOperand().getProperExpr().(BooleanLiteral).getBooleanValue() = true
)
}
from Expr e
where
isConstantExp(e) and
exists(Expr child | e.getAChildExpr() = child |
not isConstantExp(child) and
not child instanceof Annotation
) and
not e instanceof CompileTimeConstantExpr and
// Exclude expressions that appear to be disabled deliberately (e.g. `false && ...`).
not e.(AndLogicalExpr).getAnOperand().(BooleanLiteral).getBooleanValue() = false
select e, "Expression always evaluates to the same value."