]> git.lizzy.rs Git - rust.git/commitdiff
Fix `strlen_on_c_strings` when not used with a full path
authorJason Newcomb <jsnewcomb@pm.me>
Sat, 20 Nov 2021 01:02:49 +0000 (20:02 -0500)
committerJason Newcomb <jsnewcomb@pm.me>
Sat, 20 Nov 2021 01:02:49 +0000 (20:02 -0500)
clippy_lints/src/strlen_on_c_strings.rs
clippy_utils/src/lib.rs
clippy_utils/src/paths.rs
tests/ui/strlen_on_c_strings.rs
tests/ui/strlen_on_c_strings.stderr

index be7431f11aad04af75a906aeb92c6a931caf3af9..dc28bb974005d1445b437823f247767bbc4055c9 100644 (file)
@@ -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
 
 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 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
                     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
                 );
             }
index 3fdea55aaa1bf743d87b77cbf8b7f3a56cee8167..f011380c127a25c10939ed22c1cb07796248e5a4 100644 (file)
@@ -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)
index b04d17364264a032041b2208b7225c4bd4107f0f..3ffa548e4701f809a7f068454ca4796625376068 100644 (file)
@@ -86,7 +86,6 @@
 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"];
index 21902fa8483f3e9913fedd1572daa511fee13477..121ddf1b9b120efa021aa431e4198db62155eee5 100644 (file)
@@ -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()) };
 }
index e0ca511557c5b594981270097a7161909b6fb319..5576d9d2676679776ec815b89d7e80812d17d48b 100644 (file)
@@ -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