-
Notifications
You must be signed in to change notification settings - Fork 903
/
missing_whitespace_after_keyword.rs
74 lines (67 loc) · 2.29 KB
/
missing_whitespace_after_keyword.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
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, 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 after keywords.
///
/// ## Why is this bad?
/// Missing whitespace after keywords makes the code harder to read.
///
/// ## Example
/// ```python
/// if(True):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// if (True):
/// pass
/// ```
///
/// ## References
/// - [Python documentation: Keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords)
#[violation]
pub struct MissingWhitespaceAfterKeyword;
impl AlwaysFixableViolation for MissingWhitespaceAfterKeyword {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing whitespace after keyword")
}
fn fix_title(&self) -> String {
format!("Added missing whitespace after keyword")
}
}
/// E275
pub(crate) fn missing_whitespace_after_keyword(
line: &LogicalLine,
context: &mut LogicalLinesContext,
) {
for window in line.tokens().windows(2) {
let tok0 = &window[0];
let tok1 = &window[1];
let tok0_kind = tok0.kind();
let tok1_kind = tok1.kind();
if tok0_kind.is_keyword()
&& !(tok0_kind.is_singleton()
|| matches!(tok0_kind, TokenKind::Async | TokenKind::Await)
|| tok0_kind == TokenKind::Except && tok1_kind == TokenKind::Star
|| tok0_kind == TokenKind::Yield && tok1_kind == TokenKind::Rpar
|| matches!(
tok1_kind,
TokenKind::Colon
| TokenKind::Newline
| TokenKind::NonLogicalNewline
| TokenKind::Rpar // In case of a syntax error, do not attempt to add a whitespace.
))
&& tok0.end() == tok1.start()
{
let mut diagnostic = Diagnostic::new(MissingWhitespaceAfterKeyword, tok0.range());
diagnostic.set_fix(Fix::safe_edit(Edit::insertion(" ".to_string(), tok0.end())));
context.push_diagnostic(diagnostic);
}
}
}