Skip to content

Commit

Permalink
Auto merge of #8067 - frobiac:8060-backslash_escaped_in_single_char_p…
Browse files Browse the repository at this point in the history
…attern, r=giraffate

Escape backslash in single_char_pattern.rs

Escape backslash in single_char_pattern.

Previously, the proposed clippy fix for a single backslash in raw strings ```r"\"``` or ```r#"\"#``` was also only an unescaped, *single* ```'\'```:
```shell
warning: single-character string constant used as pattern
2 |     let s = r#"abc\xyz/"#.find(r"\");
  |                                ^^^^ help: try using a `char` instead: `'\'`
  |
  = note: `#[warn(clippy::single_char_pattern)]` on by default
```

This PR corrects this to a properly escaped *double* backslash ```'\\'```.
I haven't come up with any other problematic cases, a single quote was already handled.

Closes: #8060

changelog:  Escape backslash in ``[`single_char_pattern`]``
  • Loading branch information
bors committed Dec 3, 2021
2 parents d5d830a + 5cc451b commit fddef24
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
8 changes: 7 additions & 1 deletion clippy_lints/src/methods/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,13 @@ pub(super) fn get_hint_if_single_char_arg(
// for regular string: "a"
&snip[1..(snip.len() - 1)]
};
let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });

let hint = format!("'{}'", match ch {
"'" => "\\'" ,
r"\" => "\\\\",
_ => ch,
});

Some(hint)
} else {
None
Expand Down
3 changes: 3 additions & 0 deletions tests/ui/single_char_pattern.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,7 @@ fn main() {
x.split('a');
x.split('\'');
x.split('#');
// Must escape backslash in raw strings when converting to char #8060
x.split('\\');
x.split('\\');
}
3 changes: 3 additions & 0 deletions tests/ui/single_char_pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,7 @@ fn main() {
x.split(r###"a"###);
x.split(r###"'"###);
x.split(r###"#"###);
// Must escape backslash in raw strings when converting to char #8060
x.split(r#"\"#);
x.split(r"\");
}
14 changes: 13 additions & 1 deletion tests/ui/single_char_pattern.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,17 @@ error: single-character string constant used as pattern
LL | x.split(r###"#"###);
| ^^^^^^^^^^ help: try using a `char` instead: `'#'`

error: aborting due to 32 previous errors
error: single-character string constant used as pattern
--> $DIR/single_char_pattern.rs:60:13
|
LL | x.split(r#"/"#);
| ^^^^^^ help: try using a `char` instead: `'/'`

error: single-character string constant used as pattern
--> $DIR/single_char_pattern.rs:61:13
|
LL | x.split(r"/");
| ^^^^ help: try using a `char` instead: `'/'`

error: aborting due to 34 previous errors

0 comments on commit fddef24

Please sign in to comment.