]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_bits.rs
turn `append_place_to_string` from recursion into iteration
[rust.git] / src / tools / clippy / clippy_lints / src / manual_bits.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::{meets_msrv, msrvs};
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOpKind, Expr, ExprKind, GenericArg, QPath};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::{self, Ty};
9 use rustc_semver::RustcVersion;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::sym;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for uses of `std::mem::size_of::<T>() * 8` when
16     /// `T::BITS` is available.
17     ///
18     /// ### Why is this bad?
19     /// Can be written as the shorter `T::BITS`.
20     ///
21     /// ### Example
22     /// ```rust
23     /// std::mem::size_of::<usize>() * 8;
24     /// ```
25     /// Use instead:
26     /// ```rust
27     /// usize::BITS;
28     /// ```
29     #[clippy::version = "1.60.0"]
30     pub MANUAL_BITS,
31     style,
32     "manual implementation of `size_of::<T>() * 8` can be simplified with `T::BITS`"
33 }
34
35 #[derive(Clone)]
36 pub struct ManualBits {
37     msrv: Option<RustcVersion>,
38 }
39
40 impl ManualBits {
41     #[must_use]
42     pub fn new(msrv: Option<RustcVersion>) -> Self {
43         Self { msrv }
44     }
45 }
46
47 impl_lint_pass!(ManualBits => [MANUAL_BITS]);
48
49 impl<'tcx> LateLintPass<'tcx> for ManualBits {
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51         if !meets_msrv(self.msrv.as_ref(), &msrvs::MANUAL_BITS) {
52             return;
53         }
54
55         if_chain! {
56             if let ExprKind::Binary(bin_op, left_expr, right_expr) = expr.kind;
57             if let BinOpKind::Mul = &bin_op.node;
58             if let Some((real_ty, resolved_ty, other_expr)) = get_one_size_of_ty(cx, left_expr, right_expr);
59             if matches!(resolved_ty.kind(), ty::Int(_) | ty::Uint(_));
60             if let ExprKind::Lit(lit) = &other_expr.kind;
61             if let LitKind::Int(8, _) = lit.node;
62
63             then {
64                 span_lint_and_sugg(
65                     cx,
66                     MANUAL_BITS,
67                     expr.span,
68                     "usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
69                     "consider using",
70                     format!("{}::BITS", snippet_opt(cx, real_ty.span).unwrap()),
71                     Applicability::MachineApplicable,
72                 );
73             }
74         }
75     }
76
77     extract_msrv_attr!(LateContext);
78 }
79
80 fn get_one_size_of_ty<'tcx>(
81     cx: &LateContext<'tcx>,
82     expr1: &'tcx Expr<'_>,
83     expr2: &'tcx Expr<'_>,
84 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>, &'tcx Expr<'tcx>)> {
85     match (get_size_of_ty(cx, expr1), get_size_of_ty(cx, expr2)) {
86         (Some((real_ty, resolved_ty)), None) => Some((real_ty, resolved_ty, expr2)),
87         (None, Some((real_ty, resolved_ty))) => Some((real_ty, resolved_ty, expr1)),
88         _ => None,
89     }
90 }
91
92 fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
93     if_chain! {
94         if let ExprKind::Call(count_func, _func_args) = expr.kind;
95         if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
96
97         if let QPath::Resolved(_, count_func_path) = count_func_qpath;
98         if let Some(segment_zero) = count_func_path.segments.get(0);
99         if let Some(args) = segment_zero.args;
100         if let Some(GenericArg::Type(real_ty)) = args.args.get(0);
101
102         if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id();
103         if cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id);
104         then {
105             cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (real_ty, resolved_ty))
106         } else {
107             None
108         }
109     }
110 }