|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use clippy_utils::ty::peel_mid_ty_refs; |
| 3 | +use rustc_hir::{Expr, ExprKind}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 6 | +use rustc_span::sym; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// |
| 11 | + /// Checks for calls to `std::mem::size_of_val()` where the argument is |
| 12 | + /// a reference to a reference. |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// |
| 16 | + /// The result of calling `size_of_val()` with a reference to a reference |
| 17 | + /// as the argument will be the size of any generic reference-type, not |
| 18 | + /// the size of the value behind the reference. |
| 19 | + /// |
| 20 | + /// ### Example |
| 21 | + /// ```rust |
| 22 | + /// struct Foo { |
| 23 | + /// buffer: [u8], |
| 24 | + /// } |
| 25 | + /// |
| 26 | + /// impl Foo { |
| 27 | + /// fn size(&self) -> usize { |
| 28 | + /// // Note that `&self` as an argument is a `&&Foo`: Bacause `self` |
| 29 | + /// // is already a reference, `&self` is a double-reference, |
| 30 | + /// // and the return value of `size_of_val()` therefor is the |
| 31 | + /// // size of any generic reference-type. |
| 32 | + /// std::mem::size_of_val(&self) |
| 33 | + /// } |
| 34 | + /// } |
| 35 | + /// ``` |
| 36 | + /// Use instead: |
| 37 | + /// ```rust |
| 38 | + /// struct Foo { |
| 39 | + /// buffer: [u8], |
| 40 | + /// } |
| 41 | + /// |
| 42 | + /// impl Foo { |
| 43 | + /// fn size(&self) -> usize { |
| 44 | + /// // Correct |
| 45 | + /// std::mem::size_of_val(self) |
| 46 | + /// } |
| 47 | + /// } |
| 48 | + /// ``` |
| 49 | + #[clippy::version = "1.67.0"] |
| 50 | + pub SIZE_OF_REF, |
| 51 | + correctness, |
| 52 | + "Argument to `std::mem::size_of_val()` is a double-reference, which is almost certainly unintended" |
| 53 | +} |
| 54 | +declare_lint_pass!(SizeOfRef => [SIZE_OF_REF]); |
| 55 | + |
| 56 | +impl LateLintPass<'_> for SizeOfRef { |
| 57 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { |
| 58 | + if let ExprKind::Call(path, [arg]) = expr.kind |
| 59 | + && let ExprKind::Path(ref qpath) = path.kind |
| 60 | + && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() |
| 61 | + && cx.tcx.is_diagnostic_item(sym::mem_size_of_val, def_id) |
| 62 | + && let arg_ty = cx.typeck_results().expr_ty(arg) |
| 63 | + && peel_mid_ty_refs(arg_ty).1 > 1 |
| 64 | + { |
| 65 | + span_lint_and_help( |
| 66 | + cx, |
| 67 | + SIZE_OF_REF, |
| 68 | + expr.span, |
| 69 | + "argument to `std::mem::size_of_val()` is a reference to a reference", |
| 70 | + None, |
| 71 | + "dereference the argument to `std::mem::size_of_val()` to get the size of the value instead of the generic size of any reference-type", |
| 72 | + ); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments