Skip to main content

charon_driver/frontend/
state.rs

1use crate::frontend::prelude::*;
2use annotate_snippets::Level;
3use rustc_middle::ty::{self, TyCtxt};
4use std::cell::RefCell;
5
6mod base {
7    use crate::frontend::prelude::*;
8    use itertools::Itertools;
9    use rustc_hash::FxHashMap;
10    use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
11    use rustc_middle::ty;
12    use rustc_span::symbol::Symbol;
13    use rustc_trait_elaboration::{ElaborationCtx, ItemRefKey, intern::Interner};
14    use std::{cell::RefCell, sync::Arc};
15
16    pub struct LocalContextS {
17        pub vars: HashMap<rustc_middle::thir::LocalVarId, String>,
18    }
19
20    impl Default for LocalContextS {
21        fn default() -> Self {
22            Self::new()
23        }
24    }
25
26    impl LocalContextS {
27        pub fn new() -> LocalContextS {
28            LocalContextS {
29                vars: HashMap::default(),
30            }
31        }
32    }
33
34    /// Global caches
35    #[derive(Default)]
36    pub struct GlobalCache<'tcx> {
37        /// Per-item cache.
38        pub per_item: HashMap<DefId, Rc<RefCell<ItemCache<'tcx>>>>,
39        /// Map rustc def ids to their frontend counterpart.
40        pub def_ids: HashMap<RDefId, DefId>,
41        /// Data for synthetic items. See the `synthetic_items` module.
42        pub synthetic_item_data: HashMap<SyntheticItem, SyntheticItemData<'tcx>>,
43        /// Anonymous allocations we turned into globals, in encounter order. Used to keep
44        /// the order of globals stable across runs.
45        pub anon_allocs: indexmap::IndexSet<RAllocId, rustc_hash::FxBuildHasher>,
46        /// The state shared by the constant readers.
47        pub const_reader_state: rustc_const_uneval::ReaderState<'tcx>,
48        /// Cached names and disambiguators for crate names.
49        pub disambiguated_crate_names: Option<FxHashMap<CrateNum, (Symbol, u32)>>,
50    }
51
52    impl<'tcx> GlobalCache<'tcx> {
53        pub fn crate_name(&mut self, tcx: ty::TyCtxt<'tcx>, krate: CrateNum) -> (Symbol, u32) {
54            self.disambiguated_crate_names
55                .get_or_insert_with(|| {
56                    std::iter::once(LOCAL_CRATE)
57                        .chain(tcx.crates(()).iter().copied())
58                        .into_group_map_by(|&cnum| tcx.crate_name(cnum))
59                        .into_iter()
60                        .filter(|(_, crates_by_this_name)| crates_by_this_name.len() > 1)
61                        .flat_map(|(name, mut crates_by_this_name)| {
62                            crates_by_this_name.sort_by_key(|&cnum| {
63                                // `tcx.stable_crate_id` isn't actually so stable across machines.
64                                // We try our own stability here based on paths.
65                                let source_file = tcx
66                                    .sess
67                                    .source_map()
68                                    .span_to_filename(tcx.def_span(cnum.as_def_id()))
69                                    .prefer_remapped_unconditionally()
70                                    .to_string_lossy()
71                                    .into_owned();
72                                let extern_paths = if cnum == LOCAL_CRATE {
73                                    Vec::new()
74                                } else {
75                                    tcx.crate_extern_paths(cnum)
76                                        .iter()
77                                        .map(|path| path.display().to_string())
78                                        .collect_vec()
79                                };
80                                (
81                                    cnum != LOCAL_CRATE,
82                                    source_file,
83                                    extern_paths,
84                                    cnum.as_u32(),
85                                )
86                            });
87                            crates_by_this_name.into_iter().enumerate().map(
88                                move |(disambiguator, cnum)| (cnum, (name, disambiguator as u32)),
89                            )
90                        })
91                        .collect()
92                })
93                .get(&krate)
94                .copied()
95                .unwrap_or_else(|| (tcx.crate_name(krate), 0))
96        }
97    }
98
99    /// Per-item cache
100    #[derive(Default)]
101    pub struct ItemCache<'tcx> {
102        /// The translated definition, optionally instantiated with generic arguments.
103        pub full_defs: HashMap<Option<ty::GenericArgs<'tcx>>, Arc<FullDef<'tcx>>>,
104        /// Cache the `Ty` translations.
105        pub tys: HashMap<ty::Ty<'tcx>, Ty<'tcx>>,
106        /// Cache the `ItemRef` translations. This is fast because `GenericArgs` is interned.
107        pub item_refs: HashMap<ItemRefKey<'tcx, DefId>, ItemRef<'tcx>>,
108        /// Cache of trait refs to resolved trait proofs.
109        pub trait_proofs:
110            HashMap<ty::PolyTraitRef<'tcx>, crate::frontend::traits::TraitProof<'tcx>>,
111        /// Generics for this item, if it is virtual.
112        pub virtual_generics: Option<rustc_trait_elaboration::GenericParams<'tcx, DefId>>,
113        /// Trait clauses required to make this type alias well-formed.
114        pub alias_clauses: Option<Vec<ty::Clause<'tcx>>>,
115    }
116
117    #[derive(Clone)]
118    pub struct Base<'tcx> {
119        pub ty_interner: &'tcx Interner<'tcx, TyKind<'tcx>>,
120        pub trait_proof_interner: &'tcx Interner<'tcx, TraitProofContents<'tcx>>,
121        pub item_ref_interner: &'tcx Interner<'tcx, ItemRefContents<'tcx>>,
122        pub options: Rc<crate::frontend::options::Options>,
123        pub local_ctx: Rc<RefCell<LocalContextS>>,
124        pub opt_def_id: Option<rustc_hir::def_id::DefId>,
125        pub cache: Rc<RefCell<GlobalCache<'tcx>>>,
126        pub elab_ctx: crate::frontend::traits::ElaborationCtx<'tcx, DefId>,
127        pub tcx: ty::TyCtxt<'tcx>,
128    }
129
130    impl<'tcx> Base<'tcx> {
131        pub fn new(
132            tcx: rustc_middle::ty::TyCtxt<'tcx>,
133            options: crate::frontend::options::Options,
134            bounds_options: crate::frontend::options::BoundsOptions,
135        ) -> Self {
136            Self {
137                tcx,
138                ty_interner: Box::leak(Box::default()),
139                trait_proof_interner: Box::leak(Box::default()),
140                item_ref_interner: Box::leak(Box::default()),
141                cache: Default::default(),
142                options: Rc::new(options),
143                // Always prefer `s.owner_id()` to `s.base().opt_def_id`.
144                // `opt_def_id` is used in `utils` for error reporting
145                opt_def_id: None,
146                local_ctx: Rc::new(RefCell::new(LocalContextS::new())),
147                elab_ctx: ElaborationCtx::new(tcx, bounds_options),
148            }
149        }
150    }
151}
152
153pub use self::base::*;
154
155pub trait BaseState<'tcx>: Sized {
156    fn base(&self) -> &Base<'tcx>;
157
158    fn tcx(&self) -> TyCtxt<'tcx> {
159        self.base().tcx
160    }
161
162    /// Raise an error or warning.
163    fn raise(&self, level: Level, span: Span, msg: String) {
164        let backtrace = std::backtrace::Backtrace::capture();
165        eprintln!("{}", backtrace);
166        let dcx = self.tcx().dcx();
167        if level == Level::ERROR {
168            dcx.span_err(span, msg);
169        } else {
170            dcx.span_warn(span, msg);
171        }
172    }
173
174    /// Create a state with the given owner.
175    fn with_frontend_owner(&self, owner: &DefId) -> StateWithOwner<'tcx> {
176        let mut base = self.base().clone();
177        base.opt_def_id = owner.as_real_or_promoted();
178        State {
179            owner: Owner {
180                def_id: owner.clone(),
181                cache: self.item_cache(owner),
182            },
183            base,
184        }
185    }
186    /// Create a state with the given owner.
187    fn with_rustc_owner(&self, owner_id: RDefId) -> StateWithOwner<'tcx> {
188        let owner = &owner_id.sinto(self);
189        Self::with_frontend_owner(self, owner)
190    }
191
192    /// State with only access to the global state.
193    fn base_state(&self) -> StateWithBase<'tcx> {
194        State {
195            base: self.base().clone(),
196            owner: (),
197        }
198    }
199
200    /// Access the global cache. You must not call `sinto` within this function as this will likely
201    /// result in `BorrowMut` panics.
202    fn with_global_cache<T>(&self, f: impl FnOnce(&mut GlobalCache<'tcx>) -> T) -> T {
203        let base = self.base();
204        let mut cache = base.cache.borrow_mut();
205        f(&mut cache)
206    }
207    /// The cache for a given item.
208    fn item_cache(&self, def_id: &DefId) -> Rc<RefCell<ItemCache<'tcx>>> {
209        self.with_global_cache(|cache| cache.per_item.entry(def_id.clone()).or_default().clone())
210    }
211    /// Access the cache for a given item. You must not call `sinto` within this function as this
212    /// will likely result in `BorrowMut` panics.
213    fn with_item_cache<T>(&self, def_id: &DefId, f: impl FnOnce(&mut ItemCache<'tcx>) -> T) -> T {
214        f(&mut self.item_cache(def_id).borrow_mut())
215    }
216}
217
218pub trait UnderOwnerState<'tcx>: BaseState<'tcx> {
219    fn owner(&self) -> DefId;
220    fn owner_cache(&self) -> &Rc<RefCell<ItemCache<'tcx>>>;
221
222    fn param_env(&self) -> ty::ParamEnv<'tcx> {
223        self.owner().param_env(self)
224    }
225    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
226        self.owner().typing_env(self)
227    }
228
229    fn as_state_with_owner(&self) -> StateWithOwner<'tcx> {
230        State {
231            base: self.base().clone(),
232            owner: Owner {
233                def_id: self.owner(),
234                cache: self.owner_cache().clone(),
235            },
236        }
237    }
238
239    /// Access the cache for the current item. You must not call `sinto` within this function as
240    /// this will likely result in `BorrowMut` panics.
241    fn with_cache<T>(&self, f: impl FnOnce(&mut ItemCache<'tcx>) -> T) -> T {
242        f(&mut self.owner_cache().borrow_mut())
243    }
244    fn with_predicate_searcher<T>(
245        &self,
246        f: impl FnOnce(&mut PredicateSearcher<'tcx>, &StateWithBase<'tcx>) -> T,
247    ) -> T {
248        let s = self;
249        let base = s.base();
250        let owner = s.owner();
251        let base_state = s.base_state();
252        let mut predicate_searcher = base.elab_ctx.predicate_searcher_for(&base_state, owner);
253        f(&mut predicate_searcher, &base_state)
254    }
255}
256
257#[derive(Clone)]
258pub struct State<'tcx, Owner> {
259    pub base: Base<'tcx>,
260    pub owner: Owner,
261}
262
263/// The item whose context we are in, with its cache.
264// We keep the cache here rather than going through `GlobalCache` for perf reasons.
265#[derive(Clone)]
266pub struct Owner<'tcx> {
267    def_id: DefId,
268    cache: Rc<RefCell<ItemCache<'tcx>>>,
269}
270
271pub type StateWithBase<'tcx> = State<'tcx, ()>;
272pub type StateWithOwner<'tcx> = State<'tcx, Owner<'tcx>>;
273
274impl<'tcx> StateWithBase<'tcx> {
275    pub fn new(
276        tcx: rustc_middle::ty::TyCtxt<'tcx>,
277        options: crate::frontend::options::Options,
278        bounds_options: crate::frontend::options::BoundsOptions,
279    ) -> Self {
280        Self {
281            base: Base::new(tcx, options, bounds_options),
282            owner: (),
283        }
284    }
285}
286impl<'tcx, O> BaseState<'tcx> for State<'tcx, O> {
287    fn base(&self) -> &Base<'tcx> {
288        &self.base
289    }
290}
291impl<'tcx> UnderOwnerState<'tcx> for StateWithOwner<'tcx> {
292    fn owner(&self) -> DefId {
293        self.owner.def_id.clone()
294    }
295    fn owner_cache(&self) -> &Rc<RefCell<ItemCache<'tcx>>> {
296        &self.owner.cache
297    }
298}
299
300impl<'tcx, A: BaseState<'tcx>, B> BaseState<'tcx> for (A, B) {
301    fn base(&self) -> &Base<'tcx> {
302        self.0.base()
303    }
304}
305impl<'tcx, A: UnderOwnerState<'tcx>, B> UnderOwnerState<'tcx> for (A, B) {
306    fn owner(&self) -> DefId {
307        self.0.owner()
308    }
309    fn owner_cache(&self) -> &Rc<RefCell<ItemCache<'tcx>>> {
310        self.0.owner_cache()
311    }
312}