-
Notifications
You must be signed in to change notification settings - Fork 903
/
missing_whitespace_around_operator.rs
348 lines (316 loc) · 11.1 KB
/
missing_whitespace_around_operator.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
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, DiagnosticKind, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_parser::TokenKind;
use ruff_text_size::Ranged;
use crate::checkers::logical_lines::LogicalLinesContext;
use crate::rules::pycodestyle::rules::logical_lines::LogicalLine;
/// ## What it does
/// Checks for missing whitespace around all operators.
///
/// ## Why is this bad?
/// According to [PEP 8], there should be one space before and after all
/// operators.
///
/// ## Example
/// ```python
/// if number==42:
/// print('you have found the meaning of life')
/// ```
///
/// Use instead:
/// ```python
/// if number == 42:
/// print('you have found the meaning of life')
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
// E225
#[violation]
pub struct MissingWhitespaceAroundOperator;
impl AlwaysFixableViolation for MissingWhitespaceAroundOperator {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing whitespace around operator")
}
fn fix_title(&self) -> String {
format!("Add missing whitespace")
}
}
/// ## What it does
/// Checks for missing whitespace arithmetic operators.
///
/// ## Why is this bad?
/// According to [PEP 8], there should be one space before and after an
/// arithmetic operator (+, -, /, and *).
///
/// ## Example
/// ```python
/// number = 40+2
/// ```
///
/// Use instead:
/// ```python
/// number = 40 + 2
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
// E226
#[violation]
pub struct MissingWhitespaceAroundArithmeticOperator;
impl AlwaysFixableViolation for MissingWhitespaceAroundArithmeticOperator {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing whitespace around arithmetic operator")
}
fn fix_title(&self) -> String {
format!("Add missing whitespace")
}
}
/// ## What it does
/// Checks for missing whitespace around bitwise and shift operators.
///
/// ## Why is this bad?
/// According to [PEP 8], there should be one space before and after bitwise and
/// shift operators (<<, >>, &, |, ^).
///
/// ## Example
/// ```python
/// x = 128<<1
/// ```
///
/// Use instead:
/// ```python
/// x = 128 << 1
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
// E227
#[violation]
pub struct MissingWhitespaceAroundBitwiseOrShiftOperator;
impl AlwaysFixableViolation for MissingWhitespaceAroundBitwiseOrShiftOperator {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing whitespace around bitwise or shift operator")
}
fn fix_title(&self) -> String {
format!("Add missing whitespace")
}
}
/// ## What it does
/// Checks for missing whitespace around the modulo operator.
///
/// ## Why is this bad?
/// According to [PEP 8], the modulo operator (%) should have whitespace on
/// either side of it.
///
/// ## Example
/// ```python
/// remainder = 10%2
/// ```
///
/// Use instead:
/// ```python
/// remainder = 10 % 2
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#other-recommendations
// E228
#[violation]
pub struct MissingWhitespaceAroundModuloOperator;
impl AlwaysFixableViolation for MissingWhitespaceAroundModuloOperator {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing whitespace around modulo operator")
}
fn fix_title(&self) -> String {
format!("Add missing whitespace")
}
}
/// E225, E226, E227, E228
pub(crate) fn missing_whitespace_around_operator(
line: &LogicalLine,
context: &mut LogicalLinesContext,
) {
let mut tokens = line.tokens().iter().peekable();
let first_token = tokens.by_ref().find(|token| !token.kind().is_trivia());
let Some(mut prev_token) = first_token else {
return;
};
let mut parens = u32::from(matches!(
prev_token.kind(),
TokenKind::Lpar | TokenKind::Lambda
));
let mut fstrings = u32::from(matches!(prev_token.kind(), TokenKind::FStringStart));
while let Some(token) = tokens.next() {
let kind = token.kind();
// There should not be a ")" directly after a token, as it is a syntax error. However if that happens,
// allow it in order to prevent entering a loop where E225 adds a space only for E202 to remove it.
if kind.is_trivia()
|| tokens
.peek()
.is_some_and(|token| token.kind() == TokenKind::Rpar)
{
continue;
}
match kind {
TokenKind::FStringStart => fstrings += 1,
TokenKind::FStringEnd => fstrings = fstrings.saturating_sub(1),
TokenKind::Lpar | TokenKind::Lambda => parens += 1,
TokenKind::Rpar => parens = parens.saturating_sub(1),
_ => {}
};
let needs_space = if kind == TokenKind::Equal && (parens > 0 || fstrings > 0) {
// Allow keyword args, defaults: foo(bar=None) and f-strings: f'{foo=}'
NeedsSpace::No
} else if kind == TokenKind::Slash {
// Tolerate the "/" operator in function definition
// For more info see PEP570
// `def f(a, /, b):` or `def f(a, b, /):` or `f = lambda a, /:`
// ^ ^ ^
let slash_in_func = matches!(
tokens.peek().map(|t| t.kind()),
Some(TokenKind::Comma | TokenKind::Rpar | TokenKind::Colon)
);
NeedsSpace::from(!slash_in_func)
} else if kind.is_unary() || matches!(kind, TokenKind::Star | TokenKind::DoubleStar) {
let is_binary = {
let prev_kind = prev_token.kind();
// Check if the operator is used as a binary operator.
// Allow unary operators: -123, -x, +1.
// Allow argument unpacking: foo(*args, **kwargs)
matches!(
prev_kind,
TokenKind::Rpar | TokenKind::Rsqb | TokenKind::Rbrace
) || !(prev_kind.is_operator()
|| prev_kind.is_keyword()
|| prev_kind.is_soft_keyword())
};
if is_binary {
if kind == TokenKind::DoubleStar {
// Enforce consistent spacing, but don't enforce whitespaces.
NeedsSpace::Optional
} else {
NeedsSpace::Yes
}
} else {
NeedsSpace::No
}
} else if is_whitespace_needed(kind) {
NeedsSpace::Yes
} else {
NeedsSpace::No
};
if needs_space != NeedsSpace::No {
let has_leading_trivia =
prev_token.end() < token.start() || prev_token.kind().is_trivia();
let has_trailing_trivia = tokens.peek().map_or(true, |next| {
token.end() < next.start() || next.kind().is_trivia()
});
match (has_leading_trivia, has_trailing_trivia) {
// Operator with trailing but no leading space, enforce consistent spacing.
(false, true) => {
let mut diagnostic =
Diagnostic::new(diagnostic_kind_for_operator(kind), token.range());
diagnostic.set_fix(Fix::safe_edit(Edit::insertion(
" ".to_string(),
token.start(),
)));
context.push_diagnostic(diagnostic);
}
// Operator with leading but no trailing space, enforce consistent spacing.
(true, false) => {
let mut diagnostic =
Diagnostic::new(diagnostic_kind_for_operator(kind), token.range());
diagnostic.set_fix(Fix::safe_edit(Edit::insertion(
" ".to_string(),
token.end(),
)));
context.push_diagnostic(diagnostic);
}
// Operator with no space, require spaces if it is required by the operator.
(false, false) => {
if needs_space == NeedsSpace::Yes {
let mut diagnostic =
Diagnostic::new(diagnostic_kind_for_operator(kind), token.range());
diagnostic.set_fix(Fix::safe_edits(
Edit::insertion(" ".to_string(), token.start()),
[Edit::insertion(" ".to_string(), token.end())],
));
context.push_diagnostic(diagnostic);
}
}
(true, true) => {
// Operator has leading and trailing spaces, all good.
}
}
}
prev_token = token;
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum NeedsSpace {
/// Needs a leading and trailing space.
Yes,
/// Doesn't need a leading or trailing space. Or in other words, we don't care how many
/// leading or trailing spaces that token has.
No,
/// Needs consistent leading and trailing spacing. The operator needs spacing if
/// * it has a leading space
/// * it has a trailing space
Optional,
}
impl From<bool> for NeedsSpace {
fn from(value: bool) -> Self {
if value {
NeedsSpace::Yes
} else {
NeedsSpace::No
}
}
}
fn diagnostic_kind_for_operator(operator: TokenKind) -> DiagnosticKind {
if operator == TokenKind::Percent {
DiagnosticKind::from(MissingWhitespaceAroundModuloOperator)
} else if operator.is_bitwise_or_shift() {
DiagnosticKind::from(MissingWhitespaceAroundBitwiseOrShiftOperator)
} else if operator.is_arithmetic() {
DiagnosticKind::from(MissingWhitespaceAroundArithmeticOperator)
} else {
DiagnosticKind::from(MissingWhitespaceAroundOperator)
}
}
fn is_whitespace_needed(kind: TokenKind) -> bool {
matches!(
kind,
TokenKind::DoubleStarEqual
| TokenKind::StarEqual
| TokenKind::SlashEqual
| TokenKind::DoubleSlashEqual
| TokenKind::PlusEqual
| TokenKind::MinusEqual
| TokenKind::NotEqual
| TokenKind::Less
| TokenKind::Greater
| TokenKind::PercentEqual
| TokenKind::CircumflexEqual
| TokenKind::AmperEqual
| TokenKind::VbarEqual
| TokenKind::EqEqual
| TokenKind::LessEqual
| TokenKind::GreaterEqual
| TokenKind::LeftShiftEqual
| TokenKind::RightShiftEqual
| TokenKind::Equal
| TokenKind::And
| TokenKind::Or
| TokenKind::In
| TokenKind::Is
| TokenKind::Rarrow
| TokenKind::ColonEqual
| TokenKind::Slash
| TokenKind::Percent
) || kind.is_arithmetic()
|| (kind.is_bitwise_or_shift() &&
// As a special-case, pycodestyle seems to ignore whitespace around the tilde.
!matches!(kind, TokenKind::Tilde))
}