Skip to main content

charon_driver/translate/
translate_crate.rs

1//! This file governs the overall translation of items.
2//!
3//! Translation works as follows: we translate each `TransItemSource` of interest into an
4//! appropriate item. In the process of translating an item we may find more `front::DefId`s of
5//! interest; we register those as an appropriate `TransItemSource`, which will 1/ enqueue the item
6//! so that it eventually gets translated too, and 2/ return an `ItemId` we can use to refer to
7//! it.
8//!
9//! We start with the DefId of the current crate (or of anything passed to `--start-from`) and
10//! recursively translate everything we find.
11//!
12//! There's another important component at play: opacity. Each item is assigned an opacity based on
13//! its name. By default, items from the local crate are transparent and items from foreign crates
14//! are opaque (this can be controlled with `--include`, `--opaque` and `--exclude`). If an item is
15//! opaque, its signature/"outer shell" will be translated (e.g. for functions that's the
16//! signature) but not its contents.
17use itertools::Itertools;
18use petgraph::visit::{Dfs, Walker};
19use rustc_hash::{FxHashMap, FxHashSet as HashSet};
20use rustc_hir::def_id::LOCAL_CRATE;
21use rustc_middle::ty::{self, TyCtxt};
22use rustc_span::{def_id::DefId, sym};
23use std::any::Any;
24use std::cell::RefCell;
25use std::path::PathBuf;
26use std::sync::Arc;
27
28use super::translate_ctx::*;
29use crate::frontend as front;
30use crate::frontend::{BaseState, SInto};
31use charon_lib::ast::*;
32use charon_lib::name_matcher::NamePattern;
33use charon_lib::options::{CliOpts, ConstHandling, StartFrom, TranslateOptions};
34use charon_lib::transform::TransformCtx;
35
36/// The id of an untranslated item.
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38pub struct TransItemSource<'tcx> {
39    pub item: RustcItem<'tcx>,
40}
41
42/// Refers to a rustc item. Can be either the polymorphic version (`Poly`) of the item, or a
43/// monomorphization (`Mono` or `MonoTrait`) of it.
44/// For `MonoTrait` items, their kind should be either `trait decl` or `struct vtable`:
45///     1. the trait is translated as in poly mode, except that we don't translate any of its
46///        associated item lists.
47///     2. the vtable is translated with erased signature of the methods and without generic types.
48///        In other words, there is one "opaque" vtable per trait.
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub enum RustcItem<'tcx> {
51    Poly(front::DefId),
52    Mono(front::ItemRef<'tcx>),
53    MonoTrait(front::DefId),
54}
55
56impl<'tcx> TransItemSource<'tcx> {
57    pub fn new(item: RustcItem<'tcx>) -> Self {
58        if let RustcItem::Mono(item) = &item {
59            if item.mentions_non_lt_param {
60                panic!("Item is not monomorphic: {item:?}")
61            }
62        } else if let RustcItem::MonoTrait(_) = &item
63            && !TransItemSource::is_for_trait(item.def_id())
64        {
65            panic!("Item {item:?} should not be translated as monomorphic_trait")
66        }
67        Self { item }
68    }
69
70    /// Refers to the given item. Depending on `monomorphize`, this chooses between the monomorphic
71    /// and polymorphic versions of the item.
72    pub fn from_item(item: &front::ItemRef<'tcx>, monomorphize: bool) -> Self {
73        if monomorphize {
74            if TransItemSource::is_for_trait(&item.def_id) {
75                Self::monomorphic_trait(&item.def_id)
76            } else {
77                Self::monomorphic(item)
78            }
79        } else {
80            Self::polymorphic(&item.def_id)
81        }
82    }
83
84    /// Refers to the polymorphic version of this item.
85    pub fn polymorphic(def_id: &front::DefId) -> Self {
86        Self::new(RustcItem::Poly(def_id.clone()))
87    }
88
89    /// Refers to the monomorphic version of this item.
90    pub fn monomorphic(item: &front::ItemRef<'tcx>) -> Self {
91        Self::new(RustcItem::Mono(item.clone()))
92    }
93
94    /// Refers to the monomorphic trait (or vtable).
95    /// See the docs of `RustcItem::MonoTrait` for details.
96    pub fn monomorphic_trait(def_id: &front::DefId) -> Self {
97        Self::new(RustcItem::MonoTrait(def_id.clone()))
98    }
99
100    pub fn def_id(&self) -> &front::DefId {
101        self.item.def_id()
102    }
103
104    pub fn kind(&self) -> ItemOrModuleKind {
105        let def_kind = &self.def_id().kind;
106        ItemOrModuleKind::from_def_kind(def_kind)
107            .unwrap_or_else(|| panic!("Item kind {def_kind:?} cannot be translated using Charon"))
108    }
109
110    pub fn is_translatable(def_id: &front::DefId) -> bool {
111        ItemOrModuleKind::from_def_kind(&def_id.kind).is_some()
112    }
113
114    pub fn is_for_trait(def_id: &front::DefId) -> bool {
115        matches!(
116            def_id.kind,
117            front::DefKind::Trait | front::DefKind::TraitAlias
118        ) || def_id.as_derived() == Some(&front::DerivedItemKind::VTableDef)
119    }
120
121    /// For virtual items that have a parent (typically a method impl), return this parent. Does
122    /// not attempt to generally compute the parent of an item. Used to compute names.
123    pub(crate) fn naming_parent(&self, s: &impl front::BaseState<'tcx>) -> Option<Self> {
124        let derived = self.def_id().as_derived()?;
125        let mut item = self.item.peel_derived(s);
126        match derived {
127            front::DerivedItemKind::BuiltinAssocItemImpl(_)
128            | front::DerivedItemKind::DropGlueMethodDef => {
129                let parent = self.def_id().typing_parent(s)?;
130                // These items have no early params of their own so we can keep the args and refer
131                // to their parent.
132                item = self.item.with_def_id(s, &parent);
133            }
134            front::DerivedItemKind::VTableDef
135            | front::DerivedItemKind::VTableMethodShim
136            | front::DerivedItemKind::VTableImpl
137            | front::DerivedItemKind::VTableDropShim => {}
138            _ => return None,
139        }
140        Some(Self::new(item))
141    }
142
143    /// Whether this item keeps the attribute information of the underlying Rust DefId.
144    pub(crate) fn use_base_attr_info(&self) -> bool {
145        self.def_id().as_derived().is_none()
146            || matches!(
147                self.def_id().base,
148                front::DefIdBase::DerivedItem(_, front::DerivedItemKind::Initializer)
149            )
150            || (matches!(
151                self.def_id().as_derived(),
152                Some(front::DerivedItemKind::BuiltinAssocItemImpl(decl))
153                    if decl.kind == front::DefKind::AssocFn
154            ) && matches!(
155                self.def_id().peel_derived().as_derived(),
156                Some(front::DerivedItemKind::FnImpl(_))
157            ))
158    }
159
160    /// Return the frontend `FullDef` for this item.
161    pub fn full_def<S: front::BaseState<'tcx>>(
162        &self,
163        s: &S,
164    ) -> Result<Arc<front::FullDef<'tcx>>, Box<dyn Any + Send>> {
165        let _guard = charon_lib::timing::scope("frontend-full-def");
166        let unwind_safe_s = std::panic::AssertUnwindSafe(s);
167        // The frontend takes care of caching the translation.
168        std::panic::catch_unwind(move || match &self.item {
169            RustcItem::Poly(def_id) => def_id.full_def(*unwind_safe_s),
170            RustcItem::Mono(item_ref) => item_ref.instantiated_full_def(*unwind_safe_s),
171            RustcItem::MonoTrait(def_id) => def_id.full_def(*unwind_safe_s),
172        })
173    }
174}
175
176impl<'tcx> RustcItem<'tcx> {
177    pub fn def_id(&self) -> &front::DefId {
178        match self {
179            RustcItem::Poly(def_id) => def_id,
180            RustcItem::Mono(item_ref) => &item_ref.def_id,
181            RustcItem::MonoTrait(def_id) => def_id,
182        }
183    }
184
185    /// Set the `DefId`, keeping the same generic arguments and resolutions.
186    pub fn with_def_id(&self, s: &impl front::BaseState<'tcx>, def_id: &front::DefId) -> Self {
187        match self {
188            Self::Poly(_) => Self::Poly(def_id.clone()),
189            Self::Mono(item) => Self::Mono(item.with_def_id(s, def_id)),
190            Self::MonoTrait(_) => Self::MonoTrait(def_id.clone()),
191        }
192    }
193
194    /// Remove one derived-item layer.
195    pub fn peel_derived(&self, s: &impl front::BaseState<'tcx>) -> Self {
196        self.with_def_id(s, self.def_id().peel_derived())
197    }
198
199    /// Refer to the (recursive) base item.
200    pub fn derived_base(&self, s: &impl front::BaseState<'tcx>) -> Self {
201        self.with_def_id(s, self.def_id().derived_base())
202    }
203
204    /// Refer to the derived item.
205    pub fn make_derived(
206        &self,
207        s: &impl front::BaseState<'tcx>,
208        kind: front::DerivedItemKind,
209    ) -> Self {
210        self.with_def_id(s, &self.def_id().clone().make_derived(kind))
211    }
212}
213
214impl<'tcx> TranslateCtx<'tcx> {
215    /// If this is a trait method declaration, return the `DefId` of its parent trait.
216    fn as_trait_method_decl(&mut self, def_id: &front::DefId) -> Option<front::DefId> {
217        if matches!(def_id.kind, front::DefKind::AssocFn)
218            && let def = self.poly_frontend_def(def_id).ok()?
219            && let front::FullDefKind::AssocFn(f) = def.kind()
220            && let associated_item = f.associated_item()
221            && let front::AssocItemContainer::TraitContainer { trait_ref } =
222                &associated_item.container
223        {
224            Some(trait_ref.def_id.clone())
225        } else {
226            None
227        }
228    }
229
230    /// Resolve a path to a list of matching `DefId`s.
231    pub fn resolve_path(
232        &self,
233        span: Span,
234        pat: &NamePattern,
235        strict: bool,
236    ) -> Result<Vec<rustc_span::def_id::DefId>, Error> {
237        super::resolve_path::def_path_def_ids(&self.frontend_state, pat, strict).map_err(|err| {
238            register_error!(self, span, "failed to resolve item path `{pat}`: {err}")
239        })
240    }
241
242    /// Resolve a path that is expected to name exactly one item.
243    pub fn resolve_single_path(
244        &self,
245        span: Span,
246        pat: &NamePattern,
247    ) -> Result<rustc_span::def_id::DefId, Error> {
248        self.resolve_path(span, pat, true)?
249            .into_iter()
250            .exactly_one()
251            .map_err(|_| register_error!(self, span, "expected exactly one item for path `{pat}`"))
252    }
253
254    fn register_polymorphic_function(&mut self, def_id: DefId) -> FunDeclId {
255        let def_id = def_id.sinto(&self.frontend_state);
256        let item = TransItemSource::polymorphic(&def_id);
257        self.register_and_enqueue(&None, item).expect_item()
258    }
259
260    fn register_poly_function_by_path(&mut self, path: &str) -> Result<FunDeclId, Error> {
261        let path = NamePattern::parse(path).unwrap();
262        let def_id = self.resolve_single_path(Span::dummy(), &path)?;
263        Ok(self.register_polymorphic_function(def_id))
264    }
265
266    /// Register the std functions needed for `builtins_to_function_calls`.
267    fn register_builtin_functions(&mut self) -> Result<(), Error> {
268        if self.options.reconstruct_asserts {
269            self.register_poly_function_by_path("core::hint::unreachable_unchecked")?;
270        }
271        if self.options.ops_to_function_calls {
272            self.register_poly_function_by_path("array::as_slice")?;
273            self.register_poly_function_by_path("array::as_mut_slice")?;
274            self.register_poly_function_by_path("core::array::repeat")?;
275        }
276        if self.options.index_to_function_calls {
277            let tcx = self.tcx;
278            for (trait_id, method_name) in [
279                (tcx.lang_items().index_trait().unwrap(), sym::index),
280                (tcx.lang_items().index_mut_trait().unwrap(), sym::index_mut),
281            ] {
282                let impls = tcx.all_impls(trait_id).filter(|&impl_id| {
283                    matches!(
284                        tcx.impl_trait_ref(impl_id).skip_binder().self_ty().kind(),
285                        ty::Array(..) | ty::Slice(..)
286                    )
287                });
288                for impl_id in impls {
289                    let method_id = tcx
290                        .associated_items(impl_id)
291                        .in_definition_order()
292                        .find(|item| item.name() == method_name)
293                        .unwrap()
294                        .def_id;
295                    self.register_polymorphic_function(method_id);
296                }
297            }
298            let trait_id = self.tcx.get_diagnostic_item(sym::SliceIndex).unwrap();
299            let impls = self.tcx.all_impls(trait_id).filter(|&impl_id| {
300                let trait_ref = tcx.impl_trait_ref(impl_id).skip_binder();
301                trait_ref.args.type_at(1).is_slice()
302                    && match trait_ref.self_ty().kind() {
303                        ty::Uint(ty::UintTy::Usize) => true,
304                        ty::Adt(def, args) => {
305                            tcx.is_lang_item(def.did(), rustc_attr_ir::LangItem::Range)
306                                && args.type_at(0) == tcx.types.usize
307                        }
308                        _ => false,
309                    }
310            });
311            for impl_id in impls {
312                let methods = tcx
313                    .associated_items(impl_id)
314                    .in_definition_order()
315                    .filter(|item| item.name() == sym::index || item.name() == sym::index_mut)
316                    .map(|item| item.def_id);
317                for method_id in methods {
318                    self.register_polymorphic_function(method_id);
319                }
320            }
321        }
322        Ok(())
323    }
324
325    /// List all the items of the crate and its dependencies. For the local crate,
326    /// only visits HIR-backed items (i.e. skips synthetic ones).
327    fn all_items(&self) -> impl Iterator<Item = DefId> + use<'tcx> {
328        let tcx = self.tcx;
329        let dep_items = tcx
330            .crates(())
331            .iter()
332            .copied()
333            .filter(move |&cnum| !tcx.crate_dep_kind(cnum).macros_only())
334            .flat_map(move |krate| {
335                (0..tcx.num_extern_def_ids(krate)).map(move |index| DefId {
336                    krate,
337                    index: rustc_span::def_id::DefIndex::from_usize(index),
338                })
339            });
340        tcx.hir_crate_items(())
341            .definitions()
342            .map(|ldid| ldid.to_def_id())
343            .chain(dep_items)
344    }
345
346    /// The functions exported under `symbol`.
347    pub(crate) fn exported_fns(&mut self, symbol: &str) -> ExportedFns<'tcx> {
348        use rustc_ast::expand::allocator::*;
349        use rustc_attr_ir::Linkage;
350        use rustc_hir::def::DefKind;
351        use rustc_middle::middle::exported_symbols::ExportedSymbol;
352        use rustc_symbol_mangling::mangle_internal_symbol;
353        let tcx = self.tcx;
354        let exported_fns = self.exported_fns.get_or_insert_with(|| {
355            let local = tcx
356                .hir_crate_items(())
357                .definitions()
358                .map(|ldid| ldid.to_def_id());
359            let dependencies = tcx
360                .crates(())
361                .iter()
362                .filter(|&&cnum| !tcx.crate_dep_kind(cnum).macros_only())
363                .filter(|&&cnum| {
364                    !tcx.is_panic_runtime(cnum)
365                        || tcx.required_panic_strategy(cnum) == Some(tcx.sess.panic_strategy())
366                })
367                .flat_map(|&cnum| tcx.exported_non_generic_symbols(cnum))
368                .filter_map(|(symbol, _)| match symbol {
369                    ExportedSymbol::NonGeneric(def_id) => Some(*def_id),
370                    _ => None,
371                });
372            let candidates = local
373                .chain(dependencies)
374                .filter(|&def_id| matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn))
375                .filter(|&def_id| !tcx.generics_of(def_id).requires_monomorphization(tcx))
376                .filter(|&def_id| tcx.codegen_fn_attrs(def_id).contains_extern_indicator());
377            let mut exported_fns = FxHashMap::<String, ExportedFns>::default();
378            for def_id in candidates {
379                let instance = rustc_middle::ty::Instance::mono(tcx, def_id);
380                let new = match tcx.codegen_fn_attrs(def_id).linkage {
381                    None | Some(Linkage::External) => ExportedFns::Strong(instance),
382                    Some(Linkage::WeakAny | Linkage::WeakODR) => ExportedFns::Weak(vec![instance]),
383                    _ => continue,
384                };
385                let symbol = tcx.symbol_name(instance).name.to_string();
386                exported_fns.entry(symbol).or_default().merge(new);
387            }
388
389            // Manually link the std allocator functions, which rustc willl generate.
390            let shimmed_fns = ALLOCATOR_METHODS
391                .iter()
392                .map(|method| method.name)
393                .chain([ALLOC_ERROR_HANDLER]);
394            for name in shimmed_fns {
395                let global_fn = mangle_internal_symbol(tcx, &global_fn_name(name));
396                let default_fn = mangle_internal_symbol(tcx, &default_fn_name(name));
397                // We only link them if no `#[global_allocator]`/`#[alloc_error_handler]` has
398                // already defined them! In which case rust gives them a custom shim that needs
399                // special-casing.
400                if !exported_fns.contains_key(&global_fn)
401                    && let Some(&ExportedFns::Strong(instance)) = exported_fns.get(&default_fn)
402                {
403                    exported_fns.insert(global_fn, ExportedFns::AllocatorShim(instance));
404                }
405            }
406
407            exported_fns
408        });
409        exported_fns.get(symbol).cloned().unwrap_or_default()
410    }
411
412    /// Add this item to the queue of items to translate. Each translated item will then
413    /// recursively register the items it refers to. We call this on the crate root and end up
414    /// exploring the whole crate.
415    #[tracing::instrument(skip(self))]
416    pub fn enqueue_module_item(
417        &mut self,
418        def_id: &front::DefId,
419        // Item that contains this one.
420        parent: ContainmentNode,
421    ) -> Option<ItemOrModuleId> {
422        if !TransItemSource::is_translatable(def_id) {
423            return None;
424        }
425        if let Some(trait_def_id) = self.as_trait_method_decl(def_id) {
426            // Selecting a method also selects its containing trait. Mark the method used so
427            // its default body is enqueued even if the trait is opaque.
428            let trait_item_id = self.enqueue_module_item(&trait_def_id, parent)?;
429            let trait_id = trait_item_id.expect_item();
430            let method_id = self.translate_trait_method_id(trait_id, def_id).ok()?;
431            self.record_containment(parent, ContainmentNode::TraitMethod(trait_id, method_id));
432            return Some(trait_item_id);
433        }
434        let item_src = if self.options.monomorphize_with_frontend {
435            let s = self.frontend_state.with_frontend_owner(def_id);
436            if !def_id.has_generics(&s) {
437                // Monomorphize this item and the items it depends on.
438                let item = front::ItemRef::identity(&s, def_id.clone());
439                TransItemSource::monomorphic(&item)
440            } else {
441                // Skip polymorphic items.
442                return None;
443            }
444        } else {
445            TransItemSource::polymorphic(def_id)
446        };
447        let id = self.register_and_enqueue(&None, item_src);
448        self.record_containment(parent, id);
449        Some(id)
450    }
451
452    /// Record that the parent contains the child, for the purposes of computing which items are
453    /// included in the "started from" set.
454    pub(crate) fn record_containment(
455        &mut self,
456        parent: impl Into<ContainmentNode>,
457        child: impl Into<ContainmentNode>,
458    ) {
459        self.containment_graph
460            .add_edge(parent.into(), child.into(), ());
461    }
462
463    /// Use the computed `containment_graph` to deduce which items should be considered as being
464    /// targeted by `--start-from`, which then affects which items are used to compute used
465    /// declarations.
466    fn compute_started_from(&mut self) {
467        let reachable: HashSet<_> = Dfs::new(&self.containment_graph, ContainmentNode::Start)
468            .iter(&self.containment_graph)
469            .collect();
470        for node in &reachable {
471            if let ContainmentNode::Item(ItemOrModuleId::Item(id)) = node
472                && let Some(mut item) = self.translated.get_item_mut(*id)
473            {
474                item.item_meta().started_from = true;
475            }
476        }
477        // Trait declarations also store method metadata.
478        for tdecl in self.translated.trait_decls.iter_mut() {
479            for (method_id, method) in tdecl.methods.iter_mut_indexed() {
480                let node = ContainmentNode::TraitMethod(tdecl.def_id, method_id);
481                method.skip_binder.item_meta.started_from = reachable.contains(&node);
482            }
483        }
484    }
485
486    /// Whether this item is polymorphic, while we are in monomorphic mode.
487    pub(crate) fn is_poly_in_mono(&self, item_src: &TransItemSource) -> bool {
488        self.options.monomorphize_with_frontend && matches!(item_src.item, RustcItem::Poly(..))
489    }
490
491    pub(crate) fn register_no_enqueue(
492        &mut self,
493        dep_src: &Option<DepSource>,
494        src: &TransItemSource<'tcx>,
495    ) -> ItemOrModuleId {
496        let item_id = match self.id_map.get(src) {
497            Some(tid) => *tid,
498            None => {
499                use ItemKind::*;
500                use ItemOrModuleKind::*;
501                let trans_id: ItemId = match src.kind() {
502                    Item(Type) => self.translated.type_decls.reserve_slot().into(),
503                    Item(TraitDecl) => self.translated.trait_decls.reserve_slot().into(),
504                    Item(TraitImpl) => self.translated.trait_impls.reserve_slot().into(),
505                    Item(Global) => self.translated.global_decls.reserve_slot().into(),
506                    Item(Fun) => self.translated.fun_decls.reserve_slot().into(),
507                    Module => return ItemOrModuleId::Module(src.def_id().real_rust_def_id()),
508                };
509                // Add the id to the queue of declarations to translate
510                self.id_map.insert(src.clone(), trans_id);
511                self.reverse_id_map.insert(trans_id, src.clone());
512                // Store the name early so the name matcher can identify paths.
513                if let Ok(name) = self.translate_name(src) {
514                    self.translated.item_names.insert(trans_id, name);
515                }
516                trans_id
517            }
518        };
519        self.errors
520            .borrow_mut()
521            .register_dep_source(dep_src, item_id, src.def_id().is_local());
522        ItemOrModuleId::Item(item_id)
523    }
524
525    /// Register this item source and enqueue it for translation.
526    pub(crate) fn register_and_enqueue(
527        &mut self,
528        dep_src: &Option<DepSource>,
529        item_src: TransItemSource<'tcx>,
530    ) -> ItemOrModuleId {
531        let id = self.register_no_enqueue(dep_src, &item_src);
532        self.items_to_translate.push_back(item_src);
533        id
534    }
535
536    /// Enqueue an item from its id.
537    pub(crate) fn enqueue_id(&mut self, id: impl Into<ItemId>) {
538        let id = id.into();
539        if self.translated.get_item(id).is_none() {
540            let item_src = self.reverse_id_map[&id].clone();
541            self.items_to_translate.push_back(item_src);
542        }
543    }
544
545    /// Register the associated types of this trait.
546    pub fn register_assoc_items(
547        &mut self,
548        trait_def_id: &front::DefId,
549        trait_id: TraitDeclId,
550    ) -> Result<(), Error> {
551        if self.method_status.get(trait_id).is_some() {
552            return Ok(());
553        }
554        let trait_def = self.poly_frontend_def(trait_def_id)?;
555        let t = trait_def.kind().as_trait().unwrap();
556        let names = self
557            .translated
558            .assoc_item_names
559            .get_or_insert_with(trait_id, Default::default);
560        for item in t.items(&self.frontend_state) {
561            let name = TraitItemName(
562                item.name
563                    .as_ref()
564                    .map(|n| n.to_string().into())
565                    .unwrap_or_default(),
566            );
567            let id: AssocItemId = match item.kind {
568                front::AssocKind::Type { .. } => names.types.push(name).into(),
569                front::AssocKind::Fn { .. } => names.methods.push(name).into(),
570                front::AssocKind::Const { .. } => names.consts.push(name).into(),
571            };
572            self.assoc_item_id_map.insert(item.def_id.clone(), id);
573        }
574        self.method_status.get_or_insert_with(trait_id, || {
575            names.methods.map_ref(|_| MethodStatus::default())
576        });
577        Ok(())
578    }
579
580    /// Get the unique per-trait id corresponding to this associated item. The `DefId` can be of an
581    /// item declaration or item implementation.
582    pub fn translate_assoc_item_id(
583        &mut self,
584        trait_id: TraitDeclId,
585        item_def_id: &front::DefId,
586    ) -> Result<AssocItemId, Error> {
587        // The same assoc item `DefId` could belong to several `TraitDeclId`s because of
588        // monomorphization, so we only return the item id if we know this trait's data is
589        // initialized.
590        if let Some(&item_id) = self.assoc_item_id_map.get(item_def_id)
591            && self.method_status.get(trait_id).is_some()
592        {
593            return Ok(item_id);
594        }
595
596        let item_def = self.poly_frontend_def(item_def_id)?;
597        let assoc = item_def
598            .associated_item()
599            .expect("expected an associated item");
600        let decl_def_id = assoc.implemented_trait_item_id();
601
602        if decl_def_id != item_def_id
603            && let Some(&item_id) = self.assoc_item_id_map.get(decl_def_id)
604            && self.method_status.get(trait_id).is_some()
605        {
606            self.assoc_item_id_map.insert(item_def_id.clone(), item_id);
607            return Ok(item_id);
608        }
609
610        self.register_assoc_items(assoc.trait_def_id(), trait_id)?;
611        let item_id = *self.assoc_item_id_map.get(decl_def_id).unwrap();
612        Ok(item_id)
613    }
614
615    /// Register a trait method and return its `TraitMethodId`. This id is unique per trait.
616    /// This does not make the method be considered "used"; use `mark_method_as_used` for that.
617    pub fn translate_trait_method_id_no_enqueue(
618        &mut self,
619        trait_id: TraitDeclId,
620        def_id: &front::DefId,
621    ) -> Result<TraitMethodId, Error> {
622        let item_id = self.translate_assoc_item_id(trait_id, def_id)?;
623        Ok(*item_id.as_method().unwrap())
624    }
625    /// Register a trait method and return its `TraitMethodId`. This id is unique per trait.
626    /// This makes the method be considered "used".
627    pub fn translate_trait_method_id(
628        &mut self,
629        trait_id: TraitDeclId,
630        def_id: &front::DefId,
631    ) -> Result<TraitMethodId, Error> {
632        let method_id = self.translate_trait_method_id_no_enqueue(trait_id, def_id)?;
633        self.mark_method_as_used(trait_id, method_id);
634        Ok(method_id)
635    }
636    /// Register a trait associated type and return its `AssocTypeId`. This id is unique per trait.
637    pub fn translate_assoc_type_id(
638        &mut self,
639        trait_id: TraitDeclId,
640        def_id: &front::DefId,
641    ) -> Result<AssocTypeId, Error> {
642        let item_id = self.translate_assoc_item_id(trait_id, def_id)?;
643        Ok(*item_id.as_type().unwrap())
644    }
645    /// Register a trait associated const and return its `AssocTypeId`. This id is unique per trait.
646    pub fn translate_assoc_const_id(
647        &mut self,
648        trait_id: TraitDeclId,
649        def_id: &front::DefId,
650    ) -> Result<AssocConstId, Error> {
651        let item_id = self.translate_assoc_item_id(trait_id, def_id)?;
652        Ok(*item_id.as_const().unwrap())
653    }
654
655    /// Claim the first type id for the declaration of the unit type.
656    pub(crate) fn reserve_unit_decl(&mut self) {
657        let def_id =
658            front::DefId::make_synthetic(&self.frontend_state, front::SyntheticItem::Tuple(0));
659        let item_src = if self.options.monomorphize_with_frontend
660            && let Ok(def) = self.poly_frontend_def(&def_id)
661        {
662            TransItemSource::monomorphic(def.this())
663        } else {
664            TransItemSource::polymorphic(&def_id)
665        };
666        let id = if self.options.no_gen_tuple_structs {
667            self.register_and_enqueue(&None, item_src)
668        } else {
669            self.register_no_enqueue(&None, &item_src)
670        };
671        assert_eq!(
672            id,
673            ItemOrModuleId::Item(TypeDeclId::UNIT.into()),
674            "the unit type must come first"
675        );
676    }
677
678    pub(crate) fn register_target_info(&mut self) {
679        let target_data = &self.tcx.data_layout;
680        let triple = self.get_target_triple();
681
682        let mut primitive_alignments = SeqHashMap::default();
683        primitive_alignments.insert(ScalarTy::Bool, rustc_abi::Align::ONE.bytes());
684        for (ty, alignment) in [
685            (IntegerTy::Signed(IntTy::I8), rustc_abi::Align::ONE.bytes()),
686            (IntegerTy::Signed(IntTy::I16), target_data.i16_align.bytes()),
687            (IntegerTy::Signed(IntTy::I32), target_data.i32_align.bytes()),
688            (IntegerTy::Signed(IntTy::I64), target_data.i64_align.bytes()),
689            (
690                IntegerTy::Signed(IntTy::I128),
691                target_data.i128_align.bytes(),
692            ),
693            (
694                IntegerTy::Signed(IntTy::Isize),
695                target_data.pointer_align().bytes(),
696            ),
697            (
698                IntegerTy::Unsigned(UIntTy::U8),
699                rustc_abi::Align::ONE.bytes(),
700            ),
701            (
702                IntegerTy::Unsigned(UIntTy::U16),
703                target_data.i16_align.bytes(),
704            ),
705            (
706                IntegerTy::Unsigned(UIntTy::U32),
707                target_data.i32_align.bytes(),
708            ),
709            (
710                IntegerTy::Unsigned(UIntTy::U64),
711                target_data.i64_align.bytes(),
712            ),
713            (
714                IntegerTy::Unsigned(UIntTy::U128),
715                target_data.i128_align.bytes(),
716            ),
717            (
718                IntegerTy::Unsigned(UIntTy::Usize),
719                target_data.pointer_align().bytes(),
720            ),
721        ] {
722            primitive_alignments.insert(ScalarTy::Integer(ty), alignment);
723        }
724        primitive_alignments.insert(ScalarTy::Float(FloatTy::F16), target_data.f16_align.bytes());
725        primitive_alignments.insert(ScalarTy::Float(FloatTy::F32), target_data.f32_align.bytes());
726        primitive_alignments.insert(ScalarTy::Float(FloatTy::F64), target_data.f64_align.bytes());
727        primitive_alignments.insert(
728            ScalarTy::Float(FloatTy::F128),
729            target_data.f128_align.bytes(),
730        );
731        // INFO: This is not explicitly guaranteed by the reference, but by the implementation of rustc.
732        // https://doc.rust-lang.org/1.97.1/nightly-rustc/src/rustc_ty_utils/layout.rs.html#391
733        primitive_alignments.insert(ScalarTy::Char, target_data.i32_align.bytes());
734
735        let c_enum_smallest_repr_ty = match target_data.c_enum_min_size {
736            rustc_abi::Integer::I8 => IntTy::I8,
737            rustc_abi::Integer::I16 => IntTy::I16,
738            rustc_abi::Integer::I32 => IntTy::I32,
739            rustc_abi::Integer::I64 => IntTy::I64,
740            rustc_abi::Integer::I128 => IntTy::I128,
741        };
742
743        let target = &self.tcx.sess.target;
744        let info = TargetInfo {
745            arch: self
746                .translate_rustc_arch(&target.arch)
747                .expect("all rustc Arch variants should be translated"),
748            vendor: target.vendor_symbol().to_string(),
749            os: self
750                .translate_rustc_os(&target.os)
751                .expect("all rustc Os variants should be translated"),
752            env: self
753                .translate_rustc_env(&target.env)
754                .expect("all rustc Env variants should be translated"),
755            cfg_abi: self
756                .translate_rustc_cfg_abi(&target.cfg_abi)
757                .expect("all rustc CfgAbi variants should be translated"),
758            families: target.families.iter().map(|f| f.to_string()).collect(),
759            binary_format: self
760                .translate_rustc_binary_format(&target.binary_format)
761                .expect("all rustc BinaryFormat variants should be translated"),
762            panic_strategy: self
763                .translate_rustc_panic_strategy(&self.tcx.sess.panic_strategy())
764                .expect("all rustc PanicStrategy variants should be translated"),
765            target_pointer_size: target_data.pointer_size().bytes(),
766            is_little_endian: matches!(target_data.endian, rustc_abi::Endian::Little),
767            c_enum_smallest_repr_ty,
768            primitive_alignments,
769        };
770        self.translated.target_information.insert(triple, info);
771    }
772}
773
774// Id and item reference registration.
775impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
776    pub(crate) fn make_dep_source(&self, span: Span) -> Option<DepSource> {
777        Some(DepSource {
778            src_id: self.item_id.as_item()?,
779            span: self.item_src.def_id().is_local().then_some(span),
780        })
781    }
782
783    /// Register this item source and enqueue it for translation.
784    pub(crate) fn register_and_enqueue<T: TryFrom<ItemId>>(
785        &mut self,
786        span: Span,
787        item_src: TransItemSource<'tcx>,
788    ) -> T {
789        let dep_src = self.make_dep_source(span);
790        self.t_ctx
791            .register_and_enqueue(&dep_src, item_src)
792            .expect_item()
793    }
794
795    pub(crate) fn register_no_enqueue<T: TryFrom<ItemId>>(
796        &mut self,
797        span: Span,
798        src: &TransItemSource<'tcx>,
799    ) -> T {
800        let dep_src = self.make_dep_source(span);
801        self.t_ctx.register_no_enqueue(&dep_src, src).expect_item()
802    }
803
804    /// Register this item and maybe enqueue it for translation.
805    pub(crate) fn register_item_maybe_enqueue<T: TryFrom<ItemId>>(
806        &mut self,
807        span: Span,
808        enqueue: bool,
809        item: &front::ItemRef<'tcx>,
810    ) -> T {
811        let mono = self.should_monomorphize_item(item);
812        let item = if mono {
813            item.erase(self.frontend_state_with_id())
814        } else {
815            item.clone()
816        };
817        let item_src = TransItemSource::from_item(&item, mono);
818        if enqueue {
819            self.register_and_enqueue(span, item_src)
820        } else {
821            self.register_no_enqueue(span, &item_src)
822        }
823    }
824
825    /// Register this item and enqueue it for translation.
826    pub(crate) fn register_item<T: TryFrom<ItemId>>(
827        &mut self,
828        span: Span,
829        item: &front::ItemRef<'tcx>,
830    ) -> T {
831        self.register_item_maybe_enqueue(span, true, item)
832    }
833
834    /// Register this item without enqueueing it for translation.
835    #[expect(dead_code)]
836    pub(crate) fn register_item_no_enqueue<T: TryFrom<ItemId>>(
837        &mut self,
838        span: Span,
839        item: &front::ItemRef<'tcx>,
840    ) -> T {
841        self.register_item_maybe_enqueue(span, false, item)
842    }
843
844    /// Register this item and maybe enqueue it for translation.
845    pub(crate) fn translate_item_maybe_enqueue<T: TryFrom<DeclRef<ItemId>>>(
846        &mut self,
847        span: Span,
848        frontend_item: &front::ItemRef<'tcx>,
849        enqueue: bool,
850    ) -> Result<T, Error> {
851        if frontend_item.may_be_further_specialized {
852            register_error!(
853                self,
854                span,
855                "`{:?}` may be overridden by a more specialized impl depending on how generics are \
856                instantiated; translating it as is",
857                frontend_item.def_id
858            );
859        }
860
861        let id: ItemId = self.register_item_maybe_enqueue(span, enqueue, frontend_item);
862        // In mono mode, we keep trait decls generic.
863        let mut generics = if self.should_monomorphize_item(frontend_item)
864            && !matches!(
865                frontend_item.def_id.kind,
866                front::DefKind::Trait | front::DefKind::TraitAlias
867            ) {
868            GenericArgs::empty()
869        } else {
870            self.translate_generic_args(span, frontend_item)?
871        };
872
873        // Recover regions that rustc normally erases.
874        let regions = self.recover_extra_early_regions(span, frontend_item)?;
875        generics.regions.extend(regions);
876
877        // Add late bound regions as well. Only some items can have late regions: functions
878        // natively have them, and items based on functions/closures inherit them.
879        // The item args match the item params we set up in `translate_item_generics`.
880        if matches!(
881            frontend_item.def_id.kind,
882            front::DefKind::Fn | front::DefKind::AssocFn | front::DefKind::Closure
883        ) || matches!(
884            frontend_item.def_id.derived_base().kind,
885            front::DefKind::Fn
886                | front::DefKind::FnPtr
887                | front::DefKind::AssocFn
888                | front::DefKind::Closure
889                | front::DefKind::Ctor(..)
890        ) {
891            let def = self.frontend_def(frontend_item)?;
892            if let Some(param_env) = def.param_env()
893                && let Some(late_bound) = &param_env.late_bound
894            {
895                generics.regions.extend(
896                    late_bound
897                        .binder
898                        .bound_vars
899                        .iter()
900                        .map(|_| self.translate_erased_region()),
901                );
902            }
903            // If we're in the process of translating this same base item, we can reuse the
904            // generics they have in common.
905            if self.item_src.def_id().derived_base() == frontend_item.def_id.derived_base() {
906                let depth = self.binding_levels.depth();
907                for (a, b) in generics.regions.iter_mut().zip(
908                    self.outermost_binder()
909                        .params
910                        .identity_args_at_depth(depth)
911                        .regions,
912                ) {
913                    *a = b;
914                }
915            }
916        }
917
918        if frontend_item.def_id.as_derived() == Some(&front::DerivedItemKind::VTableDef) {
919            // Remove the `Self` type variable from the generic parameters.
920            generics.types.remove_and_shift_ids(TypeVarId::ZERO);
921            if !self.monomorphize() {
922                // The vtable type also takes associated types as parameters.
923                let tref = frontend_item.peel_derived(self.frontend_state());
924                let assoc_tys: Vec<_> = tref
925                    .trait_associated_types(self.frontend_state_with_id())
926                    .iter()
927                    .map(|ty| self.translate_ty(span, ty))
928                    .try_collect()?;
929                generics.types.extend(assoc_tys);
930            }
931        }
932
933        let trait_ref = frontend_item
934            .in_trait
935            .as_ref()
936            .map(|trait_proof| self.translate_trait_proof(span, trait_proof))
937            .transpose()?
938            .map(PolyTraitRef::erase);
939
940        let item = DeclRef {
941            id,
942            generics: Box::new(generics),
943            trait_ref,
944        };
945        Ok(item.try_into().ok().unwrap())
946    }
947
948    /// Register this item and enqueue it for translation.
949    ///
950    /// Note: for `FnPtr`s use `translate_fn_ptr` instead, as this handles late-bound variables
951    /// correctly. For `TypeDeclRef`s use `translate_type_decl_ref` instead, as this correctly
952    /// recognizes built-in ADTs.
953    pub(crate) fn translate_item<T: TryFrom<DeclRef<ItemId>>>(
954        &mut self,
955        span: Span,
956        item: &front::ItemRef<'tcx>,
957    ) -> Result<T, Error> {
958        self.translate_item_maybe_enqueue(span, item, true)
959    }
960
961    /// Translate a type def id
962    pub(crate) fn translate_type_decl_ref(
963        &mut self,
964        span: Span,
965        item: &front::ItemRef<'tcx>,
966    ) -> Result<TypeDeclRef, Error> {
967        self.translate_type_decl_ref_maybe_enqueue(span, item, true)
968    }
969
970    /// Register a type item and maybe enqueue it for translation. Use this to
971    /// obtain a `TypeDeclRef`, don't construct one manually.
972    pub(crate) fn translate_type_decl_ref_maybe_enqueue(
973        &mut self,
974        span: Span,
975        item: &front::ItemRef<'tcx>,
976        enqueue: bool,
977    ) -> Result<TypeDeclRef, Error> {
978        let builtin = self.recognize_builtin_adt(item);
979        if builtin == Some(BuiltinAdt::Tuple) && self.t_ctx.options.no_gen_tuple_structs {
980            // The declaration has no clauses, so we drop the `Sized` proofs of the fields.
981            let generics = self.translate_generic_args_without_trait_refs(span, item)?;
982            return Ok(TypeDeclRef {
983                id: TypeDeclId::UNIT,
984                generics: Box::new(generics),
985                builtin,
986            });
987        }
988        let item_ref: DeclRef<ItemId> = self.translate_item_maybe_enqueue(span, item, enqueue)?;
989        assert!(item_ref.trait_ref.is_none());
990        Ok(TypeDeclRef {
991            id: item_ref.id.try_into().unwrap(),
992            generics: item_ref.generics,
993            builtin,
994        })
995    }
996
997    /// In mono mode, we need to resolve all method calls directly to the implemented method;
998    /// generated methods don't have their own DefId however, so normal trait resolution will
999    /// not resolve them. We do this resolution here instead.
1000    // FIXME: resolve virtual methods in the frontend
1001    fn try_resolve_generated_method_ref(
1002        &mut self,
1003        span: Span,
1004        item: &front::ItemRef<'tcx>,
1005    ) -> Result<Option<RegionBinder<FnPtr>>, Error> {
1006        if self.monomorphize()
1007            && let Some(in_trait) = &item.in_trait
1008            && let Some((_, method_item)) = self.recognize_generated_impl_proof(in_trait)
1009            && let def = self.frontend_def(item)?
1010            && let front::FullDefKind::AssocFn(f) = def.kind()
1011            && !f.associated_item().has_value
1012        {
1013            let fn_ref: FunDeclRef = self.translate_item(span, &method_item)?;
1014            let late_bound = f.param_env().late_bound.as_ref().unwrap();
1015            self.translate_region_binder(span, &late_bound.binder, |ctx, _| {
1016                let mut generics = fn_ref.generics.move_under_binder();
1017                // The method's late-bound regions are the last regions of the generated method.
1018                generics.set_trailing_regions_to_identity(&ctx.innermost_binder().params);
1019                Ok(FnPtr::new(FnPtrKind::Fun(fn_ref.id), generics))
1020            })
1021            .map(Some)
1022        } else {
1023            Ok(None)
1024        }
1025    }
1026
1027    /// Translate a reference to a trait method declaration without registering the declaration as
1028    /// a `FunDecl`. `TraitDecl.methods` contains the declaration signature and metadata; only
1029    /// default implementations give rise to a real function item.
1030    fn translate_method_decl_fn_ptr(
1031        &mut self,
1032        span: Span,
1033        item: &front::ItemRef<'tcx>,
1034    ) -> Result<Option<RegionBinder<FnPtr>>, Error> {
1035        let Some(in_trait) = &item.in_trait else {
1036            return Ok(None);
1037        };
1038        let def = self.frontend_def(item)?;
1039        let front::FullDefKind::AssocFn(f) = def.kind() else {
1040            return Ok(None);
1041        };
1042        if !matches!(
1043            &f.associated_item().container,
1044            front::AssocItemContainer::TraitContainer { .. }
1045        ) {
1046            return Ok(None);
1047        }
1048
1049        let trait_ref = self.translate_trait_proof(span, in_trait)?.erase();
1050        let generics = self.translate_generic_args(span, item)?;
1051        let late_bound = f.param_env().late_bound.as_ref().unwrap();
1052        self.translate_region_binder(span, &late_bound.binder, |ctx, _| {
1053            let method_id = ctx.translate_trait_method_id(trait_ref.trait_id(), &item.def_id)?;
1054            let fn_kind = FnPtrKind::Trait(trait_ref.move_under_binder(), method_id);
1055            let generics = generics.move_under_binder();
1056            let generics = generics.concat(&ctx.innermost_binder().params.identity_args());
1057            Ok(FnPtr::new(fn_kind, generics))
1058        })
1059        .map(Some)
1060    }
1061
1062    /// Translate a function reference, assuming that the late-bound regions are in scope. Prefer
1063    /// the `translate_bound_fn_ptr*` methods whenever sensible.
1064    #[tracing::instrument(skip(self, span))]
1065    pub(crate) fn translate_unbound_fn_ptr_maybe_enqueue(
1066        &mut self,
1067        span: Span,
1068        item: &front::ItemRef<'tcx>,
1069        enqueue: bool,
1070    ) -> Result<FnPtr, Error> {
1071        let fun_item: DeclRef<ItemId> = self.translate_item_maybe_enqueue(span, item, enqueue)?;
1072        let fun_item: DeclRef<FunDeclId> = fun_item.try_convert_id().unwrap();
1073        let fun_id = match fun_item.trait_ref {
1074            // Direct function call
1075            None => FnPtrKind::Fun(fun_item.id),
1076            // Trait method
1077            Some(trait_ref) => {
1078                let trait_decl_id = trait_ref.trait_id();
1079                let method_id = self.translate_trait_method_id(trait_decl_id, &item.def_id)?;
1080                FnPtrKind::Trait(trait_ref, method_id)
1081            }
1082        };
1083        let mut generics = fun_item.generics;
1084        // The last n regions are the late-bound ones and were provided as erased regions by
1085        // `translate_item`.
1086        generics.set_trailing_regions_to_identity(&self.innermost_binder().params);
1087        Ok(FnPtr::new(fun_id, generics))
1088    }
1089
1090    #[tracing::instrument(skip(self, span))]
1091    pub(crate) fn translate_bound_fn_ptr_maybe_enqueue(
1092        &mut self,
1093        span: Span,
1094        item: &front::ItemRef<'tcx>,
1095        enqueue: bool,
1096    ) -> Result<RegionBinder<FnPtr>, Error> {
1097        if let Some(fn_ptr) = self.try_resolve_generated_method_ref(span, item)? {
1098            return Ok(fn_ptr);
1099        }
1100        if let Some(fn_ptr) = self.translate_method_decl_fn_ptr(span, item)? {
1101            return Ok(fn_ptr);
1102        }
1103
1104        let def = self.frontend_def(item)?;
1105        // The late-bound lifetimes of closures are treated separately.
1106        let late_bound = if let Some(param_env) = def.param_env()
1107            && let Some(late_bound) = &param_env.late_bound
1108            && !matches!(def.kind(), front::FullDefKind::Closure(_))
1109        {
1110            &late_bound.binder
1111        } else {
1112            &front::Binder::empty()
1113        };
1114        self.translate_region_binder(span, late_bound, |ctx, _| {
1115            ctx.translate_unbound_fn_ptr_maybe_enqueue(span, item, enqueue)
1116        })
1117    }
1118
1119    /// Translate a reference to a function or trait method.
1120    #[tracing::instrument(skip(self, span))]
1121    pub(crate) fn translate_bound_fn_ptr(
1122        &mut self,
1123        span: Span,
1124        item: &front::ItemRef<'tcx>,
1125    ) -> Result<RegionBinder<FnPtr>, Error> {
1126        self.translate_bound_fn_ptr_maybe_enqueue(span, item, true)
1127    }
1128
1129    pub(crate) fn translate_bound_fn_ptr_no_enqueue(
1130        &mut self,
1131        span: Span,
1132        item: &front::ItemRef<'tcx>,
1133    ) -> Result<RegionBinder<FnPtr>, Error> {
1134        self.translate_bound_fn_ptr_maybe_enqueue(span, item, false)
1135    }
1136
1137    /// Translate a reference to a function or trait method, erasing or inferring its late-bound
1138    /// lifetimes.
1139    pub(crate) fn translate_fn_ptr(
1140        &mut self,
1141        span: Span,
1142        item: &front::ItemRef<'tcx>,
1143    ) -> Result<FnPtr, Error> {
1144        let fn_ptr = self.translate_bound_fn_ptr(span, item)?;
1145        let fn_ptr = self.erase_region_binder(fn_ptr);
1146        Ok(fn_ptr)
1147    }
1148
1149    pub(crate) fn translate_global_decl_ref(
1150        &mut self,
1151        span: Span,
1152        item: &front::ItemRef<'tcx>,
1153    ) -> Result<GlobalDeclRef, Error> {
1154        self.translate_item(span, item)
1155    }
1156
1157    pub(crate) fn translate_trait_decl_ref(
1158        &mut self,
1159        span: Span,
1160        item: &front::ItemRef<'tcx>,
1161    ) -> Result<TraitDeclRef, Error> {
1162        self.translate_item(span, item)
1163    }
1164
1165    pub(crate) fn translate_trait_impl_ref(
1166        &mut self,
1167        span: Span,
1168        item: &front::ItemRef<'tcx>,
1169    ) -> Result<TraitImplRef, Error> {
1170        self.translate_item(span, item)
1171    }
1172}
1173
1174#[tracing::instrument(skip(tcx, error_ctx))]
1175pub fn translate<'tcx>(
1176    tcx: TyCtxt<'tcx>,
1177    cli_options: &CliOpts,
1178    mut error_ctx: ErrorCtx,
1179    sysroot: PathBuf,
1180) -> Result<TransformCtx, Error> {
1181    let translate_options = TranslateOptions::new(&mut error_ctx, cli_options);
1182
1183    let traits_to_remove: HashSet<rustc_hir::def_id::DefId> = {
1184        let frontend_state = front::state::State::new(
1185            tcx,
1186            front::options::Options::default(),
1187            front::options::BoundsOptions::default(),
1188        );
1189        translate_options
1190            .hide_traits
1191            .iter()
1192            .flat_map(|pat| {
1193                super::resolve_path::def_path_def_ids(&frontend_state, pat, true).unwrap()
1194            })
1195            .collect()
1196    };
1197    let frontend_state = front::state::State::new(
1198        tcx,
1199        front::options::Options {
1200            inline_anon_consts: !translate_options.raw_consts,
1201            consts: rustc_const_uneval::Config {
1202                anon_allocs_as_globals: matches!(
1203                    translate_options.consts,
1204                    ConstHandling::Values | ConstHandling::Bytes
1205                ),
1206            },
1207            treat_box_as_builtin: translate_options.treat_box_as_builtin,
1208        },
1209        front::options::BoundsOptions {
1210            add_destruct_bounds: translate_options.add_destruct_bounds,
1211            remove_traits: traits_to_remove,
1212        },
1213    );
1214
1215    let crate_def_id: front::DefId = rustc_span::def_id::CRATE_DEF_ID
1216        .to_def_id()
1217        .sinto(&frontend_state);
1218    let crate_name = crate_def_id.crate_name(&frontend_state).to_string();
1219    trace!("# Crate: {}", crate_name);
1220
1221    let mut ctx = TranslateCtx {
1222        tcx,
1223        sysroot,
1224        frontend_state,
1225        options: translate_options,
1226        errors: RefCell::new(error_ctx),
1227        translated: TranslatedCrate {
1228            crate_name,
1229            preset: cli_options.preset,
1230            runtime_checks: RuntimeChecks {
1231                ub_checks: tcx.sess.ub_checks(),
1232                overflow_checks: tcx.sess.overflow_checks(),
1233                contract_checks: tcx.sess.contract_checks(),
1234            },
1235            ..TranslatedCrate::default()
1236        },
1237        method_status: Default::default(),
1238        assoc_item_id_map: Default::default(),
1239        id_map: Default::default(),
1240        reverse_id_map: Default::default(),
1241        file_to_id: Default::default(),
1242        items_to_translate: Default::default(),
1243        processed: Default::default(),
1244        containment_graph: Default::default(),
1245        translate_stack: Default::default(),
1246        cached_spans: Default::default(),
1247        cached_span_datas: Default::default(),
1248        cached_file_ids: Default::default(),
1249        cached_names: Default::default(),
1250        exported_fns: Default::default(),
1251        exported_foreign_items: Default::default(),
1252        lt_mutability_computer: Default::default(),
1253        monomorphic_layouts: Default::default(),
1254        intrinsic_def_ids: Default::default(),
1255    };
1256    ctx.register_target_info();
1257    ctx.reserve_unit_decl();
1258    ctx.register_builtin_functions()?;
1259
1260    // Start translating from the selected items.
1261    for start_from in ctx.options.start_from.clone() {
1262        match start_from {
1263            StartFrom::Pattern { pattern, strict } => {
1264                // in multi-crate translation a pattern may not be found in one crate but be in another.
1265                let strict = strict && !ctx.options.merge_crates;
1266                if let Ok(def_ids) = ctx.resolve_path(Span::dummy(), &pattern, strict) {
1267                    for def_id in def_ids {
1268                        let def_id: front::DefId = def_id.sinto(&ctx.frontend_state);
1269                        use front::DefKind::*;
1270                        match def_id.kind {
1271                            // These can be named but we can't translate them standalone.
1272                            AssocTy | OpaqueTy | Variant => {
1273                                let span = ctx.def_span(&def_id);
1274                                register_error!(
1275                                    ctx,
1276                                    span,
1277                                    "Cannot register item `{def_id:?}` with kind `{:?}`",
1278                                    def_id.kind
1279                                );
1280                                continue;
1281                            }
1282                            // This has the same name as the underlying ADT, so we skip that and
1283                            // translate only the ADT.
1284                            Ctor(..) => continue,
1285                            _ => {}
1286                        }
1287                        ctx.enqueue_module_item(&def_id, ContainmentNode::Start);
1288                    }
1289                }
1290            }
1291            StartFrom::Attribute(attr_name) => {
1292                let attr_path = attr_name
1293                    .split("::")
1294                    .map(rustc_span::Symbol::intern)
1295                    .collect_vec();
1296                let items = ctx.all_items();
1297                let mut add_if_attr_matches = |def_id: DefId| {
1298                    let def_id: front::DefId = def_id.sinto(&ctx.frontend_state);
1299                    if matches!(def_id.kind, front::DefKind::Mod) {
1300                        return;
1301                    }
1302                    let attrs = def_id.attrs(tcx);
1303                    let matches = match attr_path.as_slice() {
1304                        // The `#[test]` attribute is expanded by rustc and no longer exists at
1305                        // this stage; `RustcTestEntrypointMarker` marks the test functions we want.
1306                        [sym::test] => rustc_attr_ir::find_attr!(attrs, RustcTestEntrypointMarker),
1307                        // Otherwise, look for a tool attribute.
1308                        _ => attrs.iter().any(|a| {
1309                            matches!(a, rustc_attr_ir::Attribute::Tool { item, .. }
1310                                if *item.path.segments == *attr_path)
1311                        }),
1312                    };
1313                    if matches {
1314                        ctx.enqueue_module_item(&def_id, ContainmentNode::Start);
1315                    }
1316                };
1317                for def_id in items {
1318                    add_if_attr_matches(def_id)
1319                }
1320            }
1321            StartFrom::Pub => {
1322                let mut add_if_matches = |ldid: rustc_hir::def_id::LocalDefId| {
1323                    let def_id: front::DefId = ldid.to_def_id().sinto(&ctx.frontend_state);
1324                    if !matches!(def_id.kind, front::DefKind::Mod)
1325                        && def_id.visibility(tcx) == Some(true)
1326                    {
1327                        ctx.enqueue_module_item(&def_id, ContainmentNode::Start);
1328                    }
1329                };
1330                for ldid in tcx.hir_crate_items(()).definitions() {
1331                    add_if_matches(ldid)
1332                }
1333            }
1334            StartFrom::EntryPoint => {
1335                if let Some((def_id, rustc_session::config::EntryFnType::Main { .. })) =
1336                    tcx.entry_fn(())
1337                {
1338                    let def_id: front::DefId = def_id.sinto(&ctx.frontend_state);
1339                    ctx.enqueue_module_item(&def_id, ContainmentNode::Start);
1340                }
1341            }
1342            StartFrom::GlobalCtors => {
1343                // Translate constructors that run before the program start; this is decided
1344                // by the linker, which is a bit obscure, so we follow the same logic as Miri. See:
1345                // https://github.com/rust-lang/miri/blob/ddd2b2fc87565b16fd38e7cab9838295aaca1c40/src/shims/global_ctor.rs
1346                use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
1347                use rustc_middle::middle::exported_symbols::ExportedSymbol;
1348                use rustc_structures::CrateType;
1349                use rustc_target::spec::BinaryFormat;
1350                let is_ctor_section = |section: &str| match tcx.sess.target.binary_format {
1351                    BinaryFormat::Coff => section == ".CRT$XCU",
1352                    BinaryFormat::MachO => {
1353                        let mut parts = section.splitn(3, ',');
1354                        parts.next() == Some("__DATA")
1355                            && parts.next() == Some("__mod_init_func")
1356                            && matches!(parts.next(), None | Some("mod_init_funcs"))
1357                    }
1358                    BinaryFormat::Elf | BinaryFormat::Wasm => section == ".init_array",
1359                    _ => false,
1360                };
1361                let mut add_if_ctor = |rust_def_id: DefId, used: bool| {
1362                    if used
1363                        && let Some(section) = tcx.codegen_fn_attrs(rust_def_id).link_section
1364                        && is_ctor_section(section.as_str())
1365                    {
1366                        let def_id: front::DefId = rust_def_id.sinto(&ctx.frontend_state);
1367                        ctx.enqueue_module_item(&def_id, ContainmentNode::Start);
1368                    }
1369                };
1370                // For the local crate, we walk all its items and check their `#[used]` flags.
1371                // We can't do like below because if the crate is a binary its exported symbols
1372                // don't include its `#[used]` statics.
1373                for ldid in tcx.hir_crate_items(()).definitions() {
1374                    if tcx.def_kind(ldid).has_codegen_attrs() && !tcx.is_foreign_item(ldid) {
1375                        let flags = tcx.codegen_fn_attrs(ldid).flags;
1376                        let used = flags.intersects(
1377                            CodegenFnAttrFlags::USED_COMPILER | CodegenFnAttrFlags::USED_LINKER,
1378                        );
1379                        add_if_ctor(ldid.to_def_id(), used);
1380                    }
1381                }
1382                // For binary crates, we also look at the exported symbols of the dependencies,
1383                // because their constructors get linked into the final executable.
1384                if tcx.crate_types().contains(&CrateType::Executable) {
1385                    for &cnum in tcx.crates(()) {
1386                        if tcx.crate_dep_kind(cnum).macros_only() {
1387                            continue;
1388                        }
1389                        for &(symbol, info) in tcx.exported_non_generic_symbols(cnum) {
1390                            if let ExportedSymbol::NonGeneric(def_id) = symbol
1391                                && !tcx.is_foreign_item(def_id)
1392                            {
1393                                add_if_ctor(def_id, info.used);
1394                            }
1395                        }
1396                    }
1397                }
1398            }
1399        }
1400    }
1401
1402    if ctx.options.merge_crates {
1403        // With multi-crate translation (`--merge-crates`), we need to enqueue the whole
1404        // crate for translation, regardless of `--start-from`. This is to ensure all reachable
1405        // local items are translated in one go.
1406        // Take for example these two crates:
1407        // crate A: `pub fn foo() {}`
1408        // crate B: `pub fn bar() { crate_a::foo() }`
1409        // If we have `--start-from crate_b::bar`:
1410        // - crate A doesn't translate anything, since no start-from pattern mentions it
1411        // - crate B translates `bar` as a local fn, but also `foo` as a *foreign* one!
1412        // We are then stuck with a foreign `foo`, despite crate A being translatable.
1413        // Translating all items and then pruning them after filtering avoids this.
1414        let root: front::DefId = LOCAL_CRATE.as_def_id().sinto(&ctx.frontend_state);
1415        // Enqueue the whole crate for translation, but without marking any more
1416        // items as "started from" (since only items reachable from the `Start` node
1417        // are counted as such).
1418        ctx.enqueue_module_item(&root, ContainmentNode::WholeCrate);
1419    }
1420
1421    if ctx.errors.borrow().has_errors() {
1422        // Don't continue translating if there were errors while parsing options.
1423        return Err(Error::dummy());
1424    }
1425
1426    trace!(
1427        "Queue after we explored the crate:\n{:?}",
1428        &ctx.items_to_translate
1429    );
1430
1431    // Translate.
1432    //
1433    // For as long as the queue of items to translate is not empty, we pop the top item and
1434    // translate it. If an item refers to non-translated (potentially external) items, we add them
1435    // to the queue.
1436    //
1437    // Note that the order in which we translate the definitions doesn't matter:
1438    // we never need to lookup a translated definition, and only use the map
1439    // from Rust ids to translated ids.
1440    while let Some(item_src) = ctx.items_to_translate.pop_front() {
1441        if ctx.processed.insert(item_src.clone()) {
1442            ctx.translate_item(&item_src);
1443        }
1444    }
1445
1446    // Store the entry point in the crate, if it was reached.
1447    if let Some((def_id, rustc_session::config::EntryFnType::Main { .. })) = tcx.entry_fn(()) {
1448        let def_id: front::DefId = def_id.sinto(&ctx.frontend_state);
1449        let s = ctx.frontend_state.with_frontend_owner(&def_id);
1450        // entry-points can't have generics.
1451        let item = front::ItemRef::identity(&s, def_id.clone());
1452        let item_src = TransItemSource::from_item(&item, ctx.options.monomorphize_with_frontend);
1453        let id = ctx.register_no_enqueue(&None, &item_src).expect_item();
1454        ctx.translated.entry_point = Some(FunDeclRef {
1455            id,
1456            generics: Box::new(GenericArgs::empty()),
1457        });
1458    }
1459
1460    // Save all the monomorphic layouts we encountered during translation.
1461    let target = ctx.get_target_triple();
1462    for (tref, layout) in std::mem::take(&mut ctx.monomorphic_layouts) {
1463        if let Some(decl) = ctx.translated.type_decls.get_mut(tref.id) {
1464            decl.monomorphic_layouts
1465                .entry(*tref.generics)
1466                .or_default()
1467                .insert(target.clone(), layout);
1468        }
1469    }
1470
1471    // Remove methods not marked as "used". They are never called and we made sure not to translate
1472    // them. This removes them from the traits and impls.
1473    // This also marks as lazy the vtables of impls that weren't translated.
1474    ctx.cleanup_impls();
1475    ctx.compute_started_from();
1476
1477    // Return the context, dropping the frontend state and rustc `tcx`.
1478    Ok(TransformCtx {
1479        options: ctx.options,
1480        translated: ctx.translated,
1481        errors: ctx.errors,
1482    })
1483}