-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathnative_literals.rs
261 lines (235 loc) · 8.5 KB
/
native_literals.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
use std::fmt;
use std::str::FromStr;
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::{
self as ast, Expr, Int, LiteralExpressionRef, StringLiteral, StringLiteralFlags,
StringLiteralValue, UnaryOp,
};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum LiteralType {
Str,
Bytes,
Int,
Float,
Bool,
}
impl FromStr for LiteralType {
type Err = ();
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"str" => Ok(LiteralType::Str),
"bytes" => Ok(LiteralType::Bytes),
"int" => Ok(LiteralType::Int),
"float" => Ok(LiteralType::Float),
"bool" => Ok(LiteralType::Bool),
_ => Err(()),
}
}
}
impl LiteralType {
fn as_zero_value_expr(self) -> Expr {
match self {
LiteralType::Str => ast::ExprStringLiteral {
value: StringLiteralValue::single(StringLiteral {
flags: StringLiteralFlags::default().with_dynamic(),
range: TextRange::default(),
value: "".into(),
}),
..ast::ExprStringLiteral::default()
}
.into(),
LiteralType::Bytes => ast::ExprBytesLiteral::default().into(),
LiteralType::Int => ast::ExprNumberLiteral {
value: ast::Number::Int(Int::from(0u8)),
range: TextRange::default(),
}
.into(),
LiteralType::Float => ast::ExprNumberLiteral {
value: ast::Number::Float(0.0),
range: TextRange::default(),
}
.into(),
LiteralType::Bool => ast::ExprBooleanLiteral::default().into(),
}
}
}
impl TryFrom<LiteralExpressionRef<'_>> for LiteralType {
type Error = ();
fn try_from(literal_expr: LiteralExpressionRef<'_>) -> Result<Self, Self::Error> {
match literal_expr {
LiteralExpressionRef::StringLiteral(_) => Ok(LiteralType::Str),
LiteralExpressionRef::BytesLiteral(_) => Ok(LiteralType::Bytes),
LiteralExpressionRef::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
match value {
ast::Number::Int(_) => Ok(LiteralType::Int),
ast::Number::Float(_) => Ok(LiteralType::Float),
ast::Number::Complex { .. } => Err(()),
}
}
LiteralExpressionRef::BooleanLiteral(_) => Ok(LiteralType::Bool),
LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => {
Err(())
}
}
}
}
impl fmt::Display for LiteralType {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
LiteralType::Str => fmt.write_str("str"),
LiteralType::Bytes => fmt.write_str("bytes"),
LiteralType::Int => fmt.write_str("int"),
LiteralType::Float => fmt.write_str("float"),
LiteralType::Bool => fmt.write_str("bool"),
}
}
}
/// ## What it does
/// Checks for unnecessary calls to `str`, `bytes`, `int`, `float`, and `bool`.
///
/// ## Why is this bad?
/// The mentioned constructors can be replaced with their respective literal
/// forms, which are more readable and idiomatic.
///
/// ## Example
/// ```python
/// str("foo")
/// ```
///
/// Use instead:
/// ```python
/// "foo"
/// ```
///
/// ## References
/// - [Python documentation: `str`](https://docs.python.org/3/library/stdtypes.html#str)
/// - [Python documentation: `bytes`](https://docs.python.org/3/library/stdtypes.html#bytes)
/// - [Python documentation: `int`](https://docs.python.org/3/library/functions.html#int)
/// - [Python documentation: `float`](https://docs.python.org/3/library/functions.html#float)
/// - [Python documentation: `bool`](https://docs.python.org/3/library/functions.html#bool)
#[derive(ViolationMetadata)]
pub(crate) struct NativeLiterals {
literal_type: LiteralType,
}
impl AlwaysFixableViolation for NativeLiterals {
#[derive_message_formats]
fn message(&self) -> String {
let NativeLiterals { literal_type } = self;
format!("Unnecessary `{literal_type}` call (rewrite as a literal)")
}
fn fix_title(&self) -> String {
let NativeLiterals { literal_type } = self;
match literal_type {
LiteralType::Str => "Replace with string literal".to_string(),
LiteralType::Bytes => "Replace with bytes literal".to_string(),
LiteralType::Int => "Replace with integer literal".to_string(),
LiteralType::Float => "Replace with float literal".to_string(),
LiteralType::Bool => "Replace with boolean literal".to_string(),
}
}
}
/// UP018
pub(crate) fn native_literals(
checker: &mut Checker,
call: &ast::ExprCall,
parent_expr: Option<&ast::Expr>,
) {
let ast::ExprCall {
func,
arguments:
ast::Arguments {
args,
keywords,
range: _,
},
range: _,
} = call;
if !keywords.is_empty() || args.len() > 1 {
return;
}
let semantic = checker.semantic();
let Some(builtin) = semantic.resolve_builtin_symbol(func) else {
return;
};
let Ok(literal_type) = LiteralType::from_str(builtin) else {
return;
};
// There's no way to rewrite, e.g., `f"{f'{str()}'}"` within a nested f-string.
if semantic.in_f_string() {
if semantic
.current_expressions()
.filter(|expr| expr.is_f_string_expr())
.count()
> 1
{
return;
}
}
match args.first() {
None => {
let mut diagnostic = Diagnostic::new(NativeLiterals { literal_type }, call.range());
// Do not suggest fix for attribute access on an int like `int().attribute`
// Ex) `int().denominator` is valid but `0.denominator` is not
if literal_type == LiteralType::Int && matches!(parent_expr, Some(Expr::Attribute(_))) {
return;
}
let expr = literal_type.as_zero_value_expr();
let content = checker.generator().expr(&expr);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
content,
call.range(),
)));
checker.diagnostics.push(diagnostic);
}
Some(arg) => {
let literal_expr = if let Some(literal_expr) = arg.as_literal_expr() {
// Skip implicit concatenated strings.
if literal_expr.is_implicit_concatenated() {
return;
}
literal_expr
} else if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::UAdd | UnaryOp::USub,
operand,
..
}) = arg
{
if let Some(literal_expr) = operand
.as_literal_expr()
.filter(|expr| matches!(expr, LiteralExpressionRef::NumberLiteral(_)))
{
literal_expr
} else {
// Only allow unary operators for numbers.
return;
}
} else {
return;
};
let Ok(arg_literal_type) = LiteralType::try_from(literal_expr) else {
return;
};
if arg_literal_type != literal_type {
return;
}
let arg_code = checker.locator().slice(arg);
// Attribute access on an integer requires the integer to be parenthesized to disambiguate from a float
// Ex) `(7).denominator` is valid but `7.denominator` is not
// Note that floats do not have this problem
// Ex) `(1.0).real` is valid and `1.0.real` is too
let content = match (parent_expr, literal_type) {
(Some(Expr::Attribute(_)), LiteralType::Int) => format!("({arg_code})"),
_ => arg_code.to_string(),
};
let mut diagnostic = Diagnostic::new(NativeLiterals { literal_type }, call.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
content,
call.range(),
)));
checker.diagnostics.push(diagnostic);
}
}
}