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
use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType};
use ruff_python_semantic::analyze::typing::find_binding_value;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `len` calls on sequences in a boolean test context.
///
/// ## Why is this bad?
/// Empty sequences are considered false in a boolean context.
/// You can either remove the call to `len`
/// or compare the length against a scalar.
///
/// ## Example
/// ```python
/// fruits = ["orange", "apple"]
/// vegetables = []
///
/// if len(fruits):
/// print(fruits)
///
/// if not len(vegetables):
/// print(vegetables)
/// ```
///
/// Use instead:
/// ```python
/// fruits = ["orange", "apple"]
/// vegetables = []
///
/// if fruits:
/// print(fruits)
///
/// if not vegetables:
/// print(vegetables)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe when the `len` call includes a comment,
/// as the comment would be removed.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// fruits = []
/// if len(
/// fruits # comment
/// ):
/// ...
/// ```
///
/// ## References
/// [PEP 8: Programming Recommendations](https://peps.python.org/pep-0008/#programming-recommendations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct LenTest {
expression: SourceCodeSnippet,
}
impl AlwaysFixableViolation for LenTest {
#[derive_message_formats]
fn message(&self) -> String {
if let Some(expression) = self.expression.full_display() {
format!("`len({expression})` used as condition without comparison")
} else {
"`len(SEQUENCE)` used as condition without comparison".to_string()
}
}
fn fix_title(&self) -> String {
"Remove `len`".to_string()
}
}
/// PLC1802
pub(crate) fn len_test(checker: &Checker, call: &ExprCall) {
let ExprCall {
func, arguments, ..
} = call;
let semantic = checker.semantic();
if !semantic.in_boolean_test() {
return;
}
if !semantic.match_builtin_expr(func, "len") {
return;
}
// Single argument and no keyword arguments
let [argument] = &*arguments.args else { return };
if !arguments.keywords.is_empty() {
return;
}
// Simple inferred sequence type (e.g., list, set, dict, tuple, string, bytes, varargs, kwargs).
if !is_sequence(argument, semantic) && !is_indirect_sequence(argument, semantic) {
return;
}
let replacement = checker.locator().slice(argument.range()).to_string();
checker
.report_diagnostic(
LenTest {
expression: SourceCodeSnippet::new(replacement.clone()),
},
call.range(),
)
.set_fix(Fix::applicable_edit(
Edit::range_replacement(
edits::pad(replacement, call.range(), checker.locator()),
call.range(),
),
if checker.comment_ranges().intersects(call.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
));
}
fn is_indirect_sequence(expr: &Expr, semantic: &SemanticModel) -> bool {
let Expr::Name(ast::ExprName { id: name, .. }) = expr else {
return false;
};
let scope = semantic.current_scope();
let Some(binding_id) = scope.get(name) else {
return false;
};
let binding = semantic.binding(binding_id);
// Attempt to find the binding's value
let Some(binding_value) = find_binding_value(binding, semantic) else {
// If the binding is not an argument, return false
if !binding.kind.is_argument() {
return false;
}
// Attempt to retrieve the function definition statement
let Some(function) = binding
.statement(semantic)
.and_then(|statement| statement.as_function_def_stmt())
else {
return false;
};
// If not find in non-default params, it must be varargs or kwargs
return function.parameters.find(name).is_none();
};
// If `binding_value` is found, check if it is a sequence
is_sequence(binding_value, semantic)
}
fn is_sequence(expr: &Expr, semantic: &SemanticModel) -> bool {
// Check if the expression type is a direct sequence match (dict, list, set, tuple, string or bytes)
if matches!(
ResolvedPythonType::from(expr),
ResolvedPythonType::Atom(
PythonType::Dict
| PythonType::List
| PythonType::Set
| PythonType::Tuple
| PythonType::String
| PythonType::Bytes
)
) {
return true;
}
// Check if the expression is a function call to a built-in sequence constructor
let Some(ExprCall { func, .. }) = expr.as_call_expr() else {
return false;
};
// Match against specific built-in constructors that return sequences
semantic.resolve_builtin_symbol(func).is_some_and(|func| {
matches!(
func,
"chr"
| "format"
| "input"
| "repr"
| "str"
| "list"
| "dir"
| "locals"
| "globals"
| "vars"
| "dict"
| "set"
| "frozenset"
| "tuple"
| "range"
| "bin"
| "bytes"
| "bytearray"
| "hex"
| "memoryview"
| "oct"
| "ascii"
| "sorted"
)
})
}