Skip to main content

rustc_lint/
raw_borrows_via_references.rs

1use rustc_ast::BorrowKind;
2use rustc_hir::{Expr, ExprKind, TyKind};
3use rustc_lint_defs::{declare_lint, declare_lint_pass};
4use rustc_middle::ty::{self, Ty};
5
6use crate::diagnostics::{RawBorrowViaReference, RawBorrowViaReferenceSuggestion};
7use crate::{LateContext, LateLintPass, LintContext};
8
9#[doc =
r" The `raw_borrows_via_references` lint checks for references that decay immediately into raw borrows."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![warn(raw_borrows_via_references)]"]
#[doc = r""]
#[doc = r" fn via_ref(x: *const (i32, i32)) -> *const i32 {"]
#[doc = r"     unsafe { &(*x).0 as *const i32 }"]
#[doc = r" }"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     let x = (0, 1);"]
#[doc = r"     let _r = via_ref(&x);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Creating unnecessary references is discouraged because it makes code"]
#[doc =
r" less explicit and can lead to undefined behavior. Creating a reference"]
#[doc = r" induces aliasing assumptions that the compiler relies on, so an"]
#[doc =
r" otherwise-pointless reference can cause undefined behavior even when the"]
#[doc =
r" reference is never read through. Avoiding them keeps the code more"]
#[doc = r" explicit and easier to reason about."]
#[doc = r""]
#[doc =
r" See the [Reference] for the full set of validity requirements that"]
#[doc = r" references must uphold."]
#[doc = r""]
#[doc =
r" [Reference]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it will trigger for a large"#]
#[doc = r" amount of existing Rust code."]
#[doc = r" Eventually it is desired for this to become warn-by-default."]
pub static RAW_BORROWS_VIA_REFERENCES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "RAW_BORROWS_VIA_REFERENCES",
            default_level: ::rustc_lint_defs::Allow,
            desc: "creating raw borrows via references is discouraged",
            ..
        };declare_lint! {
10    /// The `raw_borrows_via_references` lint checks for references that decay immediately into raw borrows.
11    ///
12    /// ### Example
13    ///
14    /// ```rust
15    /// #![warn(raw_borrows_via_references)]
16    ///
17    /// fn via_ref(x: *const (i32, i32)) -> *const i32 {
18    ///     unsafe { &(*x).0 as *const i32 }
19    /// }
20    ///
21    /// fn main() {
22    ///     let x = (0, 1);
23    ///     let _r = via_ref(&x);
24    /// }
25    /// ```
26    ///
27    /// {{produces}}
28    ///
29    /// ### Explanation
30    ///
31    /// Creating unnecessary references is discouraged because it makes code
32    /// less explicit and can lead to undefined behavior. Creating a reference
33    /// induces aliasing assumptions that the compiler relies on, so an
34    /// otherwise-pointless reference can cause undefined behavior even when the
35    /// reference is never read through. Avoiding them keeps the code more
36    /// explicit and easier to reason about.
37    ///
38    /// See the [Reference] for the full set of validity requirements that
39    /// references must uphold.
40    ///
41    /// [Reference]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
42    ///
43    /// This lint is "allow" by default because it will trigger for a large
44    /// amount of existing Rust code.
45    /// Eventually it is desired for this to become warn-by-default.
46    pub RAW_BORROWS_VIA_REFERENCES,
47    // FIXME: This should eventually be `Warn`, see the "Explanation" above.
48    Allow,
49    "creating raw borrows via references is discouraged"
50}
51
52pub struct RawBorrowsViaReferences;
#[automatically_derived]impl ::core::marker::Copy for RawBorrowsViaReferences
    {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RawBorrowsViaReferences {
}
#[automatically_derived]impl ::core::clone::Clone for RawBorrowsViaReferences
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for RawBorrowsViaReferences {
    fn name(&self) -> &'static str { "RawBorrowsViaReferences" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [RAW_BORROWS_VIA_REFERENCES]))
    }
}
impl RawBorrowsViaReferences {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [RAW_BORROWS_VIA_REFERENCES]))
    }
}declare_lint_pass!(RawBorrowsViaReferences => [RAW_BORROWS_VIA_REFERENCES]);
53
54impl<'tcx> LateLintPass<'tcx> for RawBorrowsViaReferences {
55    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
56        if let ExprKind::Cast(exp, ty) = expr.kind
57            && let ExprKind::AddrOf(BorrowKind::Ref, mutbl, addr_of_exp) = exp.kind
58            && let TyKind::Ptr(..) = ty.kind
59            && addr_of_exp.is_syntactic_place_expr()
60        {
61            let suggestion = if let Some(borrow_span) =
62                exp.span.find_ancestor_inside_same_ctxt(expr.span)
63                && let Some(addr_of_span) = addr_of_exp.span.find_ancestor_in_same_ctxt(expr.span)
64                && let Some(ty_span) = ty.span.find_ancestor_in_same_ctxt(expr.span)
65                && borrow_span.can_be_used_for_suggestions()
66                && addr_of_span.can_be_used_for_suggestions()
67                && ty_span.can_be_used_for_suggestions()
68            {
69                let drop_cast = cx.typeck_results().expr_ty_opt(exp).is_some_and(|borrow_ty| {
70                    cx.typeck_results().expr_ty_opt(expr).is_some_and(|cast_ty| {
71                        #[allow(non_exhaustive_omitted_patterns)] match borrow_ty.kind() {
    ty::Ref(_, referent, ref_mutbl) if
        cast_ty == Ty::new_ptr(cx.tcx, *referent, *ref_mutbl) => true,
    _ => false,
}matches!(
72                            borrow_ty.kind(),
73                            ty::Ref(_, referent, ref_mutbl)
74                                if cast_ty == Ty::new_ptr(cx.tcx, *referent, *ref_mutbl)
75                        )
76                    })
77                });
78                RawBorrowViaReferenceSuggestion::Spanful {
79                    left: borrow_span.until(addr_of_span),
80                    right: drop_cast
81                        .then(|| addr_of_span.shrink_to_hi().until(ty_span.shrink_to_hi())),
82                    mutbl: mutbl.ptr_str(),
83                }
84            } else {
85                RawBorrowViaReferenceSuggestion::Spanless { mutbl: mutbl.ptr_str() }
86            };
87
88            cx.emit_span_lint(
89                RAW_BORROWS_VIA_REFERENCES,
90                expr.span,
91                RawBorrowViaReference { suggestion },
92            );
93        }
94    }
95}