-
Notifications
You must be signed in to change notification settings - Fork 903
/
f_strings.rs
446 lines (405 loc) · 14.1 KB
/
f_strings.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::borrow::Cow;
use anyhow::{Context, Result};
use rustc_hash::FxHashMap;
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::str::{leading_quote, trailing_quote};
use ruff_python_ast::{self as ast, Constant, Expr, Keyword};
use ruff_python_literal::format::{
FieldName, FieldNamePart, FieldType, FormatPart, FormatString, FromTemplate,
};
use ruff_python_parser::{lexer, Mode, Tok};
use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::fits_or_shrinks;
use crate::rules::pyflakes::format::FormatSummary;
use crate::rules::pyupgrade::helpers::curly_escape;
/// ## What it does
/// Checks for `str.format` calls that can be replaced with f-strings.
///
/// ## Why is this bad?
/// f-strings are more readable and generally preferred over `str.format`
/// calls.
///
/// ## Example
/// ```python
/// "{}".format(foo)
/// ```
///
/// Use instead:
/// ```python
/// f"{foo}"
/// ```
///
/// ## References
/// - [Python documentation: f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
#[violation]
pub struct FString;
impl Violation for FString {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("Use f-string instead of `format` call")
}
fn fix_title(&self) -> Option<String> {
Some("Convert to f-string".to_string())
}
}
/// Like [`FormatSummary`], but maps positional and keyword arguments to their
/// values. For example, given `{a} {b}".format(a=1, b=2)`, `FormatFunction`
/// would include `"a"` and `'b'` in `kwargs`, mapped to `1` and `2`
/// respectively.
#[derive(Debug)]
struct FormatSummaryValues<'a> {
args: Vec<&'a Expr>,
kwargs: FxHashMap<&'a str, &'a Expr>,
auto_index: usize,
}
impl<'a> FormatSummaryValues<'a> {
fn try_from_call(call: &'a ast::ExprCall, locator: &'a Locator) -> Option<Self> {
let mut extracted_args: Vec<&Expr> = Vec::new();
let mut extracted_kwargs: FxHashMap<&str, &Expr> = FxHashMap::default();
for arg in &call.arguments.args {
if matches!(arg, Expr::Starred(..))
|| contains_quotes(locator.slice(arg))
|| locator.contains_line_break(arg.range())
{
return None;
}
extracted_args.push(arg);
}
for keyword in &call.arguments.keywords {
let Keyword {
arg,
value,
range: _,
} = keyword;
let Some(key) = arg else {
return None;
};
if contains_quotes(locator.slice(value)) || locator.contains_line_break(value.range()) {
return None;
}
extracted_kwargs.insert(key, value);
}
if extracted_args.is_empty() && extracted_kwargs.is_empty() {
return None;
}
Some(Self {
args: extracted_args,
kwargs: extracted_kwargs,
auto_index: 0,
})
}
/// Return the next positional argument.
fn arg_auto(&mut self) -> Option<&Expr> {
let idx = self.auto_index;
self.auto_index += 1;
self.arg_positional(idx)
}
/// Return the positional argument at the given index.
fn arg_positional(&self, index: usize) -> Option<&Expr> {
self.args.get(index).copied()
}
/// Return the keyword argument with the given name.
fn arg_keyword(&self, key: &str) -> Option<&Expr> {
self.kwargs.get(key).copied()
}
}
/// Return `true` if the string contains quotes.
fn contains_quotes(string: &str) -> bool {
string.contains(['\'', '"'])
}
enum FormatContext {
/// The expression is used as a bare format spec (e.g., `{x}`).
Bare,
/// The expression is used with conversion flags, or attribute or subscript access
/// (e.g., `{x!r}`, `{x.y}`, `{x[y]}`).
Accessed,
}
/// Given an [`Expr`], format it for use in a formatted expression within an f-string.
fn formatted_expr<'a>(expr: &Expr, context: FormatContext, locator: &Locator<'a>) -> Cow<'a, str> {
let text = locator.slice(expr);
let parenthesize = match (context, expr) {
// E.g., `x + y` should be parenthesized in `f"{(x + y)[0]}"`.
(
FormatContext::Accessed,
Expr::BinOp(_)
| Expr::UnaryOp(_)
| Expr::BoolOp(_)
| Expr::NamedExpr(_)
| Expr::Compare(_)
| Expr::IfExp(_)
| Expr::Lambda(_)
| Expr::Await(_)
| Expr::Yield(_)
| Expr::YieldFrom(_)
| Expr::Starred(_),
) => true,
// E.g., `12` should be parenthesized in `f"{(12).real}"`.
(
FormatContext::Accessed,
Expr::Constant(ast::ExprConstant {
value: Constant::Int(..),
..
}),
) => text.chars().all(|c| c.is_ascii_digit()),
// E.g., `{x, y}` should be parenthesized in `f"{(x, y)}"`.
(
_,
Expr::GeneratorExp(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::SetComp(_)
| Expr::DictComp(_),
) => true,
_ => false,
};
if parenthesize && !text.starts_with('(') && !text.ends_with(')') {
Cow::Owned(format!("({text})"))
} else {
Cow::Borrowed(text)
}
}
/// Convert a string `.format` call to an f-string.
///
/// Returns `None` if the string does not require conversion, and `Err` if the conversion
/// is not possible.
fn try_convert_to_f_string(
range: TextRange,
summary: &mut FormatSummaryValues,
locator: &Locator,
) -> Result<Option<String>> {
// Strip the unicode prefix. It's redundant in Python 3, and invalid when used
// with f-strings.
let contents = locator.slice(range);
let contents = if contents.starts_with('U') || contents.starts_with('u') {
&contents[1..]
} else {
contents
};
// Remove the leading and trailing quotes.
let leading_quote = leading_quote(contents).context("Unable to identify leading quote")?;
let trailing_quote = trailing_quote(contents).context("Unable to identify trailing quote")?;
let contents = &contents[leading_quote.len()..contents.len() - trailing_quote.len()];
if contents.is_empty() {
return Ok(None);
}
// Parse the format string.
let format_string = FormatString::from_str(contents)?;
if format_string
.format_parts
.iter()
.all(|part| matches!(part, FormatPart::Literal(..)))
{
return Ok(None);
}
let mut converted = String::with_capacity(contents.len());
for part in format_string.format_parts {
match part {
FormatPart::Field {
field_name,
conversion_spec,
format_spec,
} => {
converted.push('{');
let field = FieldName::parse(&field_name)?;
let arg = match field.field_type {
FieldType::Auto => summary.arg_auto(),
FieldType::Index(index) => summary.arg_positional(index),
FieldType::Keyword(name) => summary.arg_keyword(&name),
}
.context("Unable to parse field")?;
converted.push_str(&formatted_expr(
arg,
if field.parts.is_empty() {
FormatContext::Bare
} else {
FormatContext::Accessed
},
locator,
));
for part in field.parts {
match part {
FieldNamePart::Attribute(name) => {
converted.push('.');
converted.push_str(&name);
}
FieldNamePart::Index(index) => {
converted.push('[');
converted.push_str(index.to_string().as_str());
converted.push(']');
}
FieldNamePart::StringIndex(index) => {
let quote = match *trailing_quote {
"'" | "'''" | "\"\"\"" => '"',
"\"" => '\'',
_ => unreachable!("invalid trailing quote"),
};
converted.push('[');
converted.push(quote);
converted.push_str(&index);
converted.push(quote);
converted.push(']');
}
}
}
if let Some(conversion_spec) = conversion_spec {
converted.push('!');
converted.push(conversion_spec);
}
if !format_spec.is_empty() {
converted.push(':');
converted.push_str(&format_spec);
}
converted.push('}');
}
FormatPart::Literal(value) => {
converted.push_str(&curly_escape(&value));
}
}
}
// Construct the format string.
let mut contents = String::with_capacity(1 + converted.len());
contents.push('f');
contents.push_str(leading_quote);
contents.push_str(&converted);
contents.push_str(trailing_quote);
Ok(Some(contents))
}
/// UP032
pub(crate) fn f_strings(
checker: &mut Checker,
call: &ast::ExprCall,
summary: &FormatSummary,
template: &Expr,
) {
if summary.has_nested_parts {
return;
}
let Expr::Attribute(ast::ExprAttribute { value, .. }) = call.func.as_ref() else {
return;
};
if !matches!(
value.as_ref(),
Expr::Constant(ast::ExprConstant {
value: Constant::Str(..),
..
}),
) {
return;
};
let Some(mut summary) = FormatSummaryValues::try_from_call(call, checker.locator()) else {
return;
};
let mut patches: Vec<(TextRange, String)> = vec![];
let mut lex = lexer::lex_starts_at(
checker.locator().slice(call.func.range()),
Mode::Expression,
call.start(),
)
.flatten();
let end = loop {
match lex.next() {
Some((Tok::Dot, range)) => {
// ```
// (
// "a"
// " {} "
// "b"
// ).format(x)
// ```
// ^ Get the position of the character before the dot.
//
// We know that the expression is a string literal, so we can safely assume that the
// dot is the start of an attribute access.
break range.start();
}
Some((Tok::String { .. }, range)) => {
match try_convert_to_f_string(range, &mut summary, checker.locator()) {
Ok(Some(fstring)) => patches.push((range, fstring)),
// Skip any strings that don't require conversion (e.g., literal segments of an
// implicit concatenation).
Ok(None) => continue,
// If any of the segments fail to convert, then we can't convert the entire
// expression.
Err(_) => return,
}
}
Some(_) => continue,
None => unreachable!("Should break from the `Tok::Dot` arm"),
}
};
if patches.is_empty() {
return;
}
let mut contents = String::with_capacity(checker.locator().slice(call).len());
let mut prev_end = call.start();
for (range, fstring) in patches {
contents.push_str(
checker
.locator()
.slice(TextRange::new(prev_end, range.start())),
);
contents.push_str(&fstring);
prev_end = range.end();
}
contents.push_str(checker.locator().slice(TextRange::new(prev_end, end)));
// If necessary, add a space between any leading keyword (`return`, `yield`, `assert`, etc.)
// and the string. For example, `return"foo"` is valid, but `returnf"foo"` is not.
let existing = checker.locator().slice(TextRange::up_to(call.start()));
if existing
.chars()
.last()
.is_some_and(|char| char.is_ascii_alphabetic())
{
contents.insert(0, ' ');
}
// Avoid refactors that exceed the line length limit.
if !fits_or_shrinks(
&contents,
template.into(),
checker.locator(),
checker.settings.pycodestyle.max_line_length,
checker.settings.tab_size,
) {
return;
}
// Finally, avoid refactors that would introduce a runtime error.
// For example, Django's `gettext` supports `format`-style arguments, but not f-strings.
// See: https://docs.djangoproject.com/en/4.2/topics/i18n/translation
if checker.semantic().current_expressions().any(|expr| {
expr.as_call_expr().is_some_and(|call| {
checker
.semantic()
.resolve_call_path(call.func.as_ref())
.map_or(false, |call_path| {
matches!(
call_path.as_slice(),
["django", "utils", "translation", "gettext" | "gettext_lazy"]
)
})
})
}) {
return;
}
let mut diagnostic = Diagnostic::new(FString, call.range());
// Avoid fix if there are comments within the call:
// ```
// "{}".format(
// 0, # 0
// )
// ```
if !checker
.indexer()
.comment_ranges()
.intersects(call.arguments.range())
{
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
contents,
call.range(),
)));
};
checker.diagnostics.push(diagnostic);
}