1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_context;
3 use clippy_utils::{expr_or_init, in_constant, std_or_core};
4 use rustc_errors::Applicability;
5 use rustc_hir::{BinOpKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::sym;
10
11 declare_clippy_lint! {
12 /// ### What it does
13 /// When `a` is `&[T]`, detect `a.len() * size_of::<T>()` and suggest `size_of_val(a)`
14 /// instead.
15 ///
16 /// ### Why is this better?
17 /// * Shorter to write
18 /// * Removes the need for the human and the compiler to worry about overflow in the
19 /// multiplication
20 /// * Potentially faster at runtime as rust emits special no-wrapping flags when it
21 /// calculates the byte length
22 /// * Less turbofishing
23 ///
24 /// ### Example
25 /// ```rust
26 /// # let data : &[i32] = &[1, 2, 3];
27 /// let newlen = data.len() * std::mem::size_of::<i32>();
28 /// ```
29 /// Use instead:
30 /// ```rust
31 /// # let data : &[i32] = &[1, 2, 3];
32 /// let newlen = std::mem::size_of_val(data);
33 /// ```
34 #[clippy::version = "1.70.0"]
35 pub MANUAL_SLICE_SIZE_CALCULATION,
36 complexity,
37 "manual slice size calculation"
38 }
39 declare_lint_pass!(ManualSliceSizeCalculation => [MANUAL_SLICE_SIZE_CALCULATION]);
40
41 impl<'tcx> LateLintPass<'tcx> for ManualSliceSizeCalculation {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>)42 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
43 // Does not apply inside const because size_of_val is not cost in stable.
44 if !in_constant(cx, expr.hir_id)
45 && let ExprKind::Binary(ref op, left, right) = expr.kind
46 && BinOpKind::Mul == op.node
47 && !expr.span.from_expansion()
48 && let Some(receiver) = simplify(cx, left, right)
49 {
50 let ctxt = expr.span.ctxt();
51 let mut app = Applicability::MachineApplicable;
52 let val_name = snippet_with_context(cx, receiver.span, ctxt, "slice", &mut app).0;
53 let Some(sugg) = std_or_core(cx) else { return };
54
55 span_lint_and_sugg(
56 cx,
57 MANUAL_SLICE_SIZE_CALCULATION,
58 expr.span,
59 "manual slice size calculation",
60 "try",
61 format!("{sugg}::mem::size_of_val({val_name})"),
62 app,
63 );
64 }
65 }
66 }
67
simplify<'tcx>( cx: &LateContext<'tcx>, expr1: &'tcx Expr<'tcx>, expr2: &'tcx Expr<'tcx>, ) -> Option<&'tcx Expr<'tcx>>68 fn simplify<'tcx>(
69 cx: &LateContext<'tcx>,
70 expr1: &'tcx Expr<'tcx>,
71 expr2: &'tcx Expr<'tcx>,
72 ) -> Option<&'tcx Expr<'tcx>> {
73 let expr1 = expr_or_init(cx, expr1);
74 let expr2 = expr_or_init(cx, expr2);
75
76 simplify_half(cx, expr1, expr2).or_else(|| simplify_half(cx, expr2, expr1))
77 }
78
simplify_half<'tcx>( cx: &LateContext<'tcx>, expr1: &'tcx Expr<'tcx>, expr2: &'tcx Expr<'tcx>, ) -> Option<&'tcx Expr<'tcx>>79 fn simplify_half<'tcx>(
80 cx: &LateContext<'tcx>,
81 expr1: &'tcx Expr<'tcx>,
82 expr2: &'tcx Expr<'tcx>,
83 ) -> Option<&'tcx Expr<'tcx>> {
84 if !expr1.span.from_expansion()
85 // expr1 is `[T1].len()`?
86 && let ExprKind::MethodCall(method_path, receiver, _, _) = expr1.kind
87 && method_path.ident.name == sym::len
88 && let receiver_ty = cx.typeck_results().expr_ty(receiver)
89 && let ty::Slice(ty1) = receiver_ty.peel_refs().kind()
90 // expr2 is `size_of::<T2>()`?
91 && let ExprKind::Call(func, _) = expr2.kind
92 && let ExprKind::Path(ref func_qpath) = func.kind
93 && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
94 && cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id)
95 && let Some(ty2) = cx.typeck_results().node_substs(func.hir_id).types().next()
96 // T1 == T2?
97 && *ty1 == ty2
98 {
99 Some(receiver)
100 } else {
101 None
102 }
103 }
104