Skip to main content

rustc_lint/
implicit_provenance_casts.rs

1use rustc_ast::util::parser::ExprPrecedence;
2use rustc_hir as hir;
3use rustc_lint_defs::{declare_lint, declare_lint_pass};
4use rustc_middle::ty::Ty;
5
6use crate::diagnostics::{
7    ImplicitProvenanceCastsInt2Ptr, ImplicitProvenanceCastsPtr2Int, Int2PtrSuggestion,
8    Ptr2IntSuggestion,
9};
10use crate::utils::std_or_core;
11use crate::{LateContext, LateLintPass};
12
13#[doc =
r" The `implicit_provenance_casts` lint detects integer-to-pointer and pointer-to-integer"]
#[doc = r" casts."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(strict_provenance_lints)]"]
#[doc = r" #![warn(implicit_provenance_casts)]"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     let x: u8 = 37;"]
#[doc = r"     let addr: usize = &x as *const u8 as usize;"]
#[doc = r"     let _ptr = addr as *const u8;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint exists to help migrate code to [*Strict Provenance* APIs][strict-provenance] where"]
#[doc =
r" possible, and make remaining uses of [*Exposed Provenance*][exposed-provenance] explicit."]
#[doc =
r" For more information on pointer provenance, see the [`std::ptr` documentation][provenance]."]
#[doc = r""]
#[doc =
r" Earlier versions of Rust did not have a clear answer how integer-to-pointer and"]
#[doc =
r" pointer-to-integer casts interact with provenance. Such casts are now defined to use the"]
#[doc =
r" exposed provenance model, but in many cases the code can be updated to strict provenance"]
#[doc =
r" APIs, which is preferable as it enables more precise reasoning about unsafe code, both by"]
#[doc = r" humans and by tools like [Miri]."]
#[doc = r""]
#[doc =
r" However, there are situations where exposed provenance is required or following the strict"]
#[doc =
r" provenance model requires major refactorings. In those cases, it's still useful to replace"]
#[doc =
r" the `as` casts with equivalent explicit use of exposed provenance APIs and a comment"]
#[doc = r" explaining why they are needed."]
#[doc = r""]
#[doc =
r" [provenance]: https://doc.rust-lang.org/core/ptr/index.html#provenance"]
#[doc =
r" [strict-provenance]: https://doc.rust-lang.org/core/ptr/index.html#strict-provenance"]
#[doc =
r" [exposed-provenance]: https://doc.rust-lang.org/core/ptr/index.html#exposed-provenance"]
#[doc = r" [Miri]: https://github.com/rust-lang/miri"]
pub static IMPLICIT_PROVENANCE_CASTS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "IMPLICIT_PROVENANCE_CASTS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "an `as` cast relying on exposed provenance is used",
            feature_gate: Some(rustc_span::sym::strict_provenance_lints),
            ..
        };declare_lint! {
14    /// The `implicit_provenance_casts` lint detects integer-to-pointer and pointer-to-integer
15    /// casts.
16    ///
17    /// ### Example
18    ///
19    /// ```rust
20    /// #![feature(strict_provenance_lints)]
21    /// #![warn(implicit_provenance_casts)]
22    ///
23    /// fn main() {
24    ///     let x: u8 = 37;
25    ///     let addr: usize = &x as *const u8 as usize;
26    ///     let _ptr = addr as *const u8;
27    /// }
28    /// ```
29    ///
30    /// {{produces}}
31    ///
32    /// ### Explanation
33    ///
34    /// This lint exists to help migrate code to [*Strict Provenance* APIs][strict-provenance] where
35    /// possible, and make remaining uses of [*Exposed Provenance*][exposed-provenance] explicit.
36    /// For more information on pointer provenance, see the [`std::ptr` documentation][provenance].
37    ///
38    /// Earlier versions of Rust did not have a clear answer how integer-to-pointer and
39    /// pointer-to-integer casts interact with provenance. Such casts are now defined to use the
40    /// exposed provenance model, but in many cases the code can be updated to strict provenance
41    /// APIs, which is preferable as it enables more precise reasoning about unsafe code, both by
42    /// humans and by tools like [Miri].
43    ///
44    /// However, there are situations where exposed provenance is required or following the strict
45    /// provenance model requires major refactorings. In those cases, it's still useful to replace
46    /// the `as` casts with equivalent explicit use of exposed provenance APIs and a comment
47    /// explaining why they are needed.
48    ///
49    /// [provenance]: https://doc.rust-lang.org/core/ptr/index.html#provenance
50    /// [strict-provenance]: https://doc.rust-lang.org/core/ptr/index.html#strict-provenance
51    /// [exposed-provenance]: https://doc.rust-lang.org/core/ptr/index.html#exposed-provenance
52    /// [Miri]: https://github.com/rust-lang/miri
53    pub IMPLICIT_PROVENANCE_CASTS,
54    Allow,
55    "an `as` cast relying on exposed provenance is used",
56    @feature_gate = strict_provenance_lints;
57}
58
59#[doc = r" Lint for int2ptr and ptr2int `as` casts."]
pub struct ImplicitProvenanceCasts;
#[automatically_derived]impl ::core::marker::Copy for ImplicitProvenanceCasts
    {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ImplicitProvenanceCasts {
}
#[automatically_derived]impl ::core::clone::Clone for ImplicitProvenanceCasts
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for ImplicitProvenanceCasts {
    fn name(&self) -> &'static str { "ImplicitProvenanceCasts" }
    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(),
                [IMPLICIT_PROVENANCE_CASTS]))
    }
}
impl ImplicitProvenanceCasts {
    #[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(),
                [IMPLICIT_PROVENANCE_CASTS]))
    }
}declare_lint_pass!(
60    /// Lint for int2ptr and ptr2int `as` casts.
61    ImplicitProvenanceCasts => [IMPLICIT_PROVENANCE_CASTS]
62);
63
64impl<'tcx> LateLintPass<'tcx> for ImplicitProvenanceCasts {
65    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
66        let hir::ExprKind::Cast(cast_from_expr, cast_to_hir) = expr.kind else { return };
67
68        let typeck_results = cx.typeck_results();
69        let cast_from_ty = typeck_results.expr_ty(cast_from_expr);
70        if cast_from_ty.is_raw_ptr() {
71            let cast_to_ty = typeck_results.expr_ty(expr);
72            if cast_to_ty.is_integral() {
73                let krate = std_or_core(cx).unwrap_or("core");
74                lint_ptr2int(cx, krate, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty)
75            }
76        } else if cast_from_ty.is_integral() {
77            let cast_to_ty = typeck_results.expr_ty(expr);
78            if cast_to_ty.is_raw_ptr() {
79                let krate = std_or_core(cx).unwrap_or("core");
80                lint_int2ptr(cx, krate, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty)
81            }
82        }
83    }
84}
85
86fn lint_ptr2int<'tcx>(
87    cx: &LateContext<'tcx>,
88    krate: &'static str,
89    expr: &'tcx hir::Expr<'tcx>,
90    cast_from_expr: &'tcx hir::Expr<'tcx>,
91    cast_from_ty: Ty<'tcx>,
92    cast_to_hir: &'tcx hir::Ty<'tcx>,
93    cast_to_ty: Ty<'tcx>,
94) {
95    let sugg = expr.span.can_be_used_for_suggestions().then(|| {
96        let needs_parens = cx.precedence(cast_from_expr) < ExprPrecedence::Unambiguous;
97        let needs_cast = !cast_to_ty.is_usize();
98        let cast_span = cast_from_expr.span.shrink_to_hi().to(cast_to_hir.span);
99        let expr_span = cast_from_expr.span.shrink_to_lo();
100        match (needs_parens, needs_cast) {
101            (true, true) => Ptr2IntSuggestion::NeedsParensCast { expr_span, cast_span, cast_to_ty },
102            (true, false) => Ptr2IntSuggestion::NeedsParens { expr_span, cast_span },
103            (false, true) => Ptr2IntSuggestion::NeedsCast { cast_span, cast_to_ty },
104            (false, false) => Ptr2IntSuggestion::Other { cast_span },
105        }
106    });
107
108    let lint = ImplicitProvenanceCastsPtr2Int { cast_from_ty, cast_to_ty, krate, sugg };
109    cx.tcx.emit_node_span_lint(IMPLICIT_PROVENANCE_CASTS, expr.hir_id, expr.span, lint);
110}
111
112fn lint_int2ptr<'tcx>(
113    cx: &LateContext<'tcx>,
114    krate: &'static str,
115    expr: &'tcx hir::Expr<'tcx>,
116    cast_from_expr: &'tcx hir::Expr<'tcx>,
117    cast_from_ty: Ty<'tcx>,
118    cast_to_hir: &'tcx hir::Ty<'tcx>,
119    cast_to_ty: Ty<'tcx>,
120) {
121    let sugg = expr.span.can_be_used_for_suggestions().then(|| Int2PtrSuggestion {
122        lo: cast_from_expr.span.shrink_to_lo(),
123        hi: cast_from_expr.span.shrink_to_hi().to(cast_to_hir.span),
124    });
125    let lint =
126        ImplicitProvenanceCastsInt2Ptr { expr_ty: cast_from_ty, cast_ty: cast_to_ty, krate, sugg };
127    cx.tcx.emit_node_span_lint(IMPLICIT_PROVENANCE_CASTS, expr.hir_id, expr.span, lint)
128}