Skip to main content

charon_driver/translate/
translate_ctx.rs

1//! The translation contexts.
2use super::translate_crate::RustcItem;
3pub use super::translate_crate::TransItemSource;
4use super::translate_generics::{BindingLevel, LifetimeMutabilityComputer};
5use crate::frontend as front;
6use crate::frontend::SInto;
7use charon_lib::ast::*;
8use charon_lib::formatter::{FmtCtx, IntoFormatter};
9use charon_lib::ids::IndexVec;
10use charon_lib::options::TranslateOptions;
11use petgraph::graphmap::DiGraphMap;
12use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
13use rustc_middle::ty::TyCtxt;
14use rustc_span::def_id::DefId as RDefId;
15use std::borrow::Cow;
16use std::cell::RefCell;
17use std::collections::VecDeque;
18use std::fmt::Debug;
19use std::ops::{Deref, DerefMut};
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::{fmt, mem};
23
24// Re-export to avoid having to fix imports.
25pub(crate) use charon_lib::errors::{
26    DepSource, ErrorCtx, Level, error_assert, raise_error, register_error,
27};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ItemOrModuleId {
31    Item(ItemId),
32    /// A module, foreign module, or inherent impl.
33    Module(RDefId),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum ItemOrModuleKind {
38    Item(ItemKind),
39    /// A module, foreign module, or inherent impl.
40    Module,
41}
42
43impl ItemOrModuleKind {
44    pub fn from_def_kind(kind: &front::DefKind) -> Option<Self> {
45        use front::DefKind::*;
46        Some(match kind {
47            Enum | Struct | Union | TyAlias | ForeignTy | AssocTy | Closure | OpaqueTy => {
48                Self::Item(ItemKind::Type)
49            }
50            Fn | AssocFn | Ctor(_, front::CtorKind::Fn) => Self::Item(ItemKind::Fun),
51            Const | Static { .. } | AssocConst | AnonConst | PromotedConst => {
52                Self::Item(ItemKind::Global)
53            }
54            Trait | TraitAlias => Self::Item(ItemKind::TraitDecl),
55            Impl { of_trait: true } => Self::Item(ItemKind::TraitImpl),
56            Impl { of_trait: false } | Mod | ForeignMod => Self::Module,
57            _ => return None,
58        })
59    }
60
61    pub fn is_fun_decl(&self) -> bool {
62        matches!(self, Self::Item(ItemKind::Fun))
63    }
64
65    pub fn is_trait_impl(&self) -> bool {
66        matches!(self, Self::Item(ItemKind::TraitImpl))
67    }
68}
69
70// `DiGraphMap` requires ordered nodes. Rustc ids have no stable ordering across compilation
71// sessions, but ordering by their indices suffices for this graph within a single translation.
72impl Ord for ItemOrModuleId {
73    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
74        use std::cmp::Ordering;
75        match (self, other) {
76            (Self::Item(a), Self::Item(b)) => a.cmp(b),
77            (Self::Module(a), Self::Module(b)) => {
78                (a.krate.as_u32(), a.index.as_u32()).cmp(&(b.krate.as_u32(), b.index.as_u32()))
79            }
80            (Self::Item(_), Self::Module(_)) => Ordering::Less,
81            (Self::Module(_), Self::Item(_)) => Ordering::Greater,
82        }
83    }
84}
85
86impl PartialOrd for ItemOrModuleId {
87    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
88        Some(self.cmp(other))
89    }
90}
91
92impl ItemOrModuleId {
93    pub fn as_item(&self) -> Option<ItemId> {
94        match self {
95            Self::Item(id) => Some(*id),
96            Self::Module(_) => None,
97        }
98    }
99
100    pub fn expect_item<T: TryFrom<ItemId>>(&self) -> T {
101        self.as_item()
102            .expect("expected a translated item")
103            .try_into()
104            .ok()
105            .expect("unexpected item kind")
106    }
107}
108
109/// Nodes in the containment graph used to compute `ItemMeta::started_from`.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111pub enum ContainmentNode {
112    Start,
113    WholeCrate,
114    Item(ItemOrModuleId),
115    TraitMethod(TraitDeclId, TraitMethodId),
116}
117
118impl From<ItemOrModuleId> for ContainmentNode {
119    fn from(id: ItemOrModuleId) -> Self {
120        Self::Item(id)
121    }
122}
123
124impl From<ItemId> for ContainmentNode {
125    fn from(id: ItemId) -> Self {
126        Self::Item(ItemOrModuleId::Item(id))
127    }
128}
129
130/// Translation context used while translating the crate data into our representation.
131pub struct TranslateCtx<'tcx> {
132    /// The Rust compiler type context
133    pub tcx: TyCtxt<'tcx>,
134    /// Path to the toolchain root.
135    pub sysroot: PathBuf,
136    /// The frontend context
137    pub frontend_state: front::StateWithBase<'tcx>,
138
139    /// The options that control translation.
140    pub options: TranslateOptions,
141    /// The translated data.
142    pub translated: TranslatedCrate,
143
144    /// Record data for each method whether it is ever used (called or implemented) and the
145    /// `FunDeclId`s of the implementations. We use this to lazily translate methods, so that we
146    /// skip unused default methods of large traits like `Iterator`.
147    ///
148    /// The complete scheme works as follows: by default we enqueue no methods for translation.
149    /// When we find a use of a method, we mark it "used" using `mark_method_as_used`. This
150    /// enqueues all known and future impls of this method. We also mark a method as used if we
151    /// find an implementation of it in a non-opaque impl, and if the method is a required method.
152    pub method_status: IndexMap<TraitDeclId, IndexVec<TraitMethodId, MethodStatus>>,
153
154    /// The map from rustc id to translated id.
155    pub id_map: HashMap<TransItemSource<'tcx>, ItemId>,
156    /// The reverse map of ids.
157    pub reverse_id_map: HashMap<ItemId, TransItemSource<'tcx>>,
158    /// Map from rustc id to associated item id
159    pub assoc_item_id_map: HashMap<front::DefId, AssocItemId>,
160    /// The reverse filename map.
161    pub file_to_id: HashMap<FileName, FileId>,
162
163    /// Context for tracking and reporting errors.
164    pub errors: RefCell<ErrorCtx>,
165    /// The declarations we came accross and which we haven't translated yet.
166    pub items_to_translate: VecDeque<TransItemSource<'tcx>>,
167    /// The declaration we've already processed (successfully or not).
168    pub processed: HashSet<TransItemSource<'tcx>>,
169    /// While translating, record which item is "contained" by another, in the sense that
170    /// `--start-from` the parent should make the child be considered started from too. We use this
171    /// to compute `ItemMeta.started_from` at the end of translation.
172    pub containment_graph: DiGraphMap<ContainmentNode, (), rustc_hash::FxBuildHasher>,
173    /// Stack of the translations currently happening. Used to avoid accidental cycles.
174    pub translate_stack: Vec<ItemOrModuleId>,
175    /// Cache of the translated spans, as translating one is costly.
176    pub cached_spans: HashMap<rustc_span::Span, Span>,
177    /// Cache of the translated span datas.
178    pub cached_span_datas: HashMap<rustc_span::Span, meta::SpanData>,
179    /// Cache of file ids per rustc source file, to avoid recomputing file names for every span.
180    pub cached_file_ids: HashMap<rustc_span::StableSourceFileId, FileId>,
181    /// Cache the names to compute them only once each.
182    pub cached_names: HashMap<TransItemSource<'tcx>, Name>,
183    /// The functions that extern functions can link to, by symbol.
184    /// Computed lazily by `exported_fns`.
185    pub exported_fns: Option<HashMap<String, ExportedFns<'tcx>>>,
186    /// For each foreign crate we've looked at, the set of its items that are nameable from outside
187    /// it. Computed lazily by `is_exported`.
188    pub exported_foreign_items: HashMap<rustc_span::def_id::CrateNum, HashSet<RDefId>>,
189    /// Compute which lifetimes are used in a `&'a mut T`. This is a global fixpoint analysis.
190    pub lt_mutability_computer: LifetimeMutabilityComputer,
191    /// The layouts of the monomorphic instances of the type declarations, for `--collect-instantiated-layouts`.
192    pub monomorphic_layouts: SeqHashMap<TypeDeclRef, Layout>,
193    /// The `DefId`s of the intrinsics we resolved by name.
194    pub intrinsic_def_ids: HashMap<rustc_span::Symbol, RDefId>,
195}
196
197/// The functions exported under a given symbol.
198#[derive(Debug, Default, Clone)]
199pub enum ExportedFns<'tcx> {
200    #[default]
201    None,
202    Strong(rustc_middle::ty::Instance<'tcx>),
203    Weak(Vec<rustc_middle::ty::Instance<'tcx>>),
204    AllocatorShim(rustc_middle::ty::Instance<'tcx>),
205    /// More than one function was strongly exported under this name; this would be a linker
206    /// error so we don't specify them.
207    Many,
208}
209
210impl<'tcx> ExportedFns<'tcx> {
211    pub(crate) fn merge(&mut self, other: ExportedFns<'tcx>) {
212        use ExportedFns::*;
213        *self = match (std::mem::take(self), other) {
214            // this would be a link error
215            (Many, _) | (_, Many) | (Strong(_), Strong(_)) => Many,
216            // strong takes precedence
217            (strong @ Strong(_), _) | (_, strong @ Strong(_)) => strong,
218            // the linker could pick any of them, so we keep them all
219            (Weak(mut weak), Weak(other)) => {
220                weak.extend(other);
221                Weak(weak)
222            }
223            (weak @ Weak(_), None) | (None, weak @ Weak(_)) => weak,
224            (None, None) => None,
225            // impossible
226            (AllocatorShim(_), _) | (_, AllocatorShim(_)) => {
227                panic!("allocator shims are added after merging exported functions")
228            }
229        };
230    }
231}
232
233/// Tracks whether a method is used (i.e. called or (non-opaquely) implemented).
234#[derive(Debug)]
235pub enum MethodStatus {
236    Unused {
237        /// The `FunDeclId`s of the method implementations. Because the method is unused, these
238        /// items are not enqueued for translation yet. When marking the method as used we'll
239        /// enqueue them.
240        implementors: HashSet<FunDeclId>,
241    },
242    Used,
243}
244
245impl Default for MethodStatus {
246    fn default() -> Self {
247        Self::Unused {
248            implementors: Default::default(),
249        }
250    }
251}
252
253/// A translation context for items.
254/// Augments the [TranslateCtx] with type-level variables.
255pub(crate) struct ItemTransCtx<'tcx, 'ctx> {
256    /// The definition we are currently extracting.
257    pub item_src: TransItemSource<'tcx>,
258    /// The id of the definition we are currently extracting.
259    pub item_id: ItemOrModuleId,
260    /// The translation context containing the top-level definitions/ids.
261    pub t_ctx: &'ctx mut TranslateCtx<'tcx>,
262    /// The frontend context with the current `DefId`.
263    pub frontend_state: front::StateWithOwner<'tcx>,
264    /// Whether to consider a `TraitProofKind::Error` as an error for us. True except inside type
265    /// aliases, because rust does not enforce correct trait bounds on type aliases.
266    pub error_on_trait_proof_error: bool,
267
268    /// The stack of generic parameter binders for the current context. Each binder introduces an
269    /// entry in this stack, with the entry as index `0` being the innermost binder. These
270    /// parameters are referenced using [`DeBruijnVar`]; see there for details.
271    pub binding_levels: BindingStack<BindingLevel<'tcx>>,
272    /// When `Some`, translate any erased lifetime to a fresh `Region::Body` lifetime.
273    pub lifetime_freshener: Option<IndexMap<RegionId, ()>>,
274    /// With `--collect-instantiated-layouts`, we instantiate all fields of reachable monomorphic types. However
275    /// we don't want to also translate these types' layouts, as it could cause cycles (like in
276    /// `struct S<T>(Box<S<(T, T)>>)`). So when this flag is set, we stop recursing into monomorphic
277    /// layouts, to avoid that.
278    pub recording_mono_layouts: bool,
279}
280
281/// Translates `T` into `U` using `frontend`'s `SInto` trait, catching any frontend panics.
282pub fn catch_sinto<S, T, U>(
283    s: &S,
284    err: &mut ErrorCtx,
285    krate: &TranslatedCrate,
286    span: Span,
287    x: &T,
288) -> Result<U, Error>
289where
290    T: Debug + SInto<S, U>,
291{
292    let unwind_safe_s = std::panic::AssertUnwindSafe(s);
293    let unwind_safe_x = std::panic::AssertUnwindSafe(x);
294    std::panic::catch_unwind(move || unwind_safe_x.sinto(*unwind_safe_s)).or_else(|_| {
295        raise_error!(
296            err,
297            crate(krate),
298            span,
299            "The frontend panicked when translating `{x:?}`."
300        )
301    })
302}
303
304impl<'tcx> TranslateCtx<'tcx> {
305    /// Span an error and register the error.
306    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
307        self.errors
308            .borrow_mut()
309            .span_err(&self.translated, span, msg, level)
310    }
311
312    pub fn get_target_triple(&self) -> TargetTriple {
313        self.tcx.sess.opts.target_triple.tuple().to_owned()
314    }
315
316    /// Translates `T` into `U` using `frontend`'s `SInto` trait, catching any frontend panics.
317    pub fn catch_sinto<S, T, U>(&mut self, s: &S, span: Span, x: &T) -> Result<U, Error>
318    where
319        T: Debug + SInto<S, U>,
320    {
321        catch_sinto(s, &mut self.errors.borrow_mut(), &self.translated, span, x)
322    }
323
324    /// Return the polymorphic definition for this item. Use with care, prefer `frontend_def` whenever
325    /// possible.
326    ///
327    /// Used for computing names, for associated items, and for various checks.
328    pub fn poly_frontend_def(
329        &mut self,
330        def_id: &front::DefId,
331    ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
332        self.frontend_def_for_item(&TransItemSource::polymorphic(def_id))
333    }
334
335    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
336    /// depending on user choice.
337    pub fn frontend_def_for_item(
338        &mut self,
339        item: &TransItemSource<'tcx>,
340    ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
341        item.full_def(&self.frontend_state).or_else(|_| {
342            let def_id = item.def_id();
343            let span = self.def_span(def_id);
344            raise_error!(
345                self,
346                span,
347                "The frontend panicked when translating `{def_id:?}`."
348            )
349        })
350    }
351
352    pub(crate) fn with_def_id<F, T>(
353        &mut self,
354        def_id: &front::DefId,
355        item_id: &ItemOrModuleId,
356        f: F,
357    ) -> T
358    where
359        F: FnOnce(&mut Self) -> T,
360    {
361        let mut errors = self.errors.borrow_mut();
362        let current_def_id = mem::replace(&mut errors.def_id, item_id.as_item());
363        let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id.is_local());
364        drop(errors); // important: release the refcell "lock"
365        let ret = f(self);
366        let mut errors = self.errors.borrow_mut();
367        errors.def_id = current_def_id;
368        errors.def_id_is_local = current_def_id_is_local;
369        ret
370    }
371}
372
373impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
374    /// Create a new `ExecContext`.
375    pub(crate) fn new(
376        item_src: TransItemSource<'tcx>,
377        item_id: ItemOrModuleId,
378        t_ctx: &'ctx mut TranslateCtx<'tcx>,
379    ) -> Self {
380        use crate::frontend::BaseState;
381        let frontend_state_with_id = t_ctx
382            .frontend_state
383            .clone()
384            .with_frontend_owner(item_src.def_id());
385        ItemTransCtx {
386            item_src,
387            item_id,
388            t_ctx,
389            frontend_state: frontend_state_with_id,
390            error_on_trait_proof_error: true,
391            binding_levels: Default::default(),
392            lifetime_freshener: None,
393            recording_mono_layouts: false,
394        }
395    }
396
397    /// Whether to monomorphize items we encounter.
398    pub fn monomorphize(&self) -> bool {
399        matches!(
400            self.item_src.item,
401            RustcItem::Mono(..) | RustcItem::MonoTrait(..)
402        )
403    }
404
405    /// Whether to translate this particular item monomorphically.
406    pub fn should_monomorphize_item(&self, item: &front::ItemRef) -> bool {
407        // Traits and vtables use `MonoTrait` in mono mode. Other items are translated
408        // monomorphically when their arguments are concrete, even if the context is poly.
409        self.options.monomorphize_with_frontend
410            && (TransItemSource::is_for_trait(&item.def_id) || !item.mentions_non_lt_param)
411    }
412
413    pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
414        self.t_ctx.span_err(span, msg, level)
415    }
416
417    pub fn frontend_state(&self) -> &front::StateWithBase<'tcx> {
418        &self.t_ctx.frontend_state
419    }
420
421    pub fn frontend_state_with_id(&self) -> &front::StateWithOwner<'tcx> {
422        &self.frontend_state
423    }
424
425    pub fn catch_sinto<T, U>(&mut self, span: Span, x: &T) -> Result<U, Error>
426    where
427        T: Debug + SInto<front::StateWithOwner<'tcx>, U>,
428    {
429        self.t_ctx.catch_sinto(&self.frontend_state, span, x)
430    }
431
432    /// Return the definition for this item. This uses the polymorphic or monomorphic definition
433    /// depending on user choice. For traits and vtable structs, we always use polymorphic definitions.
434    pub fn frontend_def(
435        &mut self,
436        item: &front::ItemRef<'tcx>,
437    ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
438        let item = if self.monomorphize() && !TransItemSource::is_for_trait(self.item_src.def_id())
439        {
440            TransItemSource::monomorphic(item)
441        } else {
442            TransItemSource::polymorphic(&item.def_id)
443        };
444        self.frontend_def_for_item(&item)
445    }
446}
447
448impl<'tcx> Deref for ItemTransCtx<'tcx, '_> {
449    type Target = TranslateCtx<'tcx>;
450    fn deref(&self) -> &Self::Target {
451        self.t_ctx
452    }
453}
454impl<'tcx> DerefMut for ItemTransCtx<'tcx, '_> {
455    fn deref_mut(&mut self) -> &mut Self::Target {
456        self.t_ctx
457    }
458}
459
460impl<'a> IntoFormatter for &'a TranslateCtx<'_> {
461    type C = FmtCtx<'a>;
462    fn into_fmt(self) -> Self::C {
463        self.translated.into_fmt()
464    }
465}
466
467impl<'a> IntoFormatter for &'a ItemTransCtx<'_, '_> {
468    type C = FmtCtx<'a>;
469    fn into_fmt(self) -> Self::C {
470        FmtCtx {
471            generics: self.binding_levels.map_ref(|bl| Cow::Borrowed(&bl.params)),
472            ..self.t_ctx.into_fmt()
473        }
474    }
475}
476
477impl<'tcx> fmt::Display for TranslateCtx<'tcx> {
478    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479        self.translated.fmt(f)
480    }
481}