/
ast_bool_op.rs
293 lines (271 loc) · 9.35 KB
/
ast_bool_op.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::iter;
use itertools::Either::{Left, Right};
use rustc_hash::FxHashMap;
use rustpython_ast::{Boolop, Constant, Expr, ExprContext, ExprKind, Unaryop};
use crate::ast::helpers::create_expr;
use crate::ast::types::Range;
use crate::autofix::Fix;
use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode, CheckKind};
use crate::source_code_generator::SourceCodeGenerator;
use crate::source_code_style::SourceCodeStyleDetector;
/// Return `true` if two `Expr` instances are equivalent names.
fn is_same_expr<'a>(a: &'a Expr, b: &'a Expr) -> Option<&'a str> {
if let (ExprKind::Name { id: a, .. }, ExprKind::Name { id: b, .. }) = (&a.node, &b.node) {
if a == b {
return Some(a);
}
}
None
}
/// Generate source code from an `Expr`.
fn to_source(expr: &Expr, stylist: &SourceCodeStyleDetector) -> String {
let mut generator = SourceCodeGenerator::new(
stylist.indentation(),
stylist.quote(),
stylist.line_ending(),
);
generator.unparse_expr(expr, 0);
generator.generate().unwrap()
}
/// SIM101
pub fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::Or, values } = &expr.node else {
return;
};
// Locate duplicate `isinstance` calls, represented as a map from argument name to indices
// of the relevant `Expr` instances in `values`.
let mut duplicates = FxHashMap::default();
for (index, call) in values.iter().enumerate() {
// Verify that this is an `isinstance` call.
let ExprKind::Call { func, args, keywords } = &call.node else {
continue;
};
if args.len() != 2 {
continue;
}
if !keywords.is_empty() {
continue;
}
let ExprKind::Name { id: func_name, .. } = &func.node else {
continue;
};
if func_name != "isinstance" {
continue;
}
// Collect the name of the argument.
let ExprKind::Name { id: arg_name, .. } = &args[0].node else {
continue;
};
duplicates
.entry(arg_name.as_str())
.or_insert_with(Vec::new)
.push(index);
}
// Generate a `Check` for each duplicate.
for (arg_name, indices) in duplicates {
if indices.len() > 1 {
let mut check = Check::new(
CheckKind::DuplicateIsinstanceCall(arg_name.to_string()),
Range::from_located(expr),
);
if checker.patch(&CheckCode::SIM101) {
// Grab the types used in each duplicate `isinstance` call.
let types: Vec<&Expr> = indices
.iter()
.map(|index| &values[*index])
.map(|expr| {
let ExprKind::Call { args, ..} = &expr.node else {
unreachable!("Indices should only contain `isinstance` calls")
};
args.get(1).expect("`isinstance` should have two arguments")
})
.collect();
// Flatten all the types used across the `isinstance` cals.
let elts: Vec<&Expr> = types
.iter()
.flat_map(|value| {
if let ExprKind::Tuple { elts, .. } = &value.node {
Left(elts.iter())
} else {
Right(iter::once(*value))
}
})
.collect();
// Generate a single `isinstance` call.
let call = create_expr(ExprKind::Call {
func: Box::new(create_expr(ExprKind::Name {
id: "isinstance".to_string(),
ctx: ExprContext::Load,
})),
args: vec![
create_expr(ExprKind::Name {
id: arg_name.to_string(),
ctx: ExprContext::Load,
}),
create_expr(ExprKind::Tuple {
elts: elts.into_iter().map(Clone::clone).collect(),
ctx: ExprContext::Load,
}),
],
keywords: vec![],
});
// Generate the combined `BoolOp`.
let bool_op = create_expr(ExprKind::BoolOp {
op: Boolop::Or,
values: iter::once(call)
.chain(
values
.iter()
.enumerate()
.filter(|(index, _)| !indices.contains(index))
.map(|(_, elt)| elt.clone()),
)
.collect(),
});
// Populate the `Fix`. Replace the _entire_ `BoolOp`. Note that if we have
// multiple duplicates, the fixes will conflict.
check.amend(Fix::replacement(
to_source(&bool_op, checker.style),
expr.location,
expr.end_location.unwrap(),
));
}
checker.add_check(check);
}
}
}
/// SIM220
pub fn a_and_not_a(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::And, values, } = &expr.node else {
return;
};
if values.len() < 2 {
return;
}
// Collect all negated and non-negated expressions.
let mut negated_expr = vec![];
let mut non_negated_expr = vec![];
for expr in values {
if let ExprKind::UnaryOp {
op: Unaryop::Not,
operand,
} = &expr.node
{
negated_expr.push(operand);
} else {
non_negated_expr.push(expr);
}
}
if negated_expr.is_empty() {
return;
}
for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut check = Check::new(
CheckKind::AAndNotA(id.to_string()),
Range::from_located(expr),
);
if checker.patch(&CheckCode::SIM220) {
check.amend(Fix::replacement(
"False".to_string(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.add_check(check);
}
}
}
}
/// SIM221
pub fn a_or_not_a(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::Or, values, } = &expr.node else {
return;
};
if values.len() < 2 {
return;
}
// Collect all negated and non-negated expressions.
let mut negated_expr = vec![];
let mut non_negated_expr = vec![];
for expr in values {
if let ExprKind::UnaryOp {
op: Unaryop::Not,
operand,
} = &expr.node
{
negated_expr.push(operand);
} else {
non_negated_expr.push(expr);
}
}
if negated_expr.is_empty() {
return;
}
for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut check = Check::new(
CheckKind::AOrNotA(id.to_string()),
Range::from_located(expr),
);
if checker.patch(&CheckCode::SIM220) {
check.amend(Fix::replacement(
"True".to_string(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.add_check(check);
}
}
}
}
/// SIM222
pub fn or_true(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::Or, values, } = &expr.node else {
return;
};
for value in values {
if let ExprKind::Constant {
value: Constant::Bool(true),
..
} = &value.node
{
let mut check = Check::new(CheckKind::OrTrue, Range::from_located(value));
if checker.patch(&CheckCode::SIM223) {
check.amend(Fix::replacement(
"True".to_string(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.add_check(check);
}
}
}
/// SIM223
pub fn and_false(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::And, values, } = &expr.node else {
return;
};
for value in values {
if let ExprKind::Constant {
value: Constant::Bool(false),
..
} = &value.node
{
let mut check = Check::new(CheckKind::AndFalse, Range::from_located(value));
if checker.patch(&CheckCode::SIM223) {
check.amend(Fix::replacement(
"False".to_string(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.add_check(check);
}
}
}