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};
13 declare_clippy_lint! {
15 /// Checks for uses of `std::mem::size_of::<T>() * 8` when
16 /// `T::BITS` is available.
18 /// ### Why is this bad?
19 /// Can be written as the shorter `T::BITS`.
23 /// std::mem::size_of::<usize>() * 8;
29 #[clippy::version = "1.60.0"]
32 "manual implementation of `size_of::<T>() * 8` can be simplified with `T::BITS`"
36 pub struct ManualBits {
37 msrv: Option<RustcVersion>,
42 pub fn new(msrv: Option<RustcVersion>) -> Self {
47 impl_lint_pass!(ManualBits => [MANUAL_BITS]);
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) {
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;
68 "usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
70 format!("{}::BITS", snippet_opt(cx, real_ty.span).unwrap()),
71 Applicability::MachineApplicable,
77 extract_msrv_attr!(LateContext);
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)),
92 fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
94 if let ExprKind::Call(count_func, _func_args) = expr.kind;
95 if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
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);
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);
105 cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (real_ty, resolved_ty))