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