Auto merge of #8067 - frobiac:8060-backslash_escaped_in_single_char_pattern, 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`]``
This commit is contained in:
bors 2021-12-03 00:23:59 +00:00
commit fddef249a2
4 changed files with 26 additions and 2 deletions

View file

@ -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

View file

@ -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('\\');
}

View file

@ -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"\");
}

View file

@ -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