|
| 1 | +use rustc_hir as hir; |
| 2 | +use rustc_hir_pretty::qpath_to_string; |
| 3 | +use rustc_lint_defs::builtin::STATIC_MUT_REF; |
| 4 | +use rustc_middle::ty::TyCtxt; |
| 5 | +use rustc_span::Span; |
| 6 | +use rustc_type_ir::Mutability; |
| 7 | + |
| 8 | +use crate::errors; |
| 9 | + |
| 10 | +/// Check for shared or mutable references of `static mut` inside expression |
| 11 | +pub fn maybe_expr_static_mut(tcx: TyCtxt<'_>, expr: hir::Expr<'_>) { |
| 12 | + let span = expr.span; |
| 13 | + let hir_id = expr.hir_id; |
| 14 | + if let hir::ExprKind::AddrOf(borrow_kind, m, expr) = expr.kind |
| 15 | + && matches!(borrow_kind, hir::BorrowKind::Ref) |
| 16 | + && let Some(var) = is_path_static_mut(*expr) |
| 17 | + { |
| 18 | + handle_static_mut_ref( |
| 19 | + tcx, |
| 20 | + span, |
| 21 | + var, |
| 22 | + span.edition().at_least_rust_2024(), |
| 23 | + matches!(m, Mutability::Mut), |
| 24 | + hir_id, |
| 25 | + ); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +fn is_path_static_mut(expr: hir::Expr<'_>) -> Option<String> { |
| 30 | + if let hir::ExprKind::Path(qpath) = expr.kind |
| 31 | + && let hir::QPath::Resolved(_, path) = qpath |
| 32 | + && let hir::def::Res::Def(def_kind, _) = path.res |
| 33 | + && let hir::def::DefKind::Static(mt) = def_kind |
| 34 | + && matches!(mt, Mutability::Mut) |
| 35 | + { |
| 36 | + return Some(qpath_to_string(&qpath)); |
| 37 | + } |
| 38 | + None |
| 39 | +} |
| 40 | + |
| 41 | +fn handle_static_mut_ref( |
| 42 | + tcx: TyCtxt<'_>, |
| 43 | + span: Span, |
| 44 | + var: String, |
| 45 | + e2024: bool, |
| 46 | + mutable: bool, |
| 47 | + hir_id: hir::HirId, |
| 48 | +) { |
| 49 | + if e2024 { |
| 50 | + let sugg = if mutable { |
| 51 | + errors::StaticMutRefSugg::Mut { span, var } |
| 52 | + } else { |
| 53 | + errors::StaticMutRefSugg::Shared { span, var } |
| 54 | + }; |
| 55 | + tcx.sess.parse_sess.dcx.emit_err(errors::StaticMutRef { span, sugg }); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + let (label, sugg, shared) = if mutable { |
| 60 | + ( |
| 61 | + errors::RefOfMutStaticLabel::Mut { span }, |
| 62 | + errors::RefOfMutStaticSugg::Mut { span, var }, |
| 63 | + "mutable ", |
| 64 | + ) |
| 65 | + } else { |
| 66 | + ( |
| 67 | + errors::RefOfMutStaticLabel::Shared { span }, |
| 68 | + errors::RefOfMutStaticSugg::Shared { span, var }, |
| 69 | + "shared ", |
| 70 | + ) |
| 71 | + }; |
| 72 | + tcx.emit_spanned_lint( |
| 73 | + STATIC_MUT_REF, |
| 74 | + hir_id, |
| 75 | + span, |
| 76 | + errors::RefOfMutStatic { shared, why_note: (), label, sugg }, |
| 77 | + ); |
| 78 | +} |
0 commit comments