Skip to content

Commit 30cbdc7

Browse files
committed
Fix lint_single_char_pattern on raw string literal
1 parent d23e6b3 commit 30cbdc7

File tree

4 files changed

+31
-4
lines changed

4 files changed

+31
-4
lines changed

clippy_lints/src/methods/mod.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2329,13 +2329,20 @@ fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &
23292329
fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
23302330
if_chain! {
23312331
if let hir::ExprKind::Lit(lit) = &arg.node;
2332-
if let ast::LitKind::Str(r, _) = lit.node;
2332+
if let ast::LitKind::Str(r, style) = lit.node;
23332333
if r.as_str().len() == 1;
23342334
then {
23352335
let mut applicability = Applicability::MachineApplicable;
23362336
let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
2337-
let c = &snip[1..snip.len() - 1];
2338-
let hint = format!("'{}'", if c == "'" { "\\'" } else { c });
2337+
let ch = if let ast::StrStyle::Raw(nhash) = style {
2338+
let nhash = nhash as usize;
2339+
// for raw string: r##"a"##
2340+
&snip[(nhash + 2)..(snip.len() - 1 - nhash)]
2341+
} else {
2342+
// for regular string: "a"
2343+
&snip[1..(snip.len() - 1)]
2344+
};
2345+
let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
23392346
span_lint_and_sugg(
23402347
cx,
23412348
SINGLE_CHAR_PATTERN,

tests/ui/single_char_pattern.fixed

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,8 @@ fn main() {
5353
// Issue #3204
5454
const S: &str = "#";
5555
x.find(S);
56+
57+
// Raw string
58+
x.split('a');
59+
x.split('a');
5660
}

tests/ui/single_char_pattern.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,8 @@ fn main() {
5353
// Issue #3204
5454
const S: &str = "#";
5555
x.find(S);
56+
57+
// Raw string
58+
x.split(r"a");
59+
x.split(r#"a"#);
5660
}

tests/ui/single_char_pattern.stderr

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,5 +132,17 @@ error: single-character string constant used as pattern
132132
LL | x.starts_with("/x03"); // issue #2996
133133
| ^^^^^^ help: try using a char instead: `'/x03'`
134134

135-
error: aborting due to 22 previous errors
135+
error: single-character string constant used as pattern
136+
--> $DIR/single_char_pattern.rs:58:13
137+
|
138+
LL | x.split(r"a");
139+
| ^^^^ help: try using a char instead: `'a'`
140+
141+
error: single-character string constant used as pattern
142+
--> $DIR/single_char_pattern.rs:59:13
143+
|
144+
LL | x.split(r#"a"#);
145+
| ^^^^^^ help: try using a char instead: `'a'`
146+
147+
error: aborting due to 24 previous errors
136148

0 commit comments

Comments
 (0)