flux_common/
mir_storage.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! This module allows storing mir bodies with borrowck facts in a thread-local
6//! storage. Unfortunately, thread local storage requires all data stored in it
7//! to have a `'static` lifetime. Therefore, we transmute the lifetime `'tcx`
8//! away when storing the data. To ensure that nothing gets meessed up, we
9//! require the client to provide a witness: an instance of type `TyCtxt<'tcx>`
10//! that is used to show that the lifetime that the client provided is indeed
11//! `'tcx`.
12
13use std::{cell::RefCell, collections::HashMap, thread_local};
14
15use rustc_borrowck::consumers::BodyWithBorrowckFacts;
16use rustc_hir::def_id::LocalDefId;
17use rustc_middle::ty::TyCtxt;
18
19use crate::bug;
20
21thread_local! {
22    pub static SHARED_STATE:
23        RefCell<HashMap<LocalDefId, BodyWithBorrowckFacts<'static>>> =
24        RefCell::new(HashMap::new());
25}
26
27/// # Safety
28///
29/// See the module level comment.
30pub unsafe fn store_mir_body<'tcx>(
31    _tcx: TyCtxt<'tcx>,
32    def_id: LocalDefId,
33    body_with_facts: BodyWithBorrowckFacts<'tcx>,
34) {
35    // SAFETY: See the module level comment.
36    let body_with_facts: BodyWithBorrowckFacts<'static> =
37        unsafe { std::mem::transmute(body_with_facts) };
38    SHARED_STATE.with(|state| {
39        let mut map = state.borrow_mut();
40        assert!(map.insert(def_id, body_with_facts).is_none());
41    });
42}
43
44/// # Safety
45///
46/// See the module level comment.
47#[expect(clippy::needless_lifetimes, reason = "we want to be very explicit about lifetimes here")]
48pub unsafe fn retrieve_mir_body<'tcx>(
49    _tcx: TyCtxt<'tcx>,
50    def_id: LocalDefId,
51) -> BodyWithBorrowckFacts<'tcx> {
52    let body_with_facts: BodyWithBorrowckFacts<'static> = SHARED_STATE.with(|state| {
53        match state.borrow_mut().remove(&def_id) {
54            Some(body) => body,
55            None => bug!("retrieve_mir_body: panic on {def_id:?}"),
56        }
57    });
58    // SAFETY: See the module level comment.
59    unsafe { std::mem::transmute(body_with_facts) }
60}