]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/size_of_in_element_count.rs
Rollup merge of #82917 - cuviper:iter-zip, r=m-ou-se
[rust.git] / clippy_lints / src / size_of_in_element_count.rs
1 //! Lint on use of `size_of` or `size_of_val` of T in an expression
2 //! expecting a count of T
3
4 use clippy_utils::diagnostics::span_lint_and_help;
5 use clippy_utils::{match_def_path, paths};
6 use if_chain::if_chain;
7 use rustc_hir::BinOpKind;
8 use rustc_hir::{Expr, ExprKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, Ty, TyS, TypeAndMut};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12
13 declare_clippy_lint! {
14     /// **What it does:** Detects expressions where
15     /// `size_of::<T>` or `size_of_val::<T>` is used as a
16     /// count of elements of type `T`
17     ///
18     /// **Why is this bad?** These functions expect a count
19     /// of `T` and not a number of bytes
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     /// ```rust,no_run
25     /// # use std::ptr::copy_nonoverlapping;
26     /// # use std::mem::size_of;
27     /// const SIZE: usize = 128;
28     /// let x = [2u8; SIZE];
29     /// let mut y = [2u8; SIZE];
30     /// unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::<u8>() * SIZE) };
31     /// ```
32     pub SIZE_OF_IN_ELEMENT_COUNT,
33     correctness,
34     "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected"
35 }
36
37 declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]);
38
39 fn get_size_of_ty(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> {
40     match expr.kind {
41         ExprKind::Call(count_func, _func_args) => {
42             if_chain! {
43                 if !inverted;
44                 if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
45                 if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id();
46                 if match_def_path(cx, def_id, &paths::MEM_SIZE_OF)
47                     || match_def_path(cx, def_id, &paths::MEM_SIZE_OF_VAL);
48                 then {
49                     cx.typeck_results().node_substs(count_func.hir_id).types().next()
50                 } else {
51                     None
52                 }
53             }
54         },
55         ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => {
56             get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted))
57         },
58         ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => {
59             get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, !inverted))
60         },
61         ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted),
62         _ => None,
63     }
64 }
65
66 fn get_pointee_ty_and_count_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> {
67     const FUNCTIONS: [&[&str]; 8] = [
68         &paths::COPY_NONOVERLAPPING,
69         &paths::COPY,
70         &paths::WRITE_BYTES,
71         &paths::PTR_SWAP_NONOVERLAPPING,
72         &paths::PTR_SLICE_FROM_RAW_PARTS,
73         &paths::PTR_SLICE_FROM_RAW_PARTS_MUT,
74         &paths::SLICE_FROM_RAW_PARTS,
75         &paths::SLICE_FROM_RAW_PARTS_MUT,
76     ];
77     const METHODS: [&str; 11] = [
78         "write_bytes",
79         "copy_to",
80         "copy_from",
81         "copy_to_nonoverlapping",
82         "copy_from_nonoverlapping",
83         "add",
84         "wrapping_add",
85         "sub",
86         "wrapping_sub",
87         "offset",
88         "wrapping_offset",
89     ];
90
91     if_chain! {
92         // Find calls to ptr::{copy, copy_nonoverlapping}
93         // and ptr::{swap_nonoverlapping, write_bytes},
94         if let ExprKind::Call(func, [.., count]) = expr.kind;
95         if let ExprKind::Path(ref func_qpath) = func.kind;
96         if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
97         if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path));
98
99         // Get the pointee type
100         if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next();
101         then {
102             return Some((pointee_ty, count));
103         }
104     };
105     if_chain! {
106         // Find calls to copy_{from,to}{,_nonoverlapping} and write_bytes methods
107         if let ExprKind::MethodCall(method_path, _, [ptr_self, .., count], _) = expr.kind;
108         let method_ident = method_path.ident.as_str();
109         if METHODS.iter().any(|m| *m == &*method_ident);
110
111         // Get the pointee type
112         if let ty::RawPtr(TypeAndMut { ty: pointee_ty, .. }) =
113             cx.typeck_results().expr_ty(ptr_self).kind();
114         then {
115             return Some((pointee_ty, count));
116         }
117     };
118     None
119 }
120
121 impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount {
122     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
123         const HELP_MSG: &str = "use a count of elements instead of a count of bytes\
124             , it already gets multiplied by the size of the type";
125
126         const LINT_MSG: &str = "found a count of bytes \
127              instead of a count of elements of `T`";
128
129         if_chain! {
130             // Find calls to functions with an element count parameter and get
131             // the pointee type and count parameter expression
132             if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr);
133
134             // Find a size_of call in the count parameter expression and
135             // check that it's the same type
136             if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false);
137             if TyS::same_type(pointee_ty, ty_used_for_size_of);
138             then {
139                 span_lint_and_help(
140                     cx,
141                     SIZE_OF_IN_ELEMENT_COUNT,
142                     count_expr.span,
143                     LINT_MSG,
144                     None,
145                     HELP_MSG
146                 );
147             }
148         };
149     }
150 }