1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::{match_def_path, meets_msrv, msrvs, paths};
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};
12 declare_clippy_lint! {
14 /// Checks for uses of `std::mem::size_of::<T>() * 8` when
15 /// `T::BITS` is available.
17 /// ### Why is this bad?
18 /// Can be written as the shorter `T::BITS`.
22 /// std::mem::size_of::<usize>() * 8;
28 #[clippy::version = "1.60.0"]
31 "manual implementation of `size_of::<T>() * 8` can be simplified with `T::BITS`"
35 pub struct ManualBits {
36 msrv: Option<RustcVersion>,
41 pub fn new(msrv: Option<RustcVersion>) -> Self {
46 impl_lint_pass!(ManualBits => [MANUAL_BITS]);
48 impl<'tcx> LateLintPass<'tcx> for ManualBits {
49 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50 if !meets_msrv(self.msrv.as_ref(), &msrvs::MANUAL_BITS) {
55 if let ExprKind::Binary(bin_op, left_expr, right_expr) = expr.kind;
56 if let BinOpKind::Mul = &bin_op.node;
57 if let Some((real_ty, resolved_ty, other_expr)) = get_one_size_of_ty(cx, left_expr, right_expr);
58 if matches!(resolved_ty.kind(), ty::Int(_) | ty::Uint(_));
59 if let ExprKind::Lit(lit) = &other_expr.kind;
60 if let LitKind::Int(8, _) = lit.node;
67 "usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
69 format!("{}::BITS", snippet_opt(cx, real_ty.span).unwrap()),
70 Applicability::MachineApplicable,
76 extract_msrv_attr!(LateContext);
79 fn get_one_size_of_ty<'tcx>(
80 cx: &LateContext<'tcx>,
81 expr1: &'tcx Expr<'_>,
82 expr2: &'tcx Expr<'_>,
83 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>, &'tcx Expr<'tcx>)> {
84 match (get_size_of_ty(cx, expr1), get_size_of_ty(cx, expr2)) {
85 (Some((real_ty, resolved_ty)), None) => Some((real_ty, resolved_ty, expr2)),
86 (None, Some((real_ty, resolved_ty))) => Some((real_ty, resolved_ty, expr1)),
91 fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
93 if let ExprKind::Call(count_func, _func_args) = expr.kind;
94 if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
96 if let QPath::Resolved(_, count_func_path) = count_func_qpath;
97 if let Some(segment_zero) = count_func_path.segments.get(0);
98 if let Some(args) = segment_zero.args;
99 if let Some(GenericArg::Type(real_ty)) = args.args.get(0);
101 if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id();
102 if match_def_path(cx, def_id, &paths::MEM_SIZE_OF);
104 cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (real_ty, resolved_ty))