-
Notifications
You must be signed in to change notification settings - Fork 897
/
unintentional_type_annotation.rs
66 lines (61 loc) · 1.76 KB
/
unintentional_type_annotation.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
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for the unintentional use of type annotations.
///
/// ## Why is this bad?
/// The use of a colon (`:`) in lieu of an assignment (`=`) can be syntactically valid, but
/// is almost certainly a mistake when used in a subscript or attribute assignment.
///
/// ## Example
/// ```python
/// a["b"]: 1
/// ```
///
/// Use instead:
/// ```python
/// a["b"] = 1
/// ```
#[violation]
pub struct UnintentionalTypeAnnotation;
impl Violation for UnintentionalTypeAnnotation {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Possible unintentional type annotation (using `:`). Did you mean to assign (using `=`)?"
)
}
}
/// B032
pub(crate) fn unintentional_type_annotation(
checker: &mut Checker,
target: &Expr,
value: Option<&Expr>,
stmt: &Stmt,
) {
if value.is_some() {
return;
}
match target {
Expr::Subscript(ast::ExprSubscript { value, .. }) => {
if value.is_name_expr() {
checker
.diagnostics
.push(Diagnostic::new(UnintentionalTypeAnnotation, stmt.range()));
}
}
Expr::Attribute(ast::ExprAttribute { value, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() {
if id.as_str() != "self" {
checker
.diagnostics
.push(Diagnostic::new(UnintentionalTypeAnnotation, stmt.range()));
}
}
}
_ => {}
};
}