Skip to content

Commit 251c3ee

Browse files
committed
Use span_suggestion in STRING_LIT_AS_BYTES
1 parent 6d4e1bd commit 251c3ee

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/strings.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_front::hir::*;
88
use syntax::codemap::Spanned;
99
use utils::STRING_PATH;
1010
use utils::SpanlessEq;
11-
use utils::{match_type, span_lint, walk_ptrs_ty, get_parent_expr};
11+
use utils::{match_type, span_lint, span_lint_and_then, walk_ptrs_ty, get_parent_expr};
1212

1313
/// **What it does:** This lint matches code of the form `x = x + y` (without `let`!).
1414
///
@@ -141,11 +141,18 @@ impl LateLintPass for StringLitAsBytes {
141141
if let ExprLit(ref lit) = args[0].node {
142142
if let LitKind::Str(ref lit_content, _) = lit.node {
143143
if lit_content.chars().all(|c| c.is_ascii()) && !in_macro(cx, args[0].span) {
144-
let msg = format!("calling `as_bytes()` on a string literal. \
145-
Consider using a byte string literal instead: \
146-
`b{}`",
147-
snippet(cx, args[0].span, r#""foo""#));
148-
span_lint(cx, STRING_LIT_AS_BYTES, e.span, &msg);
144+
span_lint_and_then(cx,
145+
STRING_LIT_AS_BYTES,
146+
e.span,
147+
"calling `as_bytes()` on a string literal",
148+
|db| {
149+
let sugg = format!("b{}",
150+
snippet(cx, args[0].span, r#""foo""#));
151+
db.span_suggestion(e.span,
152+
"consider using a byte string literal instead",
153+
sugg);
154+
});
155+
149156
}
150157
}
151158
}

tests/compile-fail/strings.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,15 @@ fn both() {
4747
#[allow(dead_code, unused_variables)]
4848
#[deny(string_lit_as_bytes)]
4949
fn str_lit_as_bytes() {
50-
let bs = "hello there".as_bytes(); //~ERROR calling `as_bytes()`
50+
let bs = "hello there".as_bytes();
51+
//~^ERROR calling `as_bytes()`
52+
//~|HELP byte string literal
53+
//~|SUGGESTION b"hello there"
54+
5155
// no warning, because this cannot be written as a byte string literal:
5256
let ubs = "☃".as_bytes();
57+
58+
let strify = stringify!(foobar).as_bytes();
5359
}
5460

5561
fn main() {

0 commit comments

Comments
 (0)