]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_bits.rs
Use `&'hir Ty` everywhere.
[rust.git] / clippy_lints / src / manual_bits.rs
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};
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 as usize;
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, 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             then {
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"));
66
67                 span_lint_and_sugg(
68                     cx,
69                     MANUAL_BITS,
70                     expr.span,
71                     "usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
72                     "consider using",
73                     sugg,
74                     app,
75                 );
76             }
77         }
78     }
79
80     extract_msrv_attr!(LateContext);
81 }
82
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)),
91         _ => None,
92     }
93 }
94
95 fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
96     if_chain! {
97         if let ExprKind::Call(count_func, _func_args) = expr.kind;
98         if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
99
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);
104
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);
107         then {
108             cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (*real_ty, resolved_ty))
109         } else {
110             None
111         }
112     }
113 }
114
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) {
118             return base_sugg;
119         }
120
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)");
126             },
127             _ => {},
128         }
129     }
130
131     format!("{base_sugg} as usize")
132 }
133
134 fn is_ty_conversion(expr: &Expr<'_>) -> bool {
135     if let ExprKind::Cast(..) = expr.kind {
136         true
137     } else if let ExprKind::MethodCall(path, [_], _) = expr.kind
138         && path.ident.name == rustc_span::sym::try_into
139     {
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.
142         true
143     } else {
144         false
145     }
146 }