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    /// The map from rustc id to translated id.
39    pub id_map: HashMap<TransItemSource, ItemId>,
40    /// The reverse map of ids.
41    pub reverse_id_map: HashMap<ItemId, TransItemSource>,
42    /// The reverse filename map.
43    pub file_to_id: HashMap<FileName, FileId>,
44
45    /// Context for tracking and reporting errors.
46    pub errors: RefCell<ErrorCtx>,
47    /// The declarations we came accross and which we haven't translated yet. We keep them sorted
48    /// to make the output order a bit more stable.
49    pub items_to_translate: BTreeSet<TransItemSource>,
50    /// The declaration we've already processed (successfully or not).
51    pub processed: HashSet<TransItemSource>,
52    /// Stack of the translations currently happening. Used to avoid accidental cycles.
53    pub translate_stack: Vec<ItemId>,
54    /// Cache the names to compute them only once each.
55    pub cached_names: HashMap<RustcItem, Name>,
56    /// Cache the `ItemMeta`s to compute them only once each.
57    pub cached_item_metas: HashMap<TransItemSource, ItemMeta>,
58}
59
60/// A translation context for items.
61/// Augments the [TranslateCtx] with type-level variables.
62pub(crate) struct ItemTransCtx<'tcx, 'ctx> {
63    /// The definition we are currently extracting.
64    pub item_src: TransItemSource,
65    /// The id of the definition we are currently extracting, if there is one.
66    pub item_id: Option<ItemId>,
67    /// The translation context containing the top-level definitions/ids.
68    pub t_ctx: &'ctx mut TranslateCtx<'tcx>,
69    /// The Hax context with the current `DefId`.
70    pub hax_state_with_id: hax::StateWithOwner<'tcx>,
71    /// Whether to consider a `ImplExprAtom::Error` as an error for us. True except inside type
72    /// aliases, because rust does not enforce correct trait bounds on type aliases.
73    pub error_on_impl_expr_error: bool,
74
75    /// The stack of generic parameter binders for the current context. Each binder introduces an
76    /// entry in this stack, with the entry as index `0` being the innermost binder. These
77    /// parameters are referenced using [`DeBruijnVar`]; see there for details.
78    pub binding_levels: BindingStack<BindingLevel>,
79}
80
81/// Translates `T` into `U` using `hax`'s `SInto` trait, catching any hax panics.
82pub fn catch_sinto<S, T, U>(
83    s: &S,
84    err: &mut ErrorCtx,
85    krate: &TranslatedCrate,
86    span: Span,
87    x: &T,
88) -> Result<U, Error>
89where
90    T: Debug + SInto<S, U>,
91{
92    let unwind_safe_s = std::panic::AssertUnwindSafe(s);
93    let unwind_safe_x = std::panic::AssertUnwindSafe(x);
94    std::panic::catch_unwind(move || unwind_safe_x.sinto(*unwind_safe_s)).or_else(|_| {
95        raise_error!(
96            err,
97            crate(krate),
98            span,
99            "Hax panicked when translating `{x:?}`."
100        )
101    })
102}
103
104impl<'tcx, 'ctx> TranslateCtx<'tcx> {
105    /// Span an error and register the error.
106    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
107        self.errors
108            .borrow_mut()
109            .span_err(&self.translated, span, msg, level)
110    }
111
112    /// Translates `T` into `U` using `hax`'s `SInto` trait, catching any hax panics.
113    pub fn catch_sinto<S, T, U>(&mut self, s: &S, span: Span, x: &T) -> Result<U, Error>
114    where
115        T: Debug + SInto<S, U>,
116    {
117        catch_sinto(s, &mut *self.errors.borrow_mut(), &self.translated, span, x)
118    }
119
120    /// Return the polymorphic definition for this item. Use with care, prefer `hax_def` whenever
121    /// possible.
122    ///
123    /// Used for computing names, for associated items, and for various checks.
124    pub fn poly_hax_def(&mut self, def_id: &hax::DefId) -> Result<Arc<hax::FullDef>, Error> {
125        self.hax_def_for_item(&RustcItem::Poly(def_id.clone()))
126    }
127
128    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
129    /// depending on user choice.
130    pub fn hax_def_for_item(&mut self, item: &RustcItem) -> Result<Arc<hax::FullDef>, Error> {
131        let def_id = item.def_id();
132        let span = self.def_span(def_id);
133        if let RustcItem::Mono(item_ref) = item
134            && item_ref.has_non_lt_param
135        {
136            raise_error!(self, span, "Item is not monomorphic: {item:?}")
137        }
138        // Hax takes care of caching the translation.
139        let unwind_safe_s = std::panic::AssertUnwindSafe(&self.hax_state);
140        std::panic::catch_unwind(move || match item {
141            RustcItem::Poly(def_id) => def_id.full_def(*unwind_safe_s),
142            RustcItem::Mono(item_ref) => item_ref.instantiated_full_def(*unwind_safe_s),
143        })
144        .or_else(|_| raise_error!(self, span, "Hax panicked when translating `{def_id:?}`."))
145    }
146
147    pub(crate) fn with_def_id<F, T>(
148        &mut self,
149        def_id: &hax::DefId,
150        item_id: Option<ItemId>,
151        f: F,
152    ) -> T
153    where
154        F: FnOnce(&mut Self) -> T,
155    {
156        let mut errors = self.errors.borrow_mut();
157        let current_def_id = mem::replace(&mut errors.def_id, item_id);
158        let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id.is_local);
159        drop(errors); // important: release the refcell "lock"
160        let ret = f(self);
161        let mut errors = self.errors.borrow_mut();
162        errors.def_id = current_def_id;
163        errors.def_id_is_local = current_def_id_is_local;
164        ret
165    }
166}
167
168impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
169    /// Create a new `ExecContext`.
170    pub(crate) fn new(
171        item_src: TransItemSource,
172        item_id: Option<ItemId>,
173        t_ctx: &'ctx mut TranslateCtx<'tcx>,
174    ) -> Self {
175        use hax::BaseState;
176        let def_id = item_src.def_id().underlying_rust_def_id();
177        let hax_state_with_id = t_ctx.hax_state.clone().with_owner_id(def_id);
178        ItemTransCtx {
179            item_src,
180            item_id,
181            t_ctx,
182            hax_state_with_id,
183            error_on_impl_expr_error: true,
184            binding_levels: Default::default(),
185        }
186    }
187
188    /// Whether to monomorphize items we encounter.
189    pub fn monomorphize(&self) -> bool {
190        matches!(self.item_src.item, RustcItem::Mono(..))
191    }
192
193    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
194        self.t_ctx.span_err(span, msg, level)
195    }
196
197    pub fn hax_state(&self) -> &hax::StateWithBase<'tcx> {
198        &self.t_ctx.hax_state
199    }
200
201    pub fn hax_state_with_id(&self) -> &hax::StateWithOwner<'tcx> {
202        &self.hax_state_with_id
203    }
204
205    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
206    /// depending on user choice.
207    pub fn hax_def(&mut self, item: &hax::ItemRef) -> Result<Arc<hax::FullDef>, Error> {
208        let item = if self.monomorphize() {
209            RustcItem::Mono(item.clone())
210        } else {
211            RustcItem::Poly(item.def_id.clone())
212        };
213        self.t_ctx.hax_def_for_item(&item)
214    }
215
216    pub(crate) fn poly_hax_def(&mut self, def_id: &hax::DefId) -> Result<Arc<hax::FullDef>, Error> {
217        self.t_ctx.poly_hax_def(def_id)
218    }
219}
220
221impl<'tcx> Deref for ItemTransCtx<'tcx, '_> {
222    type Target = TranslateCtx<'tcx>;
223    fn deref(&self) -> &Self::Target {
224        self.t_ctx
225    }
226}
227impl<'tcx> DerefMut for ItemTransCtx<'tcx, '_> {
228    fn deref_mut(&mut self) -> &mut Self::Target {
229        self.t_ctx
230    }
231}
232
233impl<'a> IntoFormatter for &'a TranslateCtx<'_> {
234    type C = FmtCtx<'a>;
235    fn into_fmt(self) -> Self::C {
236        self.translated.into_fmt()
237    }
238}
239
240impl<'a> IntoFormatter for &'a ItemTransCtx<'_, '_> {
241    type C = FmtCtx<'a>;
242    fn into_fmt(self) -> Self::C {
243        FmtCtx {
244            translated: Some(&self.t_ctx.translated),
245            generics: self.binding_levels.map_ref(|bl| Cow::Borrowed(&bl.params)),
246            locals: None,
247            indent_level: 0,
248        }
249    }
250}
251
252impl<'tcx, 'ctx> fmt::Display for TranslateCtx<'tcx> {
253    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254        self.translated.fmt(f)
255    }
256}