1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{get_parent_expr, 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;
27 /// usize::BITS as usize;
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, 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;
63 let mut app = Applicability::MachineApplicable;
64 let ty_snip = snippet_with_applicability(cx, real_ty.span, "..", &mut app);
65 let sugg = create_sugg(cx, expr, format!("{ty_snip}::BITS"));
71 "usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
80 extract_msrv_attr!(LateContext);
83 fn get_one_size_of_ty<'tcx>(
84 cx: &LateContext<'tcx>,
85 expr1: &'tcx Expr<'_>,
86 expr2: &'tcx Expr<'_>,
87 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>, &'tcx Expr<'tcx>)> {
88 match (get_size_of_ty(cx, expr1), get_size_of_ty(cx, expr2)) {
89 (Some((real_ty, resolved_ty)), None) => Some((real_ty, resolved_ty, expr2)),
90 (None, Some((real_ty, resolved_ty))) => Some((real_ty, resolved_ty, expr1)),
95 fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
97 if let ExprKind::Call(count_func, _func_args) = expr.kind;
98 if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
100 if let QPath::Resolved(_, count_func_path) = count_func_qpath;
101 if let Some(segment_zero) = count_func_path.segments.get(0);
102 if let Some(args) = segment_zero.args;
103 if let Some(GenericArg::Type(real_ty)) = args.args.get(0);
105 if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id();
106 if cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id);
108 cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (*real_ty, resolved_ty))
115 fn create_sugg(cx: &LateContext<'_>, expr: &Expr<'_>, base_sugg: String) -> String {
116 if let Some(parent_expr) = get_parent_expr(cx, expr) {
117 if is_ty_conversion(parent_expr) {
121 // These expressions have precedence over casts, the suggestion therefore
122 // needs to be wrapped into parentheses
123 match parent_expr.kind {
124 ExprKind::Unary(..) | ExprKind::AddrOf(..) | ExprKind::MethodCall(..) => {
125 return format!("({base_sugg} as usize)");
131 format!("{base_sugg} as usize")
134 fn is_ty_conversion(expr: &Expr<'_>) -> bool {
135 if let ExprKind::Cast(..) = expr.kind {
137 } else if let ExprKind::MethodCall(path, _, [], _) = expr.kind
138 && path.ident.name == rustc_span::sym::try_into
140 // This is only called for `usize` which implements `TryInto`. Therefore,
141 // we don't have to check here if `self` implements the `TryInto` trait.