]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/strlen_on_c_strings.rs
Auto merge of #7243 - mgacek8:issue7145_strlen_on_c_strings, r=giraffate
[rust.git] / clippy_lints / src / strlen_on_c_strings.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::in_macro;
3 use clippy_utils::paths;
4 use clippy_utils::source::snippet_with_macro_callsite;
5 use clippy_utils::ty::{is_type_diagnostic_item, is_type_ref_to_diagnostic_item};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::symbol::{sym, Symbol};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for usage of `libc::strlen` on a `CString` or `CStr` value,
15     /// and suggest calling `as_bytes().len()` or `to_bytes().len()` respectively instead.
16     ///
17     /// **Why is this bad?** This avoids calling an unsafe `libc` function.
18     /// Currently, it also avoids calculating the length.
19     ///
20     /// **Known problems:** None.
21     ///
22     /// **Example:**
23     ///
24     /// ```rust, ignore
25     /// use std::ffi::CString;
26     /// let cstring = CString::new("foo").expect("CString::new failed");
27     /// let len = unsafe { libc::strlen(cstring.as_ptr()) };
28     /// ```
29     /// Use instead:
30     /// ```rust, no_run
31     /// use std::ffi::CString;
32     /// let cstring = CString::new("foo").expect("CString::new failed");
33     /// let len = cstring.as_bytes().len();
34     /// ```
35     pub STRLEN_ON_C_STRINGS,
36     complexity,
37     "using `libc::strlen` on a `CString` or `CStr` value, while `as_bytes().len()` or `to_bytes().len()` respectively can be used instead"
38 }
39
40 declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]);
41
42 impl LateLintPass<'tcx> for StrlenOnCStrings {
43     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
44         if in_macro(expr.span) {
45             return;
46         }
47
48         if_chain! {
49             if let hir::ExprKind::Call(func, [recv]) = expr.kind;
50             if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind;
51
52             if (&paths::LIBC_STRLEN).iter().map(|x| Symbol::intern(x)).eq(
53                 path.segments.iter().map(|seg| seg.ident.name));
54             if let hir::ExprKind::MethodCall(path, _, args, _) = recv.kind;
55             if args.len() == 1;
56             if !args.iter().any(|e| e.span.from_expansion());
57             if path.ident.name == sym::as_ptr;
58             then {
59                 let cstring = &args[0];
60                 let ty = cx.typeck_results().expr_ty(cstring);
61                 let val_name = snippet_with_macro_callsite(cx, cstring.span, "..");
62                 let sugg = if is_type_diagnostic_item(cx, ty, sym::cstring_type){
63                     format!("{}.as_bytes().len()", val_name)
64                 } else if is_type_ref_to_diagnostic_item(cx, ty, sym::CStr){
65                     format!("{}.to_bytes().len()", val_name)
66                 } else {
67                     return;
68                 };
69
70                 span_lint_and_sugg(
71                     cx,
72                     STRLEN_ON_C_STRINGS,
73                     expr.span,
74                     "using `libc::strlen` on a `CString` or `CStr` value",
75                     "try this (you might also need to get rid of `unsafe` block in some cases):",
76                     sugg,
77                     Applicability::Unspecified // Sometimes unnecessary `unsafe` block
78                 );
79             }
80         }
81     }
82 }