forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuspiciousUnusedLoopIterationVariable.ql
More file actions
52 lines (48 loc) · 1.64 KB
/
SuspiciousUnusedLoopIterationVariable.ql
File metadata and controls
52 lines (48 loc) · 1.64 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
/**
* @name Unused loop iteration variable
* @description A loop iteration variable is unused, which suggests an error.
* @kind problem
* @problem.severity error
* @id js/unused-loop-variable
* @tags maintainability
* correctness
* @precision high
*/
import javascript
/**
* An expression that adds a value to a variable.
*
* This includes `+=` expressions, pre- and post-increment expressions,
* and expressions of the form `x = x + e`.
*/
class IncrementExpr extends Expr {
IncrementExpr() {
// x += e
this instanceof AssignAddExpr or
// ++x or x++
this instanceof PreIncExpr or this instanceof PostIncExpr or
// x = x + e
exists (AssignExpr assgn, Variable v | assgn = this |
assgn.getTarget() = v.getAnAccess() and
assgn.getRhs().(AddExpr).getAnOperand().stripParens() = v.getAnAccess()
)
}
}
/**
* Holds if `efl` is a loop whose body increments a variable and does nothing else.
*/
predicate countingLoop(EnhancedForLoop efl) {
exists (ExprStmt inc | inc.getExpr().stripParens() instanceof IncrementExpr |
inc = efl.getBody() or
inc = efl.getBody().(BlockStmt).getAStmt()
)
}
from EnhancedForLoop efl, PurelyLocalVariable iter
where iter = efl.getAnIterationVariable() and
not exists (SsaExplicitDefinition ssa | ssa.defines(efl.getIteratorExpr(), iter)) and
exists (ReachableBasicBlock body | body.getANode() = efl.getBody() |
body.getASuccessor+() = body
) and
not countingLoop(efl) and
not iter.getName().toLowerCase().regexpMatch("(_|dummy|unused).*")
select efl.getIterator(), "For loop variable " + iter.getName() + " is not used in the loop body."