forked from astral-sh/ruff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extraneous_whitespace.rs
292 lines (276 loc) · 11.6 KB
/
extraneous_whitespace.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
use ruff_diagnostics::AlwaysFixableViolation;
use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::Edit;
use ruff_diagnostics::Fix;
use ruff_macros::{derive_message_formats, violation};
use ruff_python_parser::TokenKind;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::logical_lines::LogicalLinesContext;
use super::{LogicalLine, Whitespace};
/// ## What it does
/// Checks for the use of extraneous whitespace after "(".
///
/// ## Why is this bad?
/// [PEP 8] recommends the omission of whitespace in the following cases:
/// - "Immediately inside parentheses, brackets or braces."
/// - "Immediately before a comma, semicolon, or colon."
///
/// ## Example
/// ```python
/// spam( ham[1], {eggs: 2})
/// spam(ham[ 1], {eggs: 2})
/// spam(ham[1], { eggs: 2})
/// ```
///
/// Use instead:
/// ```python
/// spam(ham[1], {eggs: 2})
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
#[violation]
pub struct WhitespaceAfterOpenBracket {
symbol: char,
}
impl AlwaysFixableViolation for WhitespaceAfterOpenBracket {
#[derive_message_formats]
fn message(&self) -> String {
let WhitespaceAfterOpenBracket { symbol } = self;
format!("Whitespace after '{symbol}'")
}
fn fix_title(&self) -> String {
let WhitespaceAfterOpenBracket { symbol } = self;
format!("Remove whitespace before '{symbol}'")
}
}
/// ## What it does
/// Checks for the use of extraneous whitespace before ")".
///
/// ## Why is this bad?
/// [PEP 8] recommends the omission of whitespace in the following cases:
/// - "Immediately inside parentheses, brackets or braces."
/// - "Immediately before a comma, semicolon, or colon."
///
/// ## Example
/// ```python
/// spam(ham[1], {eggs: 2} )
/// spam(ham[1 ], {eggs: 2})
/// spam(ham[1], {eggs: 2 })
/// ```
///
/// Use instead:
/// ```python
/// spam(ham[1], {eggs: 2})
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
#[violation]
pub struct WhitespaceBeforeCloseBracket {
symbol: char,
}
impl AlwaysFixableViolation for WhitespaceBeforeCloseBracket {
#[derive_message_formats]
fn message(&self) -> String {
let WhitespaceBeforeCloseBracket { symbol } = self;
format!("Whitespace before '{symbol}'")
}
fn fix_title(&self) -> String {
let WhitespaceBeforeCloseBracket { symbol } = self;
format!("Remove whitespace before '{symbol}'")
}
}
/// ## What it does
/// Checks for the use of extraneous whitespace before ",", ";" or ":".
///
/// ## Why is this bad?
/// [PEP 8] recommends the omission of whitespace in the following cases:
/// - "Immediately inside parentheses, brackets or braces."
/// - "Immediately before a comma, semicolon, or colon."
///
/// ## Example
/// ```python
/// if x == 4: print(x, y); x, y = y , x
/// ```
///
/// Use instead:
/// ```python
/// if x == 4: print(x, y); x, y = y, x
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#pet-peeves
#[violation]
pub struct WhitespaceBeforePunctuation {
symbol: char,
}
impl AlwaysFixableViolation for WhitespaceBeforePunctuation {
#[derive_message_formats]
fn message(&self) -> String {
let WhitespaceBeforePunctuation { symbol } = self;
format!("Whitespace before '{symbol}'")
}
fn fix_title(&self) -> String {
let WhitespaceBeforePunctuation { symbol } = self;
format!("Remove whitespace before '{symbol}'")
}
}
/// E201, E202, E203
pub(crate) fn extraneous_whitespace(line: &LogicalLine, context: &mut LogicalLinesContext) {
let mut fstrings = 0u32;
let mut brackets = vec![];
let mut prev_token = None;
let mut iter = line.tokens().iter().peekable();
while let Some(token) = iter.next() {
let kind = token.kind();
match kind {
TokenKind::FStringStart => fstrings += 1,
TokenKind::FStringEnd => fstrings = fstrings.saturating_sub(1),
TokenKind::Lsqb if fstrings == 0 => {
brackets.push(kind);
}
TokenKind::Rsqb if fstrings == 0 => {
brackets.pop();
}
TokenKind::Lbrace if fstrings == 0 => {
brackets.push(kind);
}
TokenKind::Rbrace if fstrings == 0 => {
brackets.pop();
}
_ => {}
}
if let Some(symbol) = BracketOrPunctuation::from_kind(kind) {
// Whitespace before "{" or after "}" might be required in f-strings.
// For example,
//
// ```python
// f"{ {'a': 1} }"
// ```
//
// Here, `{{` / `}} would be interpreted as a single raw `{` / `}`
// character.
match symbol {
BracketOrPunctuation::OpenBracket(symbol) if symbol != '{' || fstrings == 0 => {
let (trailing, trailing_len) = line.trailing_whitespace(token);
if !matches!(trailing, Whitespace::None) {
let mut diagnostic = Diagnostic::new(
WhitespaceAfterOpenBracket { symbol },
TextRange::at(token.end(), trailing_len),
);
diagnostic
.set_fix(Fix::safe_edit(Edit::range_deletion(diagnostic.range())));
context.push_diagnostic(diagnostic);
}
}
BracketOrPunctuation::CloseBracket(symbol) if symbol != '}' || fstrings == 0 => {
if !matches!(prev_token, Some(TokenKind::Comma)) {
if let (Whitespace::Single | Whitespace::Many | Whitespace::Tab, offset) =
line.leading_whitespace(token)
{
let mut diagnostic = Diagnostic::new(
WhitespaceBeforeCloseBracket { symbol },
TextRange::at(token.start() - offset, offset),
);
diagnostic
.set_fix(Fix::safe_edit(Edit::range_deletion(diagnostic.range())));
context.push_diagnostic(diagnostic);
}
}
}
BracketOrPunctuation::Punctuation(symbol) => {
if !matches!(prev_token, Some(TokenKind::Comma)) {
let whitespace = line.leading_whitespace(token);
if let (Whitespace::Single | Whitespace::Many | Whitespace::Tab, offset) =
whitespace
{
// If we're in a slice, and the token is a colon, and it has
// equivalent spacing on both sides, allow it.
if symbol == ':'
&& brackets
.last()
.is_some_and(|kind| matches!(kind, TokenKind::Lsqb))
{
// If we're in the second half of a double colon, disallow
// any whitespace (e.g., `foo[1: :2]` or `foo[1 : : 2]`).
if matches!(prev_token, Some(TokenKind::Colon)) {
let mut diagnostic = Diagnostic::new(
WhitespaceBeforePunctuation { symbol },
TextRange::at(token.start() - offset, offset),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(
diagnostic.range(),
)));
context.push_diagnostic(diagnostic);
} else if iter.peek().is_some_and(|token| {
matches!(token.kind(), TokenKind::Rsqb | TokenKind::Comma)
}) {
// Allow `foo[1 :]`, but not `foo[1 :]`.
// Or `foo[index :, 2]`, but not `foo[index :, 2]`.
if let (Whitespace::Many | Whitespace::Tab, offset) = whitespace
{
let mut diagnostic = Diagnostic::new(
WhitespaceBeforePunctuation { symbol },
TextRange::at(token.start() - offset, offset),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(
diagnostic.range(),
)));
context.push_diagnostic(diagnostic);
}
} else {
// Allow, e.g., `foo[1:2]` or `foo[1 : 2]` or `foo[1 :: 2]`.
let token = iter
.peek()
.filter(|next| matches!(next.kind(), TokenKind::Colon))
.unwrap_or(&token);
if line.trailing_whitespace(token) != whitespace {
let mut diagnostic = Diagnostic::new(
WhitespaceBeforePunctuation { symbol },
TextRange::at(token.start() - offset, offset),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(
diagnostic.range(),
)));
context.push_diagnostic(diagnostic);
}
}
} else {
let mut diagnostic = Diagnostic::new(
WhitespaceBeforePunctuation { symbol },
TextRange::at(token.start() - offset, offset),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(
diagnostic.range(),
)));
context.push_diagnostic(diagnostic);
}
}
}
}
_ => {}
}
}
prev_token = Some(kind);
}
}
#[derive(Debug)]
enum BracketOrPunctuation {
OpenBracket(char),
CloseBracket(char),
Punctuation(char),
}
impl BracketOrPunctuation {
fn from_kind(kind: TokenKind) -> Option<BracketOrPunctuation> {
match kind {
TokenKind::Lbrace => Some(BracketOrPunctuation::OpenBracket('{')),
TokenKind::Lpar => Some(BracketOrPunctuation::OpenBracket('(')),
TokenKind::Lsqb => Some(BracketOrPunctuation::OpenBracket('[')),
TokenKind::Rbrace => Some(BracketOrPunctuation::CloseBracket('}')),
TokenKind::Rpar => Some(BracketOrPunctuation::CloseBracket(')')),
TokenKind::Rsqb => Some(BracketOrPunctuation::CloseBracket(']')),
TokenKind::Comma => Some(BracketOrPunctuation::Punctuation(',')),
TokenKind::Colon => Some(BracketOrPunctuation::Punctuation(':')),
TokenKind::Semi => Some(BracketOrPunctuation::Punctuation(';')),
_ => None,
}
}
}