|
| 1 | +use rustc_ast::{BorrowKind, UnOp}; |
| 2 | +use rustc_hir::{Expr, ExprKind, TyKind}; |
| 3 | +use rustc_session::{declare_lint, declare_lint_pass}; |
| 4 | + |
| 5 | +use crate::lints::UnnecessaryRefs; |
| 6 | +use crate::{LateContext, LateLintPass, LintContext}; |
| 7 | + |
| 8 | +declare_lint! { |
| 9 | + /// The `unnecessary_refs` lint checks for unnecessary references. |
| 10 | + /// |
| 11 | + /// ### Example |
| 12 | + /// |
| 13 | + /// ```rust |
| 14 | + /// fn via_ref(x: *const (i32, i32)) -> *const i32 { |
| 15 | + /// unsafe { &(*x).0 as *const i32 } |
| 16 | + /// } |
| 17 | + /// |
| 18 | + /// fn main() { |
| 19 | + /// let x = 0; |
| 20 | + /// let _r = via_ref(&x); |
| 21 | + /// } |
| 22 | + /// ``` |
| 23 | + /// |
| 24 | + /// {{produces}} |
| 25 | + /// |
| 26 | + /// ### Explanation |
| 27 | + /// |
| 28 | + /// Creating unnecessary references is almost always a mistake. |
| 29 | + pub UNNECESSARY_REFS, |
| 30 | + Warn, |
| 31 | + "creating unecessary reference is discouraged" |
| 32 | +} |
| 33 | + |
| 34 | +declare_lint_pass!(UnecessaryRefs => [UNNECESSARY_REFS]); |
| 35 | + |
| 36 | +impl<'tcx> LateLintPass<'tcx> for UnecessaryRefs { |
| 37 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) { |
| 38 | + if let ExprKind::Cast(exp, ty) = expr.kind |
| 39 | + && let ExprKind::AddrOf(bk, _, exp) = exp.kind |
| 40 | + && matches!(bk, BorrowKind::Ref) |
| 41 | + && let ExprKind::Field(exp, field) = exp.kind |
| 42 | + && let ExprKind::Unary(uo, exp) = exp.kind |
| 43 | + && matches!(uo, UnOp::Deref) |
| 44 | + && let TyKind::Ptr(_) = ty.kind |
| 45 | + && let ExprKind::Path(qpath) = exp.kind |
| 46 | + { |
| 47 | + cx.emit_span_lint( |
| 48 | + UNNECESSARY_REFS, |
| 49 | + expr.span, |
| 50 | + UnnecessaryRefs { |
| 51 | + span: expr.span, |
| 52 | + replace: format!( |
| 53 | + "&raw const (*{}).{}", |
| 54 | + rustc_hir_pretty::qpath_to_string(&cx.tcx, &qpath), |
| 55 | + field |
| 56 | + ), |
| 57 | + }, |
| 58 | + ); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments