-
Notifications
You must be signed in to change notification settings - Fork 897
/
collapsible_if.rs
400 lines (358 loc) · 11.9 KB
/
collapsible_if.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
use std::borrow::Cow;
use anyhow::{bail, Result};
use libcst_native::ParenthesizedNode;
use log::error;
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::{self as ast, whitespace, Constant, ElifElseClause, Expr, Stmt};
use ruff_python_codegen::Stylist;
use ruff_python_semantic::analyze::typing::{is_sys_version_block, is_type_checking_block};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::cst::helpers::space;
use crate::cst::matchers::{match_function_def, match_if, match_indented_block, match_statement};
use crate::fix::codemods::CodegenStylist;
use crate::fix::edits::fits;
/// ## What it does
/// Checks for nested `if` statements that can be collapsed into a single `if`
/// statement.
///
/// ## Why is this bad?
/// Nesting `if` statements leads to deeper indentation and makes code harder to
/// read. Instead, combine the conditions into a single `if` statement with an
/// `and` operator.
///
/// ## Example
/// ```python
/// if foo:
/// if bar:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// if foo and bar:
/// ...
/// ```
///
/// ## References
/// - [Python documentation: The `if` statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)
/// - [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)
#[violation]
pub struct CollapsibleIf;
impl Violation for CollapsibleIf {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("Use a single `if` statement instead of nested `if` statements")
}
fn fix_title(&self) -> Option<String> {
Some("Combine `if` statements using `and`".to_string())
}
}
/// SIM102
pub(crate) fn nested_if_statements(
checker: &mut Checker,
stmt_if: &ast::StmtIf,
parent: Option<&Stmt>,
) {
let Some(nested_if) = nested_if_body(stmt_if) else {
return;
};
// Find the deepest nested if-statement, to inform the range.
let Some(test) = find_last_nested_if(nested_if.body()) else {
return;
};
// Check if the parent is already emitting a larger diagnostic including this if statement
if let Some(Stmt::If(stmt_if)) = parent {
if let Some(nested_if) = nested_if_body(stmt_if) {
// In addition to repeating the `nested_if_body` and `find_last_nested_if` check, we
// also need to be the first child in the parent
let body = nested_if.body();
if matches!(&body[0], Stmt::If(inner) if *inner == *stmt_if)
&& find_last_nested_if(body).is_some()
{
return;
}
}
}
let Some(colon) = SimpleTokenizer::starts_at(test.end(), checker.locator().contents())
.skip_trivia()
.find(|token| token.kind == SimpleTokenKind::Colon)
else {
return;
};
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
let mut diagnostic = Diagnostic::new(
CollapsibleIf,
TextRange::new(nested_if.start(), colon.end()),
);
// The fixer preserves comments in the nested body, but removes comments between
// the outer and inner if statements.
if !checker
.indexer()
.comment_ranges()
.intersects(TextRange::new(
nested_if.start(),
nested_if.body()[0].start(),
))
{
match collapse_nested_if(checker.locator(), checker.stylist(), nested_if) {
Ok(edit) => {
if edit.content().map_or(true, |content| {
fits(
content,
(&nested_if).into(),
checker.locator(),
checker.settings.line_length,
checker.settings.tab_size,
)
}) {
diagnostic.set_fix(Fix::unsafe_edit(edit));
}
}
Err(err) => error!("Failed to fix nested if: {err}"),
}
}
checker.diagnostics.push(diagnostic);
}
#[derive(Debug, Clone, Copy)]
pub(super) enum NestedIf<'a> {
If(&'a ast::StmtIf),
Elif(&'a ElifElseClause),
}
impl<'a> NestedIf<'a> {
pub(super) fn body(self) -> &'a [Stmt] {
match self {
NestedIf::If(stmt_if) => &stmt_if.body,
NestedIf::Elif(clause) => &clause.body,
}
}
pub(super) fn is_elif(self) -> bool {
matches!(self, NestedIf::Elif(..))
}
}
impl Ranged for NestedIf<'_> {
fn range(&self) -> TextRange {
match self {
NestedIf::If(stmt_if) => stmt_if.range(),
NestedIf::Elif(clause) => clause.range(),
}
}
}
impl<'a> From<&NestedIf<'a>> for AnyNodeRef<'a> {
fn from(value: &NestedIf<'a>) -> Self {
match value {
NestedIf::If(stmt_if) => (*stmt_if).into(),
NestedIf::Elif(clause) => (*clause).into(),
}
}
}
/// Returns the body, the range of the `if` or `elif` and whether the range is for an `if` or `elif`
fn nested_if_body(stmt_if: &ast::StmtIf) -> Option<NestedIf> {
let ast::StmtIf {
test,
body,
elif_else_clauses,
..
} = stmt_if;
// It must be the last condition, otherwise there could be another `elif` or `else` that only
// depends on the outer of the two conditions
let (test, nested_if) = if let Some(clause) = elif_else_clauses.last() {
if let Some(test) = &clause.test {
(test, NestedIf::Elif(clause))
} else {
// The last condition is an `else` (different rule)
return None;
}
} else {
(test.as_ref(), NestedIf::If(stmt_if))
};
// The nested if must be the only child, otherwise there is at least one more statement that
// only depends on the outer condition
if body.len() > 1 {
return None;
}
// Allow `if __name__ == "__main__":` statements.
if is_main_check(test) {
return None;
}
// Allow `if True:` and `if False:` statements.
if matches!(
test,
Expr::Constant(ast::ExprConstant {
value: Constant::Bool(..),
..
})
) {
return None;
}
Some(nested_if)
}
/// Find the last nested if statement and return the test expression and the
/// last statement.
///
/// ```python
/// if xxx:
/// if yyy:
/// # ^^^ returns this expression
/// z = 1
/// ...
/// ```
fn find_last_nested_if(body: &[Stmt]) -> Option<&Expr> {
let [Stmt::If(ast::StmtIf {
test,
body: inner_body,
elif_else_clauses,
..
})] = body
else {
return None;
};
if !elif_else_clauses.is_empty() {
return None;
}
find_last_nested_if(inner_body).or(Some(test))
}
/// Returns `true` if an expression is an `if __name__ == "__main__":` check.
fn is_main_check(expr: &Expr) -> bool {
if let Expr::Compare(ast::ExprCompare {
left, comparators, ..
}) = expr
{
if let Expr::Name(ast::ExprName { id, .. }) = left.as_ref() {
if id == "__name__" {
if let [Expr::Constant(ast::ExprConstant {
value: Constant::Str(ast::StringConstant { value, .. }),
..
})] = comparators.as_slice()
{
if value == "__main__" {
return true;
}
}
}
}
}
false
}
fn parenthesize_and_operand(expr: libcst_native::Expression) -> libcst_native::Expression {
match &expr {
_ if !expr.lpar().is_empty() => expr,
libcst_native::Expression::BooleanOperation(boolean_operation)
if matches!(
boolean_operation.operator,
libcst_native::BooleanOp::Or { .. }
) =>
{
expr.with_parens(
libcst_native::LeftParen::default(),
libcst_native::RightParen::default(),
)
}
libcst_native::Expression::IfExp(_)
| libcst_native::Expression::Lambda(_)
| libcst_native::Expression::NamedExpr(_) => expr.with_parens(
libcst_native::LeftParen::default(),
libcst_native::RightParen::default(),
),
_ => expr,
}
}
/// Convert `if a: if b:` to `if a and b:`.
pub(super) fn collapse_nested_if(
locator: &Locator,
stylist: &Stylist,
nested_if: NestedIf,
) -> Result<Edit> {
// Infer the indentation of the outer block.
let Some(outer_indent) = whitespace::indentation(locator, &nested_if) else {
bail!("Unable to fix multiline statement");
};
// Extract the module text.
let contents = locator.lines(nested_if.range());
// If this is an `elif`, we have to remove the `elif` keyword for now. (We'll
// restore the `el` later on.)
let module_text = if nested_if.is_elif() {
Cow::Owned(contents.replacen("elif", "if", 1))
} else {
Cow::Borrowed(contents)
};
// If the block is indented, "embed" it in a function definition, to preserve
// indentation while retaining valid source code. (We'll strip the prefix later
// on.)
let module_text = if outer_indent.is_empty() {
module_text
} else {
Cow::Owned(format!(
"def f():{}{module_text}",
stylist.line_ending().as_str()
))
};
// Parse the CST.
let mut tree = match_statement(&module_text)?;
let statement = if outer_indent.is_empty() {
&mut tree
} else {
let embedding = match_function_def(&mut tree)?;
let indented_block = match_indented_block(&mut embedding.body)?;
indented_block.indent = Some(outer_indent);
let Some(statement) = indented_block.body.first_mut() else {
bail!("Expected indented block to have at least one statement")
};
statement
};
let outer_if = match_if(statement)?;
let libcst_native::If {
body: libcst_native::Suite::IndentedBlock(ref mut outer_body),
orelse: None,
..
} = outer_if
else {
bail!("Expected outer if to have indented body and no else")
};
let [libcst_native::Statement::Compound(libcst_native::CompoundStatement::If(
inner_if @ libcst_native::If { orelse: None, .. },
))] = &mut *outer_body.body
else {
bail!("Expected one inner if statement");
};
outer_if.test =
libcst_native::Expression::BooleanOperation(Box::new(libcst_native::BooleanOperation {
left: Box::new(parenthesize_and_operand(outer_if.test.clone())),
operator: libcst_native::BooleanOp::And {
whitespace_before: space(),
whitespace_after: space(),
},
right: Box::new(parenthesize_and_operand(inner_if.test.clone())),
lpar: vec![],
rpar: vec![],
}));
outer_if.body = inner_if.body.clone();
// Reconstruct and reformat the code.
let module_text = tree.codegen_stylist(stylist);
let module_text = if outer_indent.is_empty() {
&module_text
} else {
module_text
.strip_prefix(&format!("def f():{}", stylist.line_ending().as_str()))
.unwrap()
};
let contents = if nested_if.is_elif() {
Cow::Owned(module_text.replacen("if", "elif", 1))
} else {
Cow::Borrowed(module_text)
};
let range = locator.lines_range(nested_if.range());
Ok(Edit::range_replacement(contents.to_string(), range))
}