Skip to content

Commit 598acba

Browse files
authored
Merge pull request #2497 from waywardmonkeys/single-char-pattern
Fix single_char_pattern for \n, \t, etc.
2 parents f071d19 + 769a1d9 commit 598acba

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

clippy_lints/src/methods.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1763,7 +1763,11 @@ fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hi
17631763
}) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg)
17641764
{
17651765
if r.len() == 1 {
1766-
let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1766+
let c = r.chars().next().unwrap();
1767+
let snip = snippet(cx, expr.span, "..");
1768+
let hint = snip.replace(
1769+
&format!("\"{}\"", c.escape_default()),
1770+
&format!("'{}'", c.escape_default()));
17671771
span_lint_and_then(
17681772
cx,
17691773
SINGLE_CHAR_PATTERN,

tests/ui/single_char_pattern.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ fn main() {
3535
x.rmatch_indices("x");
3636
x.trim_left_matches("x");
3737
x.trim_right_matches("x");
38+
// Make sure we escape characters correctly.
39+
x.split("\n");
3840

3941
let h = HashSet::<String>::new();
4042
h.contains("X"); // should not warn

tests/ui/single_char_pattern.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,5 +102,11 @@ error: single-character string constant used as pattern
102102
37 | x.trim_right_matches("x");
103103
| ---------------------^^^- help: try using a char instead: `x.trim_right_matches('x')`
104104

105-
error: aborting due to 17 previous errors
105+
error: single-character string constant used as pattern
106+
--> $DIR/single_char_pattern.rs:39:13
107+
|
108+
39 | x.split("/n");
109+
| --------^^^^- help: try using a char instead: `x.split('/n')`
110+
111+
error: aborting due to 18 previous errors
106112

0 commit comments

Comments
 (0)