-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rules.rs
453 lines (409 loc) · 14.1 KB
/
rules.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use std::collections::BTreeMap;
use std::iter;
use itertools::Either::{Left, Right};
use log::error;
use rustc_hash::FxHashSet;
use rustpython_parser::ast::{
Boolop, Constant, Expr, ExprContext, ExprKind, Keyword, Stmt, StmtKind,
};
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::{create_expr, trailing_comment_start_offset, unparse_expr};
use ruff_python_ast::types::RefEquality;
use ruff_python_stdlib::identifiers::is_identifier;
use crate::autofix::actions::delete_stmt;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
#[violation]
pub struct UnnecessaryPass;
impl AlwaysAutofixableViolation for UnnecessaryPass {
#[derive_message_formats]
fn message(&self) -> String {
format!("Unnecessary `pass` statement")
}
fn autofix_title(&self) -> String {
"Remove unnecessary `pass`".to_string()
}
}
#[violation]
pub struct DuplicateClassFieldDefinition(pub String);
impl AlwaysAutofixableViolation for DuplicateClassFieldDefinition {
#[derive_message_formats]
fn message(&self) -> String {
let DuplicateClassFieldDefinition(name) = self;
format!("Class field `{name}` is defined multiple times")
}
fn autofix_title(&self) -> String {
let DuplicateClassFieldDefinition(name) = self;
format!("Remove duplicate field definition for `{name}`")
}
}
#[violation]
pub struct NonUniqueEnums {
pub value: String,
}
impl Violation for NonUniqueEnums {
#[derive_message_formats]
fn message(&self) -> String {
let NonUniqueEnums { value } = self;
format!("Enum contains duplicate value: `{value}`")
}
}
#[violation]
pub struct UnnecessarySpread;
impl Violation for UnnecessarySpread {
#[derive_message_formats]
fn message(&self) -> String {
format!("Unnecessary spread `**`")
}
}
#[violation]
pub struct MultipleStartsEndsWith {
pub attr: String,
}
impl AlwaysAutofixableViolation for MultipleStartsEndsWith {
#[derive_message_formats]
fn message(&self) -> String {
let MultipleStartsEndsWith { attr } = self;
format!("Call `{attr}` once with a `tuple`")
}
fn autofix_title(&self) -> String {
let MultipleStartsEndsWith { attr } = self;
format!("Merge into a single `{attr}` call")
}
}
#[violation]
pub struct UnnecessaryDictKwargs;
impl Violation for UnnecessaryDictKwargs {
#[derive_message_formats]
fn message(&self) -> String {
format!("Unnecessary `dict` kwargs")
}
}
#[violation]
pub struct ReimplementedListBuiltin;
impl AlwaysAutofixableViolation for ReimplementedListBuiltin {
#[derive_message_formats]
fn message(&self) -> String {
format!("Prefer `list` over useless lambda")
}
fn autofix_title(&self) -> String {
"Replace with `list`".to_string()
}
}
/// PIE790
pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
if body.len() > 1 {
// This only catches the case in which a docstring makes a `pass` statement
// redundant. Consider removing all `pass` statements instead.
let docstring_stmt = &body[0];
let pass_stmt = &body[1];
let StmtKind::Expr { value } = &docstring_stmt.node else {
return;
};
if matches!(
value.node,
ExprKind::Constant {
value: Constant::Str(..),
..
}
) {
if matches!(pass_stmt.node, StmtKind::Pass) {
let mut diagnostic = Diagnostic::new(UnnecessaryPass, pass_stmt.range());
if checker.patch(diagnostic.kind.rule()) {
if let Some(index) = trailing_comment_start_offset(pass_stmt, checker.locator) {
diagnostic.set_fix(Fix::unspecified(Edit::range_deletion(
pass_stmt.range().add_end(index),
)));
} else {
diagnostic.try_set_fix(|| {
delete_stmt(
pass_stmt,
None,
&[],
checker.locator,
checker.indexer,
checker.stylist,
)
});
}
}
checker.diagnostics.push(diagnostic);
}
}
}
}
/// PIE794
pub fn duplicate_class_field_definition<'a, 'b>(
checker: &mut Checker<'a>,
parent: &'b Stmt,
body: &'b [Stmt],
) where
'b: 'a,
{
let mut seen_targets: FxHashSet<&str> = FxHashSet::default();
for stmt in body {
// Extract the property name from the assignment statement.
let target = match &stmt.node {
StmtKind::Assign { targets, .. } => {
if targets.len() != 1 {
continue;
}
if let ExprKind::Name { id, .. } = &targets[0].node {
id
} else {
continue;
}
}
StmtKind::AnnAssign { target, .. } => {
if let ExprKind::Name { id, .. } = &target.node {
id
} else {
continue;
}
}
_ => continue,
};
if !seen_targets.insert(target) {
let mut diagnostic = Diagnostic::new(
DuplicateClassFieldDefinition(target.to_string()),
stmt.range(),
);
if checker.patch(diagnostic.kind.rule()) {
let deleted: Vec<&Stmt> = checker.deletions.iter().map(Into::into).collect();
let locator = checker.locator;
match delete_stmt(
stmt,
Some(parent),
&deleted,
locator,
checker.indexer,
checker.stylist,
) {
Ok(fix) => {
checker.deletions.insert(RefEquality(stmt));
diagnostic.set_fix(fix);
}
Err(err) => {
error!("Failed to remove duplicate class definition: {}", err);
}
}
}
checker.diagnostics.push(diagnostic);
}
}
}
/// PIE796
pub fn non_unique_enums<'a, 'b>(checker: &mut Checker<'a>, parent: &'b Stmt, body: &'b [Stmt])
where
'b: 'a,
{
let StmtKind::ClassDef { bases, .. } = &parent.node else {
return;
};
if !bases.iter().any(|expr| {
checker
.ctx
.resolve_call_path(expr)
.map_or(false, |call_path| call_path.as_slice() == ["enum", "Enum"])
}) {
return;
}
let mut seen_targets: FxHashSet<ComparableExpr> = FxHashSet::default();
for stmt in body {
let StmtKind::Assign { value, .. } = &stmt.node else {
continue;
};
if let ExprKind::Call { func, .. } = &value.node {
if checker
.ctx
.resolve_call_path(func)
.map_or(false, |call_path| call_path.as_slice() == ["enum", "auto"])
{
continue;
}
}
if !seen_targets.insert(ComparableExpr::from(value)) {
let diagnostic = Diagnostic::new(
NonUniqueEnums {
value: unparse_expr(value, checker.stylist),
},
stmt.range(),
);
checker.diagnostics.push(diagnostic);
}
}
}
/// PIE800
pub fn unnecessary_spread(checker: &mut Checker, keys: &[Option<Expr>], values: &[Expr]) {
for item in keys.iter().zip(values.iter()) {
if let (None, value) = item {
// We only care about when the key is None which indicates a spread `**`
// inside a dict.
if let ExprKind::Dict { .. } = value.node {
let diagnostic = Diagnostic::new(UnnecessarySpread, value.range());
checker.diagnostics.push(diagnostic);
}
}
}
}
/// Return `true` if a key is a valid keyword argument name.
fn is_valid_kwarg_name(key: &Expr) -> bool {
if let ExprKind::Constant {
value: Constant::Str(value),
..
} = &key.node
{
is_identifier(value)
} else {
false
}
}
/// PIE804
pub fn unnecessary_dict_kwargs(checker: &mut Checker, expr: &Expr, kwargs: &[Keyword]) {
for kw in kwargs {
// keyword is a spread operator (indicated by None)
if kw.node.arg.is_none() {
if let ExprKind::Dict { keys, .. } = &kw.node.value.node {
// ensure foo(**{"bar-bar": 1}) doesn't error
if keys.iter().all(|expr| expr.as_ref().map_or(false, is_valid_kwarg_name)) ||
// handle case of foo(**{**bar})
(keys.len() == 1 && keys[0].is_none())
{
let diagnostic = Diagnostic::new(UnnecessaryDictKwargs, expr.range());
checker.diagnostics.push(diagnostic);
}
}
}
}
}
/// PIE810
pub fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) {
let ExprKind::BoolOp { op: Boolop::Or, values } = &expr.node else {
return;
};
let mut duplicates = BTreeMap::new();
for (index, call) in values.iter().enumerate() {
let ExprKind::Call {
func,
args,
keywords,
..
} = &call.node else {
continue
};
if !(args.len() == 1 && keywords.is_empty()) {
continue;
}
let ExprKind::Attribute { value, attr, .. } = &func.node else {
continue
};
if attr != "startswith" && attr != "endswith" {
continue;
}
let ExprKind::Name { id: arg_name, .. } = &value.node else {
continue
};
duplicates
.entry((attr.as_str(), arg_name.as_str()))
.or_insert_with(Vec::new)
.push(index);
}
// Generate a `Diagnostic` for each duplicate.
for ((attr_name, arg_name), indices) in duplicates {
if indices.len() > 1 {
let mut diagnostic = Diagnostic::new(
MultipleStartsEndsWith {
attr: attr_name.to_string(),
},
expr.range(),
);
if checker.patch(diagnostic.kind.rule()) {
let words: Vec<&Expr> = indices
.iter()
.map(|index| &values[*index])
.map(|expr| {
let ExprKind::Call { func: _, args, keywords: _} = &expr.node else {
unreachable!("{}", format!("Indices should only contain `{attr_name}` calls"))
};
args.get(0)
.unwrap_or_else(|| panic!("`{attr_name}` should have one argument"))
})
.collect();
let call = create_expr(ExprKind::Call {
func: Box::new(create_expr(ExprKind::Attribute {
value: Box::new(create_expr(ExprKind::Name {
id: arg_name.to_string(),
ctx: ExprContext::Load,
})),
attr: attr_name.to_string(),
ctx: ExprContext::Load,
})),
args: vec![create_expr(ExprKind::Tuple {
elts: words
.iter()
.flat_map(|value| {
if let ExprKind::Tuple { elts, .. } = &value.node {
Left(elts.iter())
} else {
Right(iter::once(*value))
}
})
.map(Clone::clone)
.collect(),
ctx: ExprContext::Load,
})],
keywords: vec![],
});
// Generate the combined `BoolOp`.
let mut call = Some(call);
let bool_op = create_expr(ExprKind::BoolOp {
op: Boolop::Or,
values: values
.iter()
.enumerate()
.filter_map(|(index, elt)| {
if indices.contains(&index) {
std::mem::take(&mut call)
} else {
Some(elt.clone())
}
})
.collect(),
});
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&bool_op, checker.stylist),
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}
}
}
/// PIE807
pub fn reimplemented_list_builtin(checker: &mut Checker, expr: &Expr) {
let ExprKind::Lambda { args, body } = &expr.node else {
panic!("Expected ExprKind::Lambda");
};
if args.args.is_empty()
&& args.kwonlyargs.is_empty()
&& args.posonlyargs.is_empty()
&& args.vararg.is_none()
&& args.kwarg.is_none()
{
if let ExprKind::List { elts, .. } = &body.node {
if elts.is_empty() {
let mut diagnostic = Diagnostic::new(ReimplementedListBuiltin, expr.range());
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
"list".to_string(),
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}
}
}
}