-
Notifications
You must be signed in to change notification settings - Fork 882
/
check_string_quotes.rs
479 lines (435 loc) · 15.5 KB
/
check_string_quotes.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::StringLike;
use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use super::super::settings::Quote;
/// ## What it does
/// Checks for inline strings that use single quotes or double quotes,
/// depending on the value of the [`lint.flake8-quotes.inline-quotes`] option.
///
/// ## Why is this bad?
/// Consistency is good. Use either single or double quotes for inline
/// strings, but be consistent.
///
/// ## Example
/// ```python
/// foo = 'bar'
/// ```
///
/// Assuming `inline-quotes` is set to `double`, use instead:
/// ```python
/// foo = "bar"
/// ```
///
/// ## Options
/// - `lint.flake8-quotes.inline-quotes`
///
/// ## Formatter compatibility
/// We recommend against using this rule alongside the [formatter]. The
/// formatter enforces consistent quotes for inline strings, making the rule
/// redundant.
///
/// [formatter]: https://docs.astral.sh/ruff/formatter
#[violation]
pub struct BadQuotesInlineString {
preferred_quote: Quote,
}
impl Violation for BadQuotesInlineString {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let BadQuotesInlineString { preferred_quote } = self;
match preferred_quote {
Quote::Double => format!("Single quotes found but double quotes preferred"),
Quote::Single => format!("Double quotes found but single quotes preferred"),
}
}
fn fix_title(&self) -> Option<String> {
let BadQuotesInlineString { preferred_quote } = self;
match preferred_quote {
Quote::Double => Some("Replace single quotes with double quotes".to_string()),
Quote::Single => Some("Replace double quotes with single quotes".to_string()),
}
}
}
/// ## What it does
/// Checks for multiline strings that use single quotes or double quotes,
/// depending on the value of the [`lint.flake8-quotes.multiline-quotes`]
/// setting.
///
/// ## Why is this bad?
/// Consistency is good. Use either single or double quotes for multiline
/// strings, but be consistent.
///
/// ## Example
/// ```python
/// foo = '''
/// bar
/// '''
/// ```
///
/// Assuming `multiline-quotes` is set to `double`, use instead:
/// ```python
/// foo = """
/// bar
/// """
/// ```
///
/// ## Options
/// - `lint.flake8-quotes.multiline-quotes`
///
/// ## Formatter compatibility
/// We recommend against using this rule alongside the [formatter]. The
/// formatter enforces double quotes for multiline strings, making the rule
/// redundant.
///
/// [formatter]: https://docs.astral.sh/ruff/formatter
#[violation]
pub struct BadQuotesMultilineString {
preferred_quote: Quote,
}
impl AlwaysFixableViolation for BadQuotesMultilineString {
#[derive_message_formats]
fn message(&self) -> String {
let BadQuotesMultilineString { preferred_quote } = self;
match preferred_quote {
Quote::Double => format!("Single quote multiline found but double quotes preferred"),
Quote::Single => format!("Double quote multiline found but single quotes preferred"),
}
}
fn fix_title(&self) -> String {
let BadQuotesMultilineString { preferred_quote } = self;
match preferred_quote {
Quote::Double => "Replace single multiline quotes with double quotes".to_string(),
Quote::Single => "Replace double multiline quotes with single quotes".to_string(),
}
}
}
/// ## What it does
/// Checks for docstrings that use single quotes or double quotes, depending
/// on the value of the [`lint.flake8-quotes.docstring-quotes`] setting.
///
/// ## Why is this bad?
/// Consistency is good. Use either single or double quotes for docstring
/// strings, but be consistent.
///
/// ## Example
/// ```python
/// '''
/// bar
/// '''
/// ```
///
/// Assuming `docstring-quotes` is set to `double`, use instead:
/// ```python
/// """
/// bar
/// """
/// ```
///
/// ## Options
/// - `lint.flake8-quotes.docstring-quotes`
///
/// ## Formatter compatibility
/// We recommend against using this rule alongside the [formatter]. The
/// formatter enforces double quotes for docstrings, making the rule
/// redundant.
///
/// [formatter]: https://docs.astral.sh/ruff/formatter
#[violation]
pub struct BadQuotesDocstring {
preferred_quote: Quote,
}
impl Violation for BadQuotesDocstring {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let BadQuotesDocstring { preferred_quote } = self;
match preferred_quote {
Quote::Double => format!("Single quote docstring found but double quotes preferred"),
Quote::Single => format!("Double quote docstring found but single quotes preferred"),
}
}
fn fix_title(&self) -> Option<String> {
let BadQuotesDocstring { preferred_quote } = self;
match preferred_quote {
Quote::Double => Some("Replace single quotes docstring with double quotes".to_string()),
Quote::Single => Some("Replace double quotes docstring with single quotes".to_string()),
}
}
}
const fn good_multiline(quote: Quote) -> &'static str {
match quote {
Quote::Double => "\"\"\"",
Quote::Single => "'''",
}
}
const fn good_multiline_ending(quote: Quote) -> &'static str {
match quote {
Quote::Double => "\"'''",
Quote::Single => "'\"\"\"",
}
}
const fn good_docstring(quote: Quote) -> char {
match quote {
Quote::Double => '"',
Quote::Single => '\'',
}
}
#[derive(Debug)]
struct Trivia<'a> {
last_quote_char: char,
prefix: &'a str,
raw_text: &'a str,
is_multiline: bool,
}
impl Trivia<'_> {
fn has_empty_text(&self) -> bool {
self.raw_text == "\"\"" || self.raw_text == "''"
}
}
impl<'a> From<&'a str> for Trivia<'a> {
fn from(value: &'a str) -> Self {
// Remove any prefixes (e.g., remove `u` from `u"foo"`).
let last_quote_char = value.chars().last().unwrap();
let first_quote_char = value.find(last_quote_char).unwrap();
let prefix = &value[..first_quote_char];
let raw_text = &value[first_quote_char..];
// Determine if the string is multiline-based.
let is_multiline = if raw_text.len() >= 3 {
let mut chars = raw_text.chars();
let first = chars.next().unwrap();
let second = chars.next().unwrap();
let third = chars.next().unwrap();
first == second && second == third
} else {
false
};
Self {
last_quote_char,
prefix,
raw_text,
is_multiline,
}
}
}
/// Returns `true` if the [`TextRange`] is preceded by two consecutive quotes.
fn text_starts_at_consecutive_quote(locator: &Locator, range: TextRange, quote: Quote) -> bool {
let mut previous_two_chars = locator.up_to(range.start()).chars().rev();
previous_two_chars.next() == Some(good_docstring(quote))
&& previous_two_chars.next() == Some(good_docstring(quote))
}
/// Returns `true` if the [`TextRange`] ends at a quote character.
fn text_ends_at_quote(locator: &Locator, range: TextRange, quote: Quote) -> bool {
locator
.after(range.end())
.starts_with(good_docstring(quote))
}
/// Q002
fn docstring(checker: &mut Checker, range: TextRange) {
let quotes_settings = &checker.settings.flake8_quotes;
let locator = checker.locator();
let text = locator.slice(range);
let trivia: Trivia = text.into();
if trivia.has_empty_text()
&& text_ends_at_quote(locator, range, quotes_settings.docstring_quotes)
{
// Fixing this would result in a one-sided multi-line docstring, which would
// introduce a syntax error.
checker.diagnostics.push(Diagnostic::new(
BadQuotesDocstring {
preferred_quote: quotes_settings.docstring_quotes,
},
range,
));
return;
}
if trivia
.raw_text
.contains(good_docstring(quotes_settings.docstring_quotes))
{
return;
}
let mut diagnostic = Diagnostic::new(
BadQuotesDocstring {
preferred_quote: quotes_settings.docstring_quotes,
},
range,
);
let quote_count = if trivia.is_multiline { 3 } else { 1 };
let string_contents = &trivia.raw_text[quote_count..trivia.raw_text.len() - quote_count];
let quote = good_docstring(quotes_settings.docstring_quotes)
.to_string()
.repeat(quote_count);
let mut fixed_contents =
String::with_capacity(trivia.prefix.len() + string_contents.len() + quote.len() * 2);
fixed_contents.push_str(trivia.prefix);
fixed_contents.push_str("e);
fixed_contents.push_str(string_contents);
fixed_contents.push_str("e);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
fixed_contents,
range,
)));
checker.diagnostics.push(diagnostic);
}
/// Q000, Q001
fn strings(checker: &mut Checker, sequence: &[TextRange]) {
let quotes_settings = &checker.settings.flake8_quotes;
let locator = checker.locator();
let trivia = sequence
.iter()
.map(|range| {
let text = locator.slice(*range);
let trivia: Trivia = text.into();
trivia
})
.collect::<Vec<_>>();
// Return `true` if any of the strings are inline strings that contain the quote
// character in the body.
let relax_quote = trivia.iter().any(|trivia| {
if trivia.is_multiline {
return false;
}
if trivia.last_quote_char == quotes_settings.inline_quotes.as_char() {
return false;
}
let string_contents = &trivia.raw_text[1..trivia.raw_text.len() - 1];
string_contents.contains(quotes_settings.inline_quotes.as_char())
});
for (range, trivia) in sequence.iter().zip(trivia) {
if trivia.is_multiline {
// If multiline strings aren't enforced, ignore it.
if !checker.enabled(Rule::BadQuotesMultilineString) {
continue;
}
// If our string is or contains a known good string, ignore it.
if trivia
.raw_text
.contains(good_multiline(quotes_settings.multiline_quotes))
{
continue;
}
// If our string ends with a known good ending, then ignore it.
if trivia
.raw_text
.ends_with(good_multiline_ending(quotes_settings.multiline_quotes))
{
continue;
}
let mut diagnostic = Diagnostic::new(
BadQuotesMultilineString {
preferred_quote: quotes_settings.multiline_quotes,
},
*range,
);
let string_contents = &trivia.raw_text[3..trivia.raw_text.len() - 3];
let quote = good_multiline(quotes_settings.multiline_quotes);
let mut fixed_contents = String::with_capacity(
trivia.prefix.len() + string_contents.len() + quote.len() * 2,
);
fixed_contents.push_str(trivia.prefix);
fixed_contents.push_str(quote);
fixed_contents.push_str(string_contents);
fixed_contents.push_str(quote);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
fixed_contents,
*range,
)));
checker.diagnostics.push(diagnostic);
} else if trivia.last_quote_char != quotes_settings.inline_quotes.as_char()
// If we're not using the preferred type, only allow use to avoid escapes.
&& !relax_quote
{
// If inline strings aren't enforced, ignore it.
if !checker.enabled(Rule::BadQuotesInlineString) {
continue;
}
if trivia.has_empty_text()
&& text_ends_at_quote(locator, *range, quotes_settings.inline_quotes)
{
// Fixing this would introduce a syntax error. For example, changing the initial
// single quotes to double quotes would result in a syntax error:
// ```python
// ''"assert" ' SAM macro definitions '''
// ```
checker.diagnostics.push(Diagnostic::new(
BadQuotesInlineString {
preferred_quote: quotes_settings.inline_quotes,
},
*range,
));
continue;
}
if text_starts_at_consecutive_quote(locator, *range, quotes_settings.inline_quotes) {
// Fixing this would introduce a syntax error. For example, changing the double
// doubles to single quotes would result in a syntax error:
// ```python
// ''"assert" ' SAM macro definitions '''
// ```
checker.diagnostics.push(Diagnostic::new(
BadQuotesInlineString {
preferred_quote: quotes_settings.inline_quotes,
},
*range,
));
continue;
}
let mut diagnostic = Diagnostic::new(
BadQuotesInlineString {
preferred_quote: quotes_settings.inline_quotes,
},
*range,
);
let quote = quotes_settings.inline_quotes.as_char();
let string_contents = &trivia.raw_text[1..trivia.raw_text.len() - 1];
let mut fixed_contents =
String::with_capacity(trivia.prefix.len() + string_contents.len() + 2);
fixed_contents.push_str(trivia.prefix);
fixed_contents.push(quote);
fixed_contents.push_str(string_contents);
fixed_contents.push(quote);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
fixed_contents,
*range,
)));
checker.diagnostics.push(diagnostic);
}
}
}
/// Generate `flake8-quote` diagnostics from a token stream.
pub(crate) fn check_string_quotes(checker: &mut Checker, string_like: StringLike) {
// Ignore if the string is part of a forward reference. For example,
// `x: "Literal['foo', 'bar']"`.
if checker.semantic().in_string_type_definition() {
return;
}
// If the string is part of a f-string, ignore it.
if checker
.indexer()
.fstring_ranges()
.outermost(string_like.start())
.is_some_and(|outer| outer.start() < string_like.start() && string_like.end() < outer.end())
{
return;
}
let ranges: Vec<TextRange> = match string_like {
StringLike::String(node) => node.value.iter().map(Ranged::range).collect(),
StringLike::Bytes(node) => node.value.iter().map(Ranged::range).collect(),
StringLike::FString(node) => node.value.iter().map(Ranged::range).collect(),
};
if checker.semantic().in_docstring() {
if checker.enabled(Rule::BadQuotesDocstring) {
for range in ranges {
docstring(checker, range);
}
}
} else {
if checker.any_enabled(&[Rule::BadQuotesInlineString, Rule::BadQuotesMultilineString]) {
strings(checker, &ranges);
}
}
}