forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnguardedNextInGenerator.ql
More file actions
executable file
·61 lines (51 loc) · 1.81 KB
/
UnguardedNextInGenerator.ql
File metadata and controls
executable file
·61 lines (51 loc) · 1.81 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
/**
* @name Unguarded next in generator
* @description Calling next() in a generator may cause unintended early termination of an iteration.
* @kind problem
* @tags maintainability
* portability
* @problem.severity warning
* @sub-severity low
* @precision very-high
* @id py/unguarded-next-in-generator
*/
import python
FunctionValue iter() { result = Value::named("iter") }
BuiltinFunctionValue next() { result = Value::named("next") }
predicate call_to_iter(CallNode call, EssaVariable sequence) {
sequence.getAUse() = iter().getArgumentForCall(call, 0)
}
predicate call_to_next(CallNode call, ControlFlowNode iter) {
iter = next().getArgumentForCall(call, 0)
}
predicate call_to_next_has_default(CallNode call) {
exists(call.getArg(1)) or exists(call.getArgByName("default"))
}
predicate guarded_not_empty_sequence(EssaVariable sequence) {
sequence.getDefinition() instanceof EssaEdgeRefinement
}
/** The pattern `next(iter(x))` is often used where `x` is known not be empty. Check for that. */
predicate iter_not_exhausted(EssaVariable iterator) {
exists(EssaVariable sequence |
call_to_iter(iterator.getDefinition().(AssignmentDefinition).getValue(), sequence) and
guarded_not_empty_sequence(sequence)
)
}
predicate stop_iteration_handled(CallNode call) {
exists(Try t |
t.containsInScope(call.getNode()) and
t.getAHandler().getType().pointsTo(ClassValue::stopIteration())
)
}
from CallNode call
where
call_to_next(call, _) and
not call_to_next_has_default(call) and
not exists(EssaVariable iterator |
call_to_next(call, iterator.getAUse()) and
iter_not_exhausted(iterator)
) and
call.getNode().getScope().(Function).isGenerator() and
not exists(Comp comp | comp.contains(call.getNode())) and
not stop_iteration_handled(call)
select call, "Call to next() in a generator"