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