-
Notifications
You must be signed in to change notification settings - Fork 903
/
loop_iterator_mutation.rs
293 lines (265 loc) · 8.88 KB
/
loop_iterator_mutation.rs
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::collections::HashMap;
use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::Violation;
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_ast::{
visitor::{self, Visitor},
Arguments, Expr, ExprAttribute, ExprCall, ExprSubscript, Stmt, StmtAssign, StmtAugAssign,
StmtBreak, StmtDelete, StmtFor, StmtIf,
};
use ruff_text_size::TextRange;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
/// ## What it does
/// Checks for mutations to an iterable during a loop iteration.
///
/// ## Why is this bad?
/// When iterating over an iterable, mutating the iterable can lead to unexpected
/// behavior, like skipping elements or infinite loops.
///
/// ## Example
/// ```python
/// items = [1, 2, 3]
///
/// for item in items:
/// print(item)
///
/// # Create an infinite loop by appending to the list.
/// items.append(item)
/// ```
///
/// ## References
/// - [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable)
#[violation]
pub struct LoopIteratorMutation {
name: Option<SourceCodeSnippet>,
}
impl Violation for LoopIteratorMutation {
#[derive_message_formats]
fn message(&self) -> String {
let LoopIteratorMutation { name } = self;
if let Some(name) = name.as_ref().and_then(SourceCodeSnippet::full_display) {
format!("Mutation to loop iterable `{name}` during iteration")
} else {
format!("Mutation to loop iterable during iteration")
}
}
}
/// B909
pub(crate) fn loop_iterator_mutation(checker: &mut Checker, stmt_for: &StmtFor) {
let StmtFor {
target,
iter,
body,
orelse: _,
is_async: _,
range: _,
} = stmt_for;
if !matches!(iter.as_ref(), Expr::Name(_) | Expr::Attribute(_)) {
return;
}
// Collect mutations to the iterable.
let mutations = {
let mut visitor = LoopMutationsVisitor::new(iter, target);
visitor.visit_body(body);
visitor.mutations
};
// Create a diagnostic for each mutation.
for mutation in mutations.values().flatten() {
let name = UnqualifiedName::from_expr(iter)
.map(|name| name.to_string())
.map(SourceCodeSnippet::new);
checker
.diagnostics
.push(Diagnostic::new(LoopIteratorMutation { name }, *mutation));
}
}
/// Returns `true` if the method mutates when called on an iterator.
fn is_mutating_function(function_name: &str) -> bool {
matches!(
function_name,
"append"
| "sort"
| "reverse"
| "remove"
| "clear"
| "extend"
| "insert"
| "pop"
| "popitem"
| "setdefault"
| "update"
| "intersection_update"
| "difference_update"
| "symmetric_difference_update"
| "add"
| "discard"
)
}
/// A visitor to collect mutations to a variable in a loop.
#[derive(Debug, Clone)]
struct LoopMutationsVisitor<'a> {
iter: &'a Expr,
target: &'a Expr,
mutations: HashMap<u8, Vec<TextRange>>,
branches: Vec<u8>,
branch: u8,
}
impl<'a> LoopMutationsVisitor<'a> {
/// Initialize the visitor.
fn new(iter: &'a Expr, target: &'a Expr) -> Self {
Self {
iter,
target,
mutations: HashMap::new(),
branches: vec![0],
branch: 0,
}
}
/// Register a mutation.
fn add_mutation(&mut self, range: TextRange) {
self.mutations.entry(self.branch).or_default().push(range);
}
/// Handle, e.g., `del items[0]`.
fn handle_delete(&mut self, range: TextRange, targets: &[Expr]) {
for target in targets {
if let Expr::Subscript(ExprSubscript {
range: _,
value,
slice,
ctx: _,
}) = target
{
// Find, e.g., `del items[0]`.
if ComparableExpr::from(self.iter) == ComparableExpr::from(value) {
// But allow, e.g., `for item in items: del items[item]`.
if ComparableExpr::from(self.target) != ComparableExpr::from(slice) {
self.add_mutation(range);
}
}
}
}
}
/// Handle, e.g., `items[0] = 1`.
fn handle_assign(&mut self, range: TextRange, targets: &[Expr]) {
for target in targets {
if let Expr::Subscript(ExprSubscript {
range: _,
value,
slice,
ctx: _,
}) = target
{
// Find, e.g., `items[0] = 1`.
if ComparableExpr::from(self.iter) == ComparableExpr::from(value) {
// But allow, e.g., `for item in items: items[item] = 1`.
if ComparableExpr::from(self.target) != ComparableExpr::from(slice) {
self.add_mutation(range);
}
}
}
}
}
/// Handle, e.g., `items += [1]`.
fn handle_aug_assign(&mut self, range: TextRange, target: &Expr) {
if ComparableExpr::from(self.iter) == ComparableExpr::from(target) {
self.add_mutation(range);
}
}
/// Handle, e.g., `items.append(1)`.
fn handle_call(&mut self, func: &Expr, arguments: &Arguments) {
if let Expr::Attribute(ExprAttribute {
range,
value,
attr,
ctx: _,
}) = func
{
if is_mutating_function(attr.as_str()) {
// Find, e.g., `items.remove(1)`.
if ComparableExpr::from(self.iter) == ComparableExpr::from(value) {
// But allow, e.g., `for item in items: items.remove(item)`.
if arguments.len() == 1 && matches!(attr.as_str(), "remove" | "discard") {
if let [arg] = &*arguments.args {
if ComparableExpr::from(self.target) == ComparableExpr::from(arg) {
return;
}
}
}
self.add_mutation(*range);
}
}
}
}
}
/// `Visitor` to collect all used identifiers in a statement.
impl<'a> Visitor<'a> for LoopMutationsVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
// Ex) `del items[0]`
Stmt::Delete(StmtDelete { range, targets }) => {
self.handle_delete(*range, targets);
visitor::walk_stmt(self, stmt);
}
// Ex) `items[0] = 1`
Stmt::Assign(StmtAssign { range, targets, .. }) => {
self.handle_assign(*range, targets);
visitor::walk_stmt(self, stmt);
}
// Ex) `items += [1]`
Stmt::AugAssign(StmtAugAssign { range, target, .. }) => {
self.handle_aug_assign(*range, target);
visitor::walk_stmt(self, stmt);
}
// Ex) `if True: items.append(1)`
Stmt::If(StmtIf {
test,
body,
elif_else_clauses,
..
}) => {
// Handle the `if` branch.
self.branch += 1;
self.branches.push(self.branch);
self.visit_expr(test);
self.visit_body(body);
self.branches.pop();
// Handle the `elif` and `else` branches.
for clause in elif_else_clauses {
self.branch += 1;
self.branches.push(self.branch);
if let Some(test) = &clause.test {
self.visit_expr(test);
}
self.visit_body(&clause.body);
self.branches.pop();
}
}
// On break, clear the mutations for the current branch.
Stmt::Break(StmtBreak { range: _ }) => {
if let Some(mutations) = self.mutations.get_mut(&self.branch) {
mutations.clear();
}
visitor::walk_stmt(self, stmt);
}
// Avoid recursion for class and function definitions.
Stmt::ClassDef(_) | Stmt::FunctionDef(_) => {}
// Default case.
_ => {
visitor::walk_stmt(self, stmt);
}
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
// Ex) `items.append(1)`
if let Expr::Call(ExprCall {
func, arguments, ..
}) = expr
{
self.handle_call(func, arguments);
}
visitor::walk_expr(self, expr);
}
}