diff --git a/clippy_lints/src/strlen_on_c_strings.rs b/clippy_lints/src/strlen_on_c_strings.rs index be7431f11aa..dc28bb97400 100644 --- a/clippy_lints/src/strlen_on_c_strings.rs +++ b/clippy_lints/src/strlen_on_c_strings.rs @@ -1,13 +1,13 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::paths; -use clippy_utils::source::snippet_with_macro_callsite; -use clippy_utils::ty::{is_type_diagnostic_item, is_type_ref_to_diagnostic_item}; +use clippy_utils::match_libc_symbol; +use clippy_utils::source::snippet_with_context; +use clippy_utils::ty::is_type_diagnostic_item; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::sym; declare_clippy_lint! { /// ### What it does @@ -40,28 +40,23 @@ declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]); impl LateLintPass<'tcx> for StrlenOnCStrings { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if expr.span.from_expansion() { - return; - } - if_chain! { + if !expr.span.from_expansion(); if let hir::ExprKind::Call(func, [recv]) = expr.kind; - if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind; - - if (&paths::LIBC_STRLEN).iter().map(|x| Symbol::intern(x)).eq( - path.segments.iter().map(|seg| seg.ident.name)); - if let hir::ExprKind::MethodCall(path, _, args, _) = recv.kind; - if args.len() == 1; - if !args.iter().any(|e| e.span.from_expansion()); + if let hir::ExprKind::Path(path) = &func.kind; + if let Some(did) = cx.qpath_res(path, func.hir_id).opt_def_id(); + if match_libc_symbol(cx, did, "strlen"); + if let hir::ExprKind::MethodCall(path, _, [self_arg], _) = recv.kind; + if !recv.span.from_expansion(); if path.ident.name == sym::as_ptr; then { - let cstring = &args[0]; - let ty = cx.typeck_results().expr_ty(cstring); - let val_name = snippet_with_macro_callsite(cx, cstring.span, ".."); - let sugg = if is_type_diagnostic_item(cx, ty, sym::cstring_type){ - format!("{}.as_bytes().len()", val_name) - } else if is_type_ref_to_diagnostic_item(cx, ty, sym::CStr){ - format!("{}.to_bytes().len()", val_name) + let ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); + let mut app = Applicability::Unspecified; + let val_name = snippet_with_context(cx, self_arg.span, expr.span.ctxt(), "..", &mut app).0; + let method_name = if is_type_diagnostic_item(cx, ty, sym::cstring_type) { + "as_bytes" + } else if is_type_diagnostic_item(cx, ty, sym::CStr) { + "to_bytes" } else { return; }; @@ -72,7 +67,7 @@ impl LateLintPass<'tcx> for StrlenOnCStrings { expr.span, "using `libc::strlen` on a `CString` or `CStr` value", "try this (you might also need to get rid of `unsafe` block in some cases):", - sugg, + format!("{}.{}().len()", val_name, method_name), Applicability::Unspecified // Sometimes unnecessary `unsafe` block ); } diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 3fdea55aaa1..f011380c127 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1597,6 +1597,14 @@ pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) - syms.iter().map(|x| Symbol::intern(x)).eq(path.iter().copied()) } +/// Checks if the given `DefId` matches the `libc` item. +pub fn match_libc_symbol(cx: &LateContext<'_>, did: DefId, name: &str) -> bool { + let path = cx.get_def_path(did); + // libc is meant to be used as a flat list of names, but they're all actually defined in different + // modules based on the target platform. Ignore everything but crate name and the item name. + path.first().map_or(false, |s| s.as_str() == "libc") && path.last().map_or(false, |s| s.as_str() == name) +} + pub fn match_panic_call(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> { if let ExprKind::Call(func, [arg]) = expr.kind { expr_path_res(cx, func) diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index b04d1736426..3ffa548e470 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -86,7 +86,6 @@ pub const ITERTOOLS_NEXT_TUPLE: [&str; 3] = ["itertools", "Itertools", "next_tup pub const KW_MODULE: [&str; 3] = ["rustc_span", "symbol", "kw"]; #[cfg(feature = "internal-lints")] pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"]; -pub const LIBC_STRLEN: [&str; 2] = ["libc", "strlen"]; #[cfg(any(feature = "internal-lints", feature = "metadata-collector-lint"))] pub const LINT: [&str; 2] = ["rustc_lint_defs", "Lint"]; pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"]; diff --git a/tests/ui/strlen_on_c_strings.rs b/tests/ui/strlen_on_c_strings.rs index 21902fa8483..121ddf1b9b1 100644 --- a/tests/ui/strlen_on_c_strings.rs +++ b/tests/ui/strlen_on_c_strings.rs @@ -3,6 +3,7 @@ #![feature(rustc_private)] extern crate libc; +use libc::strlen; use std::ffi::{CStr, CString}; fn main() { @@ -13,4 +14,6 @@ fn main() { // CStr let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"); let len = unsafe { libc::strlen(cstr.as_ptr()) }; + + let len = unsafe { strlen(cstr.as_ptr()) }; } diff --git a/tests/ui/strlen_on_c_strings.stderr b/tests/ui/strlen_on_c_strings.stderr index e0ca511557c..5576d9d2676 100644 --- a/tests/ui/strlen_on_c_strings.stderr +++ b/tests/ui/strlen_on_c_strings.stderr @@ -1,5 +1,5 @@ error: using `libc::strlen` on a `CString` or `CStr` value - --> $DIR/strlen_on_c_strings.rs:11:24 + --> $DIR/strlen_on_c_strings.rs:12:24 | LL | let len = unsafe { libc::strlen(cstring.as_ptr()) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -11,7 +11,7 @@ LL | let len = unsafe { cstring.as_bytes().len() }; | ~~~~~~~~~~~~~~~~~~~~~~~~ error: using `libc::strlen` on a `CString` or `CStr` value - --> $DIR/strlen_on_c_strings.rs:15:24 + --> $DIR/strlen_on_c_strings.rs:16:24 | LL | let len = unsafe { libc::strlen(cstr.as_ptr()) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -21,5 +21,16 @@ help: try this (you might also need to get rid of `unsafe` block in some cases): LL | let len = unsafe { cstr.to_bytes().len() }; | ~~~~~~~~~~~~~~~~~~~~~ -error: aborting due to 2 previous errors +error: using `libc::strlen` on a `CString` or `CStr` value + --> $DIR/strlen_on_c_strings.rs:18:24 + | +LL | let len = unsafe { strlen(cstr.as_ptr()) }; + | ^^^^^^^^^^^^^^^^^^^^^ + | +help: try this (you might also need to get rid of `unsafe` block in some cases): + | +LL | let len = unsafe { cstr.to_bytes().len() }; + | ~~~~~~~~~~~~~~~~~~~~~ + +error: aborting due to 3 previous errors