Skip to content

Commit 6fa49eb

Browse files
committed
Merge pull request #562 from fhartwig/str-lit-as-bytes
Add lint for "string literal".as_bytes()
2 parents a0496f0 + ea26ae3 commit 6fa49eb

File tree

4 files changed

+61
-1
lines changed

4 files changed

+61
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ A collection of lints to catch common mistakes and improve your Rust code.
66
[Jump to usage instructions](#usage)
77

88
##Lints
9-
There are 93 lints included in this crate:
9+
There are 94 lints included in this crate:
1010

1111
name | default | meaning
1212
---------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -83,6 +83,7 @@ name
8383
[str_to_string](https://github.com/Manishearth/rust-clippy/wiki#str_to_string) | warn | using `to_string()` on a str, which should be `to_owned()`
8484
[string_add](https://github.com/Manishearth/rust-clippy/wiki#string_add) | allow | using `x + ..` where x is a `String`; suggests using `push_str()` instead
8585
[string_add_assign](https://github.com/Manishearth/rust-clippy/wiki#string_add_assign) | allow | using `x = x + ..` where x is a `String`; suggests using `push_str()` instead
86+
[string_lit_as_bytes](https://github.com/Manishearth/rust-clippy/wiki#string_lit_as_bytes) | warn | calling `as_bytes` on a string literal; suggests using a byte string literal instead
8687
[string_to_string](https://github.com/Manishearth/rust-clippy/wiki#string_to_string) | warn | calling `String.to_string()` which is a no-op
8788
[temporary_assignment](https://github.com/Manishearth/rust-clippy/wiki#temporary_assignment) | warn | assignments to temporaries
8889
[toplevel_ref_arg](https://github.com/Manishearth/rust-clippy/wiki#toplevel_ref_arg) | warn | An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take references with `&`.

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
135135
reg.register_late_lint_pass(box misc::UsedUnderscoreBinding);
136136
reg.register_late_lint_pass(box array_indexing::ArrayIndexing);
137137
reg.register_late_lint_pass(box panic::PanicPass);
138+
reg.register_late_lint_pass(box strings::StringLitAsBytes);
138139

139140

140141
reg.register_lint_group("clippy_pedantic", vec![
@@ -225,6 +226,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
225226
ranges::RANGE_ZIP_WITH_LEN,
226227
returns::LET_AND_RETURN,
227228
returns::NEEDLESS_RETURN,
229+
strings::STRING_LIT_AS_BYTES,
228230
temporary_assignment::TEMPORARY_ASSIGNMENT,
229231
transmute::USELESS_TRANSMUTE,
230232
types::BOX_VEC,

src/strings.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,22 @@ declare_lint! {
4848
"using `x + ..` where x is a `String`; suggests using `push_str()` instead"
4949
}
5050

51+
/// **What it does:** This lint matches the `as_bytes` method called on string
52+
/// literals that contain only ascii characters. It is `Warn` by default.
53+
///
54+
/// **Why is this bad?** Byte string literals (e.g. `b"foo"`) can be used instead. They are shorter but less discoverable than `as_bytes()`.
55+
///
56+
/// **Example:**
57+
///
58+
/// ```
59+
/// let bs = "a byte string".as_bytes();
60+
/// ```
61+
declare_lint! {
62+
pub STRING_LIT_AS_BYTES,
63+
Warn,
64+
"calling `as_bytes` on a string literal; suggests using a byte string literal instead"
65+
}
66+
5167
#[derive(Copy, Clone)]
5268
pub struct StringAdd;
5369

@@ -104,3 +120,36 @@ fn is_add(cx: &LateContext, src: &Expr, target: &Expr) -> bool {
104120
_ => false,
105121
}
106122
}
123+
124+
#[derive(Copy, Clone)]
125+
pub struct StringLitAsBytes;
126+
127+
impl LintPass for StringLitAsBytes {
128+
fn get_lints(&self) -> LintArray {
129+
lint_array!(STRING_LIT_AS_BYTES)
130+
}
131+
}
132+
133+
impl LateLintPass for StringLitAsBytes {
134+
fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
135+
use std::ascii::AsciiExt;
136+
use syntax::ast::Lit_::LitStr;
137+
use utils::{snippet, in_macro};
138+
139+
if let ExprMethodCall(ref name, _, ref args) = e.node {
140+
if name.node.as_str() == "as_bytes" {
141+
if let ExprLit(ref lit) = args[0].node {
142+
if let LitStr(ref lit_content, _) = lit.node {
143+
if lit_content.chars().all(|c| c.is_ascii()) && !in_macro(cx, e.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);
149+
}
150+
}
151+
}
152+
}
153+
}
154+
}
155+
}

tests/compile-fail/strings.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ fn both() {
4444
assert_eq!(&x, &z);
4545
}
4646

47+
#[allow(dead_code, unused_variables)]
48+
#[deny(string_lit_as_bytes)]
49+
fn str_lit_as_bytes() {
50+
let bs = "hello there".as_bytes(); //~ERROR calling `as_bytes()`
51+
// no warning, because this cannot be written as a byte string literal:
52+
let ubs = "☃".as_bytes();
53+
}
54+
4755
fn main() {
4856
add_only();
4957
add_assign_only();

0 commit comments

Comments
 (0)