Skip to content

Commit 7537128

Browse files
committed
Add suggestion to write_literal and print_literal
Don't lint on a mixture of raw and regular strings Fix spans in format strings
1 parent 85f645a commit 7537128

File tree

4 files changed

+296
-31
lines changed

4 files changed

+296
-31
lines changed

clippy_lints/src/write.rs

+48-14
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
use std::borrow::Cow;
2-
use std::ops::Range;
2+
use std::iter;
3+
use std::ops::{Deref, Range};
34

45
use crate::utils::{snippet_opt, snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5-
use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, LitKind, MacCall, Path, StrLit, StrStyle};
6-
use rustc_ast::token;
6+
use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
7+
use rustc_ast::token::{self, LitKind};
78
use rustc_ast::tokenstream::TokenStream;
89
use rustc_errors::Applicability;
910
use rustc_lexer::unescape::{self, EscapeError};
@@ -437,7 +438,7 @@ impl Write {
437438
fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str: &StrLit) -> Option<SimpleFormatArgs> {
438439
use rustc_parse_format::{ParseMode, Parser, Piece};
439440

440-
let str_sym = str.symbol.as_str();
441+
let str_sym = str.symbol_unescaped.as_str();
441442
let style = match str.style {
442443
StrStyle::Cooked => None,
443444
StrStyle::Raw(n) => Some(n as usize),
@@ -513,21 +514,17 @@ impl Write {
513514
if !parser.eat(&token::Comma) {
514515
return (Some(fmtstr), expr);
515516
}
517+
518+
let comma_span = parser.prev_token.span;
516519
let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
517520
expr
518521
} else {
519522
return (Some(fmtstr), None);
520523
};
521-
let (fmt_spans, span) = match &token_expr.kind {
522-
ExprKind::Lit(lit) if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..)) => {
523-
(unnamed_args.next().unwrap_or(&[]), token_expr.span)
524-
},
524+
let (fmt_spans, lit) = match &token_expr.kind {
525+
ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
525526
ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
526-
(ExprKind::Path(_, p), ExprKind::Lit(lit))
527-
if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..)) =>
528-
{
529-
(args.get_named(p), rhs.span)
530-
},
527+
(ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
531528
_ => continue,
532529
},
533530
_ => {
@@ -536,8 +533,45 @@ impl Write {
536533
},
537534
};
538535

536+
let replacement: String = match lit.token.kind {
537+
LitKind::Integer | LitKind::Float | LitKind::Err => continue,
538+
LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
539+
lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
540+
},
541+
LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
542+
lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
543+
},
544+
LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
545+
LitKind::Byte | LitKind::Char => match lit.token.symbol.as_str().deref() {
546+
"\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
547+
"\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
548+
"\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
549+
"\\'" => "'",
550+
"{" => "{{",
551+
"}" => "}}",
552+
x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with("\\") => continue,
553+
x => x,
554+
}
555+
.into(),
556+
LitKind::Bool => lit.token.symbol.as_str().deref().into(),
557+
};
558+
539559
if !fmt_spans.is_empty() {
540-
span_lint(cx, lint, span, "literal with an empty format string");
560+
span_lint_and_then(
561+
cx,
562+
lint,
563+
token_expr.span,
564+
"literal with an empty format string",
565+
|diag| {
566+
diag.multipart_suggestion(
567+
"try this",
568+
iter::once((comma_span.to(token_expr.span), String::new()))
569+
.chain(fmt_spans.iter().cloned().zip(iter::repeat(replacement)))
570+
.collect(),
571+
Applicability::MachineApplicable,
572+
);
573+
},
574+
);
541575
}
542576
}
543577
}

tests/ui/print_literal.stderr

+62-8
Original file line numberDiff line numberDiff line change
@@ -5,66 +5,120 @@ LL | print!("Hello {}", "world");
55
| ^^^^^^^
66
|
77
= note: `-D clippy::print-literal` implied by `-D warnings`
8+
help: try this
9+
|
10+
LL | print!("Hello world");
11+
| ^^^^^--
812

913
error: literal with an empty format string
1014
--> $DIR/print_literal.rs:26:36
1115
|
1216
LL | println!("Hello {} {}", world, "world");
1317
| ^^^^^^^
18+
|
19+
help: try this
20+
|
21+
LL | println!("Hello {} world", world);
22+
| ^^^^^ --
1423

