charon_driver/translate/
translate_ctx.rs

1//! The translation contexts.
2use super::translate_crate::RustcItem;
3pub use super::translate_crate::{TraitImplSource, TransItemSource, TransItemSourceKind};
4use super::translate_generics::BindingLevel;
5use charon_lib::ast::*;
6use charon_lib::formatter::{FmtCtx, IntoFormatter};
7use charon_lib::options::TranslateOptions;
8use hax::SInto;
9use rustc_middle::ty::TyCtxt;
10use std::borrow::Cow;
11use std::cell::RefCell;
12use std::collections::{BTreeSet, HashMap, HashSet};
13use std::fmt::Debug;
14use std::ops::{Deref, DerefMut};
15use std::path::PathBuf;
16use std::sync::Arc;
17use std::{fmt, mem};
18
19// Re-export to avoid having to fix imports.
20pub(crate) use charon_lib::errors::{
21    DepSource, ErrorCtx, Level, error_assert, raise_error, register_error,
22};
23
24/// Translation context used while translating the crate data into our representation.
25pub struct TranslateCtx<'tcx> {
26    /// The Rust compiler type context
27    pub tcx: TyCtxt<'tcx>,
28    /// Path to the toolchain root.
29    pub sysroot: PathBuf,
30    /// The Hax context
31    pub hax_state: hax::StateWithBase<'tcx>,
32
33    /// The options that control translation.
34    pub options: TranslateOptions,
35    /// The translated data.
36    pub translated: TranslatedCrate,
37
38    /// Record data for each method whether it is ever used (called or implemented) and the
39    /// `FunDeclId`s of the implementations. We use this to lazily translate methods, so that we
40    /// skip unused default methods of large traits like `Iterator`.
41    ///
42    /// The complete scheme works as follows: by default we enqueue no methods for translation.
43    /// When we find a use of a method, we mark it "used" using `mark_method_as_used`. This
44    /// enqueues all known and future impls of this method. We also mark a method as used if we
45    /// find an implementation of it in a non-opaque impl, and if the method is a required method.
46    pub method_status: IndexMap<TraitDeclId, HashMap<TraitItemName, MethodStatus>>,
47
48    /// The map from rustc id to translated id.
49    pub id_map: HashMap<TransItemSource, ItemId>,
50    /// The reverse map of ids.
51    pub reverse_id_map: HashMap<ItemId, TransItemSource>,
52    /// The reverse filename map.
53    pub file_to_id: HashMap<FileName, FileId>,
54
55    /// Context for tracking and reporting errors.
56    pub errors: RefCell<ErrorCtx>,
57    /// The declarations we came accross and which we haven't translated yet. We keep them sorted
58    /// to make the output order a bit more stable.
59    pub items_to_translate: BTreeSet<TransItemSource>,
60    /// The declaration we've already processed (successfully or not).
61    pub processed: HashSet<TransItemSource>,
62    /// Stack of the translations currently happening. Used to avoid accidental cycles.
63    pub translate_stack: Vec<ItemId>,
64    /// Cache the names to compute them only once each.
65    pub cached_names: HashMap<RustcItem, Name>,
66    /// Cache the `ItemMeta`s to compute them only once each.
67    pub cached_item_metas: HashMap<TransItemSource, ItemMeta>,
68}
69
70/// Tracks whether a method is used (i.e. called or (non-opaquely) implemented).
71#[derive(Debug)]
72pub enum MethodStatus {
73    Unused {
74        /// The `FunDeclId`s of the method implementations. Because the method is unused, these
75        /// items are not enqueued for translation yet. When marking the method as used we'll
76        /// enqueue them.
77        implementors: HashSet<FunDeclId>,
78    },
79    Used,
80}
81
82impl Default for MethodStatus {
83    fn default() -> Self {
84        Self::Unused {
85            implementors: Default::default(),
86        }
87    }
88}
89
90/// A translation context for items.
91/// Augments the [TranslateCtx] with type-level variables.
92pub(crate) struct ItemTransCtx<'tcx, 'ctx> {
93    /// The definition we are currently extracting.
94    pub item_src: TransItemSource,
95    /// The id of the definition we are currently extracting, if there is one.
96    pub item_id: Option<ItemId>,
97    /// The translation context containing the top-level definitions/ids.
98    pub t_ctx: &'ctx mut TranslateCtx<'tcx>,
99    /// The Hax context with the current `DefId`.
100    pub hax_state_with_id: hax::StateWithOwner<'tcx>,
101    /// Whether to consider a `ImplExprAtom::Error` as an error for us. True except inside type
102    /// aliases, because rust does not enforce correct trait bounds on type aliases.
103    pub error_on_impl_expr_error: bool,
104
105    /// The stack of generic parameter binders for the current context. Each binder introduces an
106    /// entry in this stack, with the entry as index `0` being the innermost binder. These
107    /// parameters are referenced using [`DeBruijnVar`]; see there for details.
108    pub binding_levels: BindingStack<BindingLevel>,
109    /// When `Some`, translate any erased lifetime to a fresh `Region::Body` lifetime.
110    pub lifetime_freshener: Option<IndexMap<RegionId, ()>>,
111}
112
113/// Translates `T` into `U` using `hax`'s `SInto` trait, catching any hax panics.
114pub fn catch_sinto<S, T, U>(
115    s: &S,
116    err: &mut ErrorCtx,
117    krate: &TranslatedCrate,
118    span: Span,
119    x: &T,
120) -> Result<U, Error>
121where
122    T: Debug + SInto<S, U>,
123{
124    let unwind_safe_s = std::panic::AssertUnwindSafe(s);
125    let unwind_safe_x = std::panic::AssertUnwindSafe(x);
126    std::panic::catch_unwind(move || unwind_safe_x.sinto(*unwind_safe_s)).or_else(|_| {
127        raise_error!(
128            err,
129            crate(krate),
130            span,
131            "Hax panicked when translating `{x:?}`."
132        )
133    })
134}
135
136impl<'tcx, 'ctx> TranslateCtx<'tcx> {
137    /// Span an error and register the error.
138    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
139        self.errors
140            .borrow_mut()
141            .span_err(&self.translated, span, msg, level)
142    }
143
144    /// Translates `T` into `U` using `hax`'s `SInto` trait, catching any hax panics.
145    pub fn catch_sinto<S, T, U>(&mut self, s: &S, span: Span, x: &T) -> Result<U, Error>
146    where
147        T: Debug + SInto<S, U>,
148    {
149        catch_sinto(s, &mut *self.errors.borrow_mut(), &self.translated, span, x)
150    }
151
152    /// Return the polymorphic definition for this item. Use with care, prefer `hax_def` whenever
153    /// possible.
154    ///
155    /// Used for computing names, for associated items, and for various checks.
156    pub fn poly_hax_def(&mut self, def_id: &hax::DefId) -> Result<Arc<hax::FullDef>, Error> {
157        self.hax_def_for_item(&RustcItem::Poly(def_id.clone()))
158    }
159
160    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
161    /// depending on user choice.
162    pub fn hax_def_for_item(&mut self, item: &RustcItem) -> Result<Arc<hax::FullDef>, Error> {
163        let def_id = item.def_id();
164        let span = self.def_span(def_id);
165        if let RustcItem::Mono(item_ref) = item
166            && item_ref.has_non_lt_param
167        {
168            raise_error!(self, span, "Item is not monomorphic: {item:?}")
169        }
170        // Hax takes care of caching the translation.
171        let unwind_safe_s = std::panic::AssertUnwindSafe(&self.hax_state);
172        std::panic::catch_unwind(move || match item {
173            RustcItem::Poly(def_id) => def_id.full_def(*unwind_safe_s),
174            RustcItem::Mono(item_ref) => item_ref.instantiated_full_def(*unwind_safe_s),
175        })
176        .or_else(|_| raise_error!(self, span, "Hax panicked when translating `{def_id:?}`."))
177    }
178
179    pub(crate) fn with_def_id<F, T>(
180        &mut self,
181        def_id: &hax::DefId,
182        item_id: Option<ItemId>,
183        f: F,
184    ) -> T
185    where
186        F: FnOnce(&mut Self) -> T,
187    {
188        let mut errors = self.errors.borrow_mut();
189        let current_def_id = mem::replace(&mut errors.def_id, item_id);
190        let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id.is_local);
191        drop(errors); // important: release the refcell "lock"
192        let ret = f(self);
193        let mut errors = self.errors.borrow_mut();
194        errors.def_id = current_def_id;
195        errors.def_id_is_local = current_def_id_is_local;
196        ret
197    }
198}
199
200impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
201    /// Create a new `ExecContext`.
202    pub(crate) fn new(
203        item_src: TransItemSource,
204        item_id: Option<ItemId>,
205        t_ctx: &'ctx mut TranslateCtx<'tcx>,
206    ) -> Self {
207        use hax::BaseState;
208        let def_id = item_src.def_id().underlying_rust_def_id();
209        let hax_state_with_id = t_ctx.hax_state.clone().with_owner_id(def_id);
210        ItemTransCtx {
211            item_src,
212            item_id,
213            t_ctx,
214            hax_state_with_id,
215            error_on_impl_expr_error: true,
216            binding_levels: Default::default(),
217            lifetime_freshener: None,
218        }
219    }
220
221    /// Whether to monomorphize items we encounter.
222    pub fn monomorphize(&self) -> bool {
223        matches!(self.item_src.item, RustcItem::Mono(..))
224    }
225
226    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
227        self.t_ctx.span_err(span, msg, level)
228    }
229
230    pub fn hax_state(&self) -> &hax::StateWithBase<'tcx> {
231        &self.t_ctx.hax_state
232    }
233
234    pub fn hax_state_with_id(&self) -> &hax::StateWithOwner<'tcx> {
235        &self.hax_state_with_id
236    }
237
238    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
239    /// depending on user choice.
240    pub fn hax_def(&mut self, item: &hax::ItemRef) -> Result<Arc<hax::FullDef>, Error> {
241        let item = if self.monomorphize() {
242            RustcItem::Mono(item.clone())
243        } else {
244            RustcItem::Poly(item.def_id.clone())
245        };
246        self.t_ctx.hax_def_for_item(&item)
247    }
248
249    pub(crate) fn poly_hax_def(&mut self, def_id: &hax::DefId) -> Result<Arc<hax::FullDef>, Error> {
250        self.t_ctx.poly_hax_def(def_id)
251    }
252}
253
254impl<'tcx> Deref for ItemTransCtx<'tcx, '_> {
255    type Target = TranslateCtx<'tcx>;
256    fn deref(&self) -> &Self::Target {
257        self.t_ctx
258    }
259}
260impl<'tcx> DerefMut for ItemTransCtx<'tcx, '_> {
261    fn deref_mut(&mut self) -> &mut Self::Target {
262        self.t_ctx
263    }
264}
265
266impl<'a> IntoFormatter for &'a TranslateCtx<'_> {
267    type C = FmtCtx<'a>;
268    fn into_fmt(self) -> Self::C {
269        self.translated.into_fmt()
270    }
271}
272
273impl<'a> IntoFormatter for &'a ItemTransCtx<'_, '_> {
274    type C = FmtCtx<'a>;
275    fn into_fmt(self) -> Self::C {
276        FmtCtx {
277            translated: Some(&self.t_ctx.translated),
278            generics: self.binding_levels.map_ref(|bl| Cow::Borrowed(&bl.params)),
279            locals: None,
280            indent_level: 0,
281        }
282    }
283}
284
285impl<'tcx, 'ctx> fmt::Display for TranslateCtx<'tcx> {
286    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287        self.translated.fmt(f)
288    }
289}