Skip to content

Commit 1f8f982

Browse files
committed
Auto merge of rust-lang#13504 - samueltardieu:needless-raw-strings, r=Alexendoo
Check for needless raw strings in `format_args!()` template as well changelog: [`needless_raw_strings`, `needless_raw_string_hashes`]: check `format_args!()` template as well Fix rust-lang#13503
2 parents d9c8d97 + 36c31db commit 1f8f982

11 files changed

+239
-101
lines changed

clippy_dev/src/new_lint.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -207,13 +207,13 @@ pub(crate) fn get_stabilization_version() -> String {
207207

208208
fn get_test_file_contents(lint_name: &str, msrv: bool) -> String {
209209
let mut test = formatdoc!(
210-
r#"
210+
r"
211211
#![warn(clippy::{lint_name})]
212212
213213
fn main() {{
214214
// test code goes here
215215
}}
216-
"#
216+
"
217217
);
218218

219219
if msrv {
@@ -272,31 +272,31 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
272272

273273
result.push_str(&if enable_msrv {
274274
formatdoc!(
275-
r#"
275+
r"
276276
use clippy_config::msrvs::{{self, Msrv}};
277277
use clippy_config::Conf;
278278
{pass_import}
279279
use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
280280
use rustc_session::impl_lint_pass;
281281
282-
"#
282+
"
283283
)
284284
} else {
285285
formatdoc!(
286-
r#"
286+
r"
287287
{pass_import}
288288
use rustc_lint::{{{context_import}, {pass_type}}};
289289
use rustc_session::declare_lint_pass;
290290
291-
"#
291+
"
292292
)
293293
});
294294

295295
let _: fmt::Result = writeln!(result, "{}", get_lint_declaration(&name_upper, category));
296296

297297
result.push_str(&if enable_msrv {
298298
formatdoc!(
299-
r#"
299+
r"
300300
pub struct {name_camel} {{
301301
msrv: Msrv,
302302
}}
@@ -315,15 +315,15 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
315315
316316
// TODO: Add MSRV level to `clippy_config/src/msrvs.rs` if needed.
317317
// TODO: Update msrv config comment in `clippy_config/src/conf.rs`
318-
"#
318+
"
319319
)
320320
} else {
321321
formatdoc!(
322-
r#"
322+
r"
323323
declare_lint_pass!({name_camel} => [{name_upper}]);
324324
325325
impl {pass_type}{pass_lifetimes} for {name_camel} {{}}
326-
"#
326+
"
327327
)
328328
});
329329

@@ -416,7 +416,7 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R
416416
} else {
417417
let _: fmt::Result = writedoc!(
418418
lint_file_contents,
419-
r#"
419+
r"
420420
use rustc_lint::{{{context_import}, LintContext}};
421421
422422
use super::{name_upper};
@@ -425,7 +425,7 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R
425425
pub(super) fn check(cx: &{context_import}{pass_lifetimes}) {{
426426
todo!();
427427
}}
428-
"#
428+
"
429429
);
430430
}
431431

clippy_lints/src/raw_strings.rs

+110-82
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clippy_config::Conf;
22
use clippy_utils::diagnostics::span_lint_and_then;
3-
use clippy_utils::source::SpanRangeExt;
3+
use clippy_utils::source::{SpanRangeExt, snippet_opt};
44
use rustc_ast::ast::{Expr, ExprKind};
55
use rustc_ast::token::LitKind;
66
use rustc_errors::Applicability;
@@ -71,6 +71,23 @@ impl RawStrings {
7171

7272
impl EarlyLintPass for RawStrings {
7373
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
74+
if let ExprKind::FormatArgs(format_args) = &expr.kind
75+
&& !in_external_macro(cx.sess(), format_args.span)
76+
&& format_args.span.check_source_text(cx, |src| src.starts_with('r'))
77+
&& let Some(str) = snippet_opt(cx.sess(), format_args.span)
78+
&& let count_hash = str.bytes().skip(1).take_while(|b| *b == b'#').count()
79+
&& let Some(str) = str.get(count_hash + 2..str.len() - count_hash - 1)
80+
{
81+
self.check_raw_string(
82+
cx,
83+
str,
84+
format_args.span,
85+
"r",
86+
u8::try_from(count_hash).unwrap(),
87+
"string",
88+
);
89+
}
90+
7491
if let ExprKind::Lit(lit) = expr.kind
7592
&& let (prefix, max) = match lit.kind {
7693
LitKind::StrRaw(max) => ("r", max),
@@ -81,94 +98,105 @@ impl EarlyLintPass for RawStrings {
8198
&& !in_external_macro(cx.sess(), expr.span)
8299
&& expr.span.check_source_text(cx, |src| src.starts_with(prefix))
83100
{
84-
let str = lit.symbol.as_str();
85-
let descr = lit.kind.descr();
86-
87-
if !str.contains(['\\', '"']) {
88-
span_lint_and_then(
89-
cx,
90-
NEEDLESS_RAW_STRINGS,
91-
expr.span,
92-
"unnecessary raw string literal",
93-
|diag| {
94-
let (start, end) = hash_spans(expr.span, prefix.len(), 0, max);
95-
96-
// BytePos: skip over the `b` in `br`, we checked the prefix appears in the source text
97-
let r_pos = expr.span.lo() + BytePos::from_usize(prefix.len() - 1);
98-
let start = start.with_lo(r_pos);
99-
100-
let mut remove = vec![(start, String::new())];
101-
// avoid debug ICE from empty suggestions
102-
if !end.is_empty() {
103-
remove.push((end, String::new()));
104-
}
101+
self.check_raw_string(cx, lit.symbol.as_str(), expr.span, prefix, max, lit.kind.descr());
102+
}
103+
}
104+
}
105105

106-
diag.multipart_suggestion_verbose(
107-
format!("use a plain {descr} literal instead"),
108-
remove,
109-
Applicability::MachineApplicable,
110-
);
111-
},
112-
);
113-
if !matches!(cx.get_lint_level(NEEDLESS_RAW_STRINGS), rustc_lint::Allow) {
114-
return;
115-
}
106+
impl RawStrings {
107+
fn check_raw_string(
108+
&mut self,
109+
cx: &EarlyContext<'_>,
110+
str: &str,
111+
lit_span: Span,
112+
prefix: &str,
113+
max: u8,
114+
descr: &str,
115+
) {
116+
if !str.contains(['\\', '"']) {
117+
span_lint_and_then(
118+
cx,
119+
NEEDLESS_RAW_STRINGS,
120+
lit_span,
121+
"unnecessary raw string literal",
122+
|diag| {
123+
let (start, end) = hash_spans(lit_span, prefix.len(), 0, max);
124+
125+
// BytePos: skip over the `b` in `br`, we checked the prefix appears in the source text
126+
let r_pos = lit_span.lo() + BytePos::from_usize(prefix.len() - 1);
127+
let start = start.with_lo(r_pos);
128+
129+
let mut remove = vec![(start, String::new())];
130+
// avoid debug ICE from empty suggestions
131+
if !end.is_empty() {
132+
remove.push((end, String::new()));
133+
}
134+
135+
diag.multipart_suggestion_verbose(
136+
format!("use a plain {descr} literal instead"),
137+
remove,
138+
Applicability::MachineApplicable,
139+
);
140+
},
141+
);
142+
if !matches!(cx.get_lint_level(NEEDLESS_RAW_STRINGS), rustc_lint::Allow) {
143+
return;
116144
}
145+
}
117146

118-
let mut req = {
119-
let mut following_quote = false;
120-
let mut req = 0;
121-
// `once` so a raw string ending in hashes is still checked
122-
let num = str.as_bytes().iter().chain(once(&0)).try_fold(0u8, |acc, &b| {
123-
match b {
124-
b'"' if !following_quote => (following_quote, req) = (true, 1),
125-
b'#' => req += u8::from(following_quote),
126-
_ => {
127-
if following_quote {
128-
following_quote = false;
129-
130-
if req == max {
131-
return ControlFlow::Break(req);
132-
}
133-
134-
return ControlFlow::Continue(acc.max(req));
147+
let mut req = {
148+
let mut following_quote = false;
149+
let mut req = 0;
150+
// `once` so a raw string ending in hashes is still checked
151+
let num = str.as_bytes().iter().chain(once(&0)).try_fold(0u8, |acc, &b| {
152+
match b {
153+
b'"' if !following_quote => (following_quote, req) = (true, 1),
154+
b'#' => req += u8::from(following_quote),
155+
_ => {
156+
if following_quote {
157+
following_quote = false;
158+
159+
if req == max {
160+
return ControlFlow::Break(req);
135161
}
136-
},
137-
}
138162

139-
ControlFlow::Continue(acc)
140-
});
141-
142-
match num {
143-
ControlFlow::Continue(num) | ControlFlow::Break(num) => num,
144-
}
145-
};
146-
if self.allow_one_hash_in_raw_strings {
147-
req = req.max(1);
148-
}
149-
if req < max {
150-
span_lint_and_then(
151-
cx,
152-
NEEDLESS_RAW_STRING_HASHES,
153-
expr.span,
154-
"unnecessary hashes around raw string literal",
155-
|diag| {
156-
let (start, end) = hash_spans(expr.span, prefix.len(), req, max);
157-
158-
let message = match max - req {
159-
_ if req == 0 => format!("remove all the hashes around the {descr} literal"),
160-
1 => format!("remove one hash from both sides of the {descr} literal"),
161-
n => format!("remove {n} hashes from both sides of the {descr} literal"),
162-
};
163-
164-
diag.multipart_suggestion(
165-
message,
166-
vec![(start, String::new()), (end, String::new())],
167-
Applicability::MachineApplicable,
168-
);
163+
return ControlFlow::Continue(acc.max(req));
164+
}
169165
},
170-
);
166+
}
167+
168+
ControlFlow::Continue(acc)
169+
});
170+
171+
match num {
172+
ControlFlow::Continue(num) | ControlFlow::Break(num) => num,
171173
}
174+
};
175+
if self.allow_one_hash_in_raw_strings {
176+
req = req.max(1);
177+
}
178+
if req < max {
179+
span_lint_and_then(
180+
cx,
181+
NEEDLESS_RAW_STRING_HASHES,
182+
lit_span,
183+
"unnecessary hashes around raw string literal",
184+
|diag| {
185+
let (start, end) = hash_spans(lit_span, prefix.len(), req, max);
186+
187+
let message = match max - req {
188+
_ if req == 0 => format!("remove all the hashes around the {descr} literal"),
189+
1 => format!("remove one hash from both sides of the {descr} literal"),
190+
n => format!("remove {n} hashes from both sides of the {descr} literal"),
191+
};
192+
193+
diag.multipart_suggestion(
194+
message,
195+
vec![(start, String::new()), (end, String::new())],
196+
Applicability::MachineApplicable,
197+
);
198+
},
199+
);
172200
}
173201
}
174202
}

clippy_lints/src/rc_clone_in_vec_init.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ impl LateLintPass<'_> for RcCloneInVecInit {
6565

6666
fn loop_init_suggestion(elem: &str, len: &str, indent: &str) -> String {
6767
format!(
68-
r#"{{
68+
r"{{
6969
{indent} let mut v = Vec::with_capacity({len});
7070
{indent} (0..{len}).for_each(|_| v.push({elem}));
7171
{indent} v
72-
{indent}}}"#
72+
{indent}}}"
7373
)
7474
}
7575

lintcheck/src/json.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ fn print_lint_warnings(lint: &LintWarnings, truncate_after: usize) {
133133
println!();
134134

135135
print!(
136-
r##"{}, {}, {}"##,
136+
r"{}, {}, {}",
137137
count_string(name, "added", lint.added.len()),
138138
count_string(name, "removed", lint.removed.len()),
139139
count_string(name, "changed", lint.changed.len()),

tests/config-metadata.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ fn book() {
2020

2121
let configs = metadata().map(|conf| conf.to_markdown_paragraph()).join("\n");
2222
let expected = format!(
23-
r#"<!--
23+
r"<!--
2424
This file is generated by `cargo bless --test config-metadata`.
2525
Please use that command to update the file and do not edit it by hand.
2626
-->
@@ -33,7 +33,7 @@ and lints affected.
3333
---
3434
3535
{}
36-
"#,
36+
",
3737
configs.trim(),
3838
);
3939

tests/ui/needless_raw_string.fixed

+9
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,12 @@ fn main() {
2222
b"no hashes";
2323
c"no hashes";
2424
}
25+
26+
fn issue_13503() {
27+
println!("SELECT * FROM posts");
28+
println!("SELECT * FROM posts");
29+
println!(r##"SELECT * FROM "posts""##);
30+
31+
// Test arguments as well
32+
println!("{}", "foobar".len());
33+
}

tests/ui/needless_raw_string.rs

+9
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,12 @@ fn main() {
2222
br"no hashes";
2323
cr"no hashes";
2424
}
25+
26+
fn issue_13503() {
27+
println!(r"SELECT * FROM posts");
28+
println!(r#"SELECT * FROM posts"#);
29+
println!(r##"SELECT * FROM "posts""##);
30+
31+
// Test arguments as well
32+
println!("{}", r"foobar".len());
33+
}

0 commit comments

Comments
 (0)