1524
error: literal with an empty format string
1625
--> $DIR/print_literal.rs:27:26
1726
|
1827
LL | println!("Hello {}", "world");
1928
| ^^^^^^^
29+
|
30+
help: try this
31+
|
32+
LL | println!("Hello world");
33+
| ^^^^^--
2034

2135
error: literal with an empty format string
2236
--> $DIR/print_literal.rs:32:25
2337
|
2438
LL | println!("{0} {1}", "hello", "world");
2539
| ^^^^^^^
40+
|
41+
help: try this
42+
|
43+
LL | println!("hello {1}", "world");
44+
| ^^^^^ --
2645

2746
error: literal with an empty format string
2847
--> $DIR/print_literal.rs:32:34
2948
|
3049
LL | println!("{0} {1}", "hello", "world");
3150
| ^^^^^^^
51+
|
52+
help: try this
53+
|
54+
LL | println!("{0} world", "hello");
55+
| ^^^^^ --
3256

3357
error: literal with an empty format string
3458
--> $DIR/print_literal.rs:33:25
3559
|
3660
LL | println!("{1} {0}", "hello", "world");
3761
| ^^^^^^^
62+
|
63+
help: try this
64+
|
65+
LL | println!("{1} hello", "world");
66+
| ^^^^^--
3867

3968
error: literal with an empty format string
4069
--> $DIR/print_literal.rs:33:34
4170
|
4271
LL | println!("{1} {0}", "hello", "world");
4372
| ^^^^^^^
73+
|
74+
help: try this
75+
|
76+
LL | println!("world {0}", "hello");
77+
| ^^^^^ --
4478

4579
error: literal with an empty format string
46-
--> $DIR/print_literal.rs:36:35
80+
--> $DIR/print_literal.rs:36:29
4781
|
4882
LL | println!("{foo} {bar}", foo = "hello", bar = "world");
49-
| ^^^^^^^
83+
| ^^^^^^^^^^^^^
84+
|
85+
help: try this
86+
|
87+
LL | println!("hello {bar}", bar = "world");
88+
| ^^^^^ --
5089

5190
error: literal with an empty format string
52-
--> $DIR/print_literal.rs:36:50
91+
--> $DIR/print_literal.rs:36:44
5392
|
5493
LL | println!("{foo} {bar}", foo = "hello", bar = "world");
55-
| ^^^^^^^
94+
| ^^^^^^^^^^^^^
95+
|
96+
help: try this
97+
|
98+
LL | println!("{foo} world", foo = "hello");
99+
| ^^^^^ --
56100

57101
error: literal with an empty format string
58-
--> $DIR/print_literal.rs:37:35
102+
--> $DIR/print_literal.rs:37:29
59103
|
60104
LL | println!("{bar} {foo}", foo = "hello", bar = "world");
61-
| ^^^^^^^
105+
| ^^^^^^^^^^^^^
106+
|
107+
help: try this
108+
|
109+
LL | println!("{bar} hello", bar = "world");
110+
| ^^^^^--
62111

63112
error: literal with an empty format string
64-
--> $DIR/print_literal.rs:37:50
113+
--> $DIR/print_literal.rs:37:44
65114
|
66115
LL | println!("{bar} {foo}", foo = "hello", bar = "world");
67-
| ^^^^^^^
116+
| ^^^^^^^^^^^^^
117+
|
118+
help: try this
119+
|
120+
LL | println!("world {foo}", foo = "hello");
121+
| ^^^^^ --
68122

69123
error: aborting due to 11 previous errors
70124

tests/ui/write_literal.rs

+20
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,24 @@ fn main() {
4040
// named args shouldn't change anything either
4141
writeln!(&mut v, "{foo} {bar}", foo = "hello", bar = "world");
4242
writeln!(&mut v, "{bar} {foo}", foo = "hello", bar = "world");
43+
44+
// Replacement test
45+
writeln!(&mut v, "{}", "{hello}");
46+
writeln!(&mut v, r"{}", r"{hello}");
47+
writeln!(&mut v, "{}", '\'');
48+
writeln!(&mut v, "{}", '"');
49+
writeln!(&mut v, r"{}", '"'); // don't lint
50+
writeln!(&mut v, r"{}", '\'');
51+
writeln!(
52+
&mut v,
53+
"some {}",
54+
"hello \
55+
world!"
56+
);
57+
writeln!(
58+
&mut v,
59+
"some {}\
60+
{} \\ {}",
61+
"1", "2", "3",
62+
);
4363
}

0 commit comments

Comments
 (0)