-
Notifications
You must be signed in to change notification settings - Fork 901
/
unnecessary_literal_union.rs
170 lines (151 loc) · 5.52 KB
/
unnecessary_literal_union.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
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::pep_604_union;
use ruff_python_ast::{self as ast, Expr, ExprContext};
use ruff_python_semantic::analyze::typing::traverse_union;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for the presence of multiple literal types in a union.
///
/// ## Why is this bad?
/// `Literal["foo", 42]` has identical semantics to
/// `Literal["foo"] | Literal[42]`, but is clearer and more concise.
///
/// ## Example
/// ```python
/// from typing import Literal
///
/// field: Literal[1] | Literal[2] | str
/// ```
///
/// Use instead:
/// ```python
/// from typing import Literal
///
/// field: Literal[1, 2] | str
/// ```
///
/// ## References
/// - [Python documentation: `typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)
#[violation]
pub struct UnnecessaryLiteralUnion {
members: Vec<String>,
}
impl Violation for UnnecessaryLiteralUnion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]`",
self.members.join(", ")
)
}
fn fix_title(&self) -> Option<String> {
Some(format!("Replace with a single `Literal`",))
}
}
/// PYI030
pub(crate) fn unnecessary_literal_union<'a>(checker: &mut Checker, expr: &'a Expr) {
let mut literal_exprs = Vec::new();
let mut other_exprs = Vec::new();
// For the sake of consistency, use the first `Literal` subscript to construct the fix.
let mut literal_subscript = None;
let mut total_literals = 0;
// Split members into `literal_exprs` if they are a `Literal` annotation and `other_exprs` otherwise
let mut collect_literal_expr = |expr: &'a Expr, _parent: &'a Expr| {
if let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr {
if checker.semantic().match_typing_expr(value, "Literal") {
total_literals += 1;
if literal_subscript.is_none() {
literal_subscript = Some(value.as_ref());
}
// flatten already-unioned literals to later union again
if let Expr::Tuple(ast::ExprTuple {
elts,
range: _,
ctx: _,
parenthesized: _,
}) = slice.as_ref()
{
for expr in elts {
literal_exprs.push(expr);
}
} else {
literal_exprs.push(slice.as_ref());
}
}
} else {
other_exprs.push(expr);
}
};
// Traverse the union, collect all members, split out the literals from the rest.
traverse_union(&mut collect_literal_expr, checker.semantic(), expr);
let union_subscript = expr.as_subscript_expr();
if union_subscript.is_some_and(|subscript| {
!checker
.semantic()
.match_typing_expr(&subscript.value, "Union")
}) {
return;
}
// If there are no literal members, we don't need to do anything.
let Some(literal_subscript) = literal_subscript else {
return;
};
if total_literals == 0 || total_literals == 1 {
return;
}
let mut diagnostic = Diagnostic::new(
UnnecessaryLiteralUnion {
members: literal_exprs
.iter()
.map(|expr| checker.locator().slice(expr).to_string())
.collect(),
},
expr.range(),
);
diagnostic.set_fix({
let literal = Expr::Subscript(ast::ExprSubscript {
value: Box::new(literal_subscript.clone()),
slice: Box::new(Expr::Tuple(ast::ExprTuple {
elts: literal_exprs.into_iter().cloned().collect(),
range: TextRange::default(),
ctx: ExprContext::Load,
parenthesized: true,
})),
range: TextRange::default(),
ctx: ExprContext::Load,
});
if other_exprs.is_empty() {
// if the union is only literals, we just replace the whole thing with a single literal
Fix::safe_edit(Edit::range_replacement(
checker.generator().expr(&literal),
expr.range(),
))
} else {
let elts: Vec<Expr> = std::iter::once(literal)
.chain(other_exprs.into_iter().cloned())
.collect();
let content = if let Some(union) = union_subscript {
checker
.generator()
.expr(&Expr::Subscript(ast::ExprSubscript {
value: union.value.clone(),
slice: Box::new(Expr::Tuple(ast::ExprTuple {
elts,
range: TextRange::default(),
ctx: ExprContext::Load,
parenthesized: true,
})),
range: TextRange::default(),
ctx: ExprContext::Load,
}))
} else {
checker.generator().expr(&pep_604_union(&elts))
};
Fix::safe_edit(Edit::range_replacement(content, expr.range()))
}
});
checker.diagnostics.push(diagnostic);
}