Skip to content

Commit

Permalink
Add string_from_utf8_as_bytes linter
Browse files Browse the repository at this point in the history
Signed-off-by: Patrick José Pereira <patrickelectric@gmail.com>
  • Loading branch information
patrickelectric committed Oct 8, 2020
1 parent 9408c68 commit 4177a96
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1824,6 +1824,7 @@ Released 2018-09-13
[`string_add`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add
[`string_add_assign`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add_assign
[`string_extend_chars`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_extend_chars
[`string_from_utf8_as_bytes`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_from_utf8_as_bytes
[`string_lit_as_bytes`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_lit_as_bytes
[`string_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_to_string
[`struct_excessive_bools`]: https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools
Expand Down
3 changes: 3 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
&stable_sort_primitive::STABLE_SORT_PRIMITIVE,
&strings::STRING_ADD,
&strings::STRING_ADD_ASSIGN,
&strings::STRING_FROM_UTF8_AS_BYTES,
&strings::STRING_LIT_AS_BYTES,
&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL,
&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL,
Expand Down Expand Up @@ -1475,6 +1476,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS),
LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION),
LintId::of(&stable_sort_primitive::STABLE_SORT_PRIMITIVE),
LintId::of(&strings::STRING_FROM_UTF8_AS_BYTES),
LintId::of(&strings::STRING_LIT_AS_BYTES),
LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
Expand Down Expand Up @@ -1769,6 +1771,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
LintId::of(&regex::INVALID_REGEX),
LintId::of(&self_assignment::SELF_ASSIGNMENT),
LintId::of(&serde_api::SERDE_API_MISUSE),
LintId::of(&strings::STRING_FROM_UTF8_AS_BYTES),
LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
LintId::of(&swap::ALMOST_SWAPPED),
Expand Down
59 changes: 56 additions & 3 deletions clippy_lints/src/strings.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, LangItem, QPath};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::SymbolStr;

use if_chain::if_chain;

use crate::utils::SpanlessEq;
use crate::utils::{get_parent_expr, is_allowed, is_type_diagnostic_item, span_lint, span_lint_and_sugg};
use crate::utils::{
get_parent_expr, is_allowed, is_type_diagnostic_item, match_function_call, method_calls, paths, span_lint,
span_lint_and_sugg,
};

declare_clippy_lint! {
/// **What it does:** Checks for string appends of the form `x = x + y` (without
Expand Down Expand Up @@ -153,16 +157,65 @@ fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
}
}

declare_clippy_lint! {
/// **What it does:** Check if the string is transformed to byte array and casted back to string.
///
/// **Why is this bad?** It's unnecessary, the string can be used directly.
///
/// **Known problems:** None
///
/// **Example:**
/// ```rust
/// let string = "Hello World!";
/// let string2 = std::str::from_utf8(&string.as_bytes()[6..11]).unwrap();
/// ```
/// could be written as
/// ```rust
/// let string = "Hello World!";
/// let string2 = &string[6..1];
/// ```
pub STRING_FROM_UTF8_AS_BYTES,
correctness,
"make sure that access from slice should be done from bytes and not from string directly"
}

// Max length a b"foo" string can take
const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;

declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES]);
declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);

impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
use crate::utils::{snippet, snippet_with_applicability};
use rustc_ast::LitKind;

if_chain! {
// Find std::str::converts::from_utf8
if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);

// Find string::as_bytes
if let ExprKind::AddrOf(BorrowKind::Ref, _, ref args) = args[0].kind;
if let ExprKind::Index(ref left, ref right) = args.kind;
let (method_names, _, _) = method_calls(left, 1);
let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
if method_names.len() == 1;
if method_names[0] == "as_bytes";

// Check for slicer
if let ExprKind::Struct(ref path, _, _) = right.kind;
if let QPath::LangItem(LangItem::Range, _) = path;

then {
span_lint(
cx,
STRING_FROM_UTF8_AS_BYTES,
e.span,
"calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
);
}
}

if_chain! {
if let ExprKind::MethodCall(path, _, args, _) = &e.kind;
if path.ident.name == sym!(as_bytes);
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/utils/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ pub const STRING: [&str; 3] = ["alloc", "string", "String"];
pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
pub const STR_ENDS_WITH: [&str; 4] = ["core", "str", "<impl str>", "ends_with"];
pub const STR_FROM_UTF8: [&str; 4] = ["core", "str", "converts", "from_utf8"];
pub const STR_LEN: [&str; 4] = ["core", "str", "<impl str>", "len"];
pub const STR_STARTS_WITH: [&str; 4] = ["core", "str", "<impl str>", "starts_with"];
pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"];
Expand Down
7 changes: 7 additions & 0 deletions src/lintlist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2166,6 +2166,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
deprecation: None,
module: "methods",
},
Lint {
name: "string_from_utf8_as_bytes",
group: "correctness",
desc: "make sure that access from slice should be done from bytes and not from string directly",
deprecation: None,
module: "strings",
},
Lint {
name: "string_lit_as_bytes",
group: "style",
Expand Down
7 changes: 7 additions & 0 deletions tests/ui/string_from_utf8_as_bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#![warn(clippy::string_from_utf8_as_bytes)]
use std::str;

fn main() {
let string = "Hello World!";
let string2 = str::from_utf8(&string.as_bytes()[6..11]).unwrap();
}
10 changes: 10 additions & 0 deletions tests/ui/string_from_utf8_as_bytes.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
error: calling a slice of `as_bytes()` with `from_utf8` should be not necessary
--> $DIR/string_from_utf8_as_bytes.rs:6:19
|
LL | let string2 = str::from_utf8(&string.as_bytes()[6..11]).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D clippy::string-from-utf8-as-bytes` implied by `-D warnings`

error: aborting due to previous error

0 comments on commit 4177a96

Please sign in to comment.