Skip to main content

charon_driver/translate/
translate_items.rs

1use super::translate_crate::*;
2use super::translate_ctx::*;
3use crate::frontend as front;
4use crate::frontend::{BaseState, SInto, UnderOwnerState};
5use charon_lib::ast::*;
6use charon_lib::formatter::IntoFormatter;
7use charon_lib::options::ConstHandling;
8use charon_lib::pretty::FmtWithCtx;
9use itertools::Itertools;
10use rustc_middle::ty;
11use rustc_span::sym;
12use std::mem;
13
14impl<'tcx> TranslateCtx<'tcx> {
15    pub(crate) fn translate_item(&mut self, item_src: &TransItemSource<'tcx>) {
16        let _guard = charon_lib::timing::scope_lazy("translate-item", || {
17            let kind = format!("{:?}", item_src.kind());
18            kind.split('(').next().unwrap().to_owned()
19        });
20        let trans_id = self.register_no_enqueue(&None, item_src);
21        let def_id = item_src.def_id();
22        if self.translate_stack.contains(&trans_id) {
23            register_error!(
24                self,
25                Span::dummy(),
26                "Cycle detected while translating {def_id:?}! Stack: {:?}",
27                &self.translate_stack
28            );
29            return;
30        }
31        self.translate_stack.push(trans_id);
32        self.with_def_id(def_id, &trans_id, |mut ctx| {
33            let span = ctx.def_span(def_id);
34            // Catch cycles
35            let res = {
36                // Stopgap measure because there are still many panics in charon and the frontend.
37                let mut ctx = std::panic::AssertUnwindSafe(&mut ctx);
38                std::panic::catch_unwind(move || ctx.translate_item_aux(item_src, trans_id))
39            };
40            match res {
41                Ok(Ok(())) => return,
42                // Translation error
43                Ok(Err(_)) => {
44                    register_error!(ctx, span, "Item `{def_id:?}` caused errors; ignoring.")
45                }
46                // Panic
47                Err(_) => register_error!(
48                    ctx,
49                    span,
50                    "Thread panicked when extracting item `{def_id:?}`."
51                ),
52            };
53        });
54        if let Some(trans_id) = trans_id.as_item()
55            && self.errors.borrow().item_has_errors(trans_id)
56            && let Some(mut item) = self.translated.get_item_mut(trans_id)
57        {
58            item.item_meta().has_errors = true;
59        }
60        // We must be careful not to early-return from this function to not unbalance the stack.
61        self.translate_stack.pop();
62    }
63
64    pub(crate) fn translate_item_aux(
65        &mut self,
66        item_src: &TransItemSource<'tcx>,
67        trans_id: ItemOrModuleId,
68    ) -> Result<(), Error> {
69        // The name may have already been computed.
70        let name = match trans_id
71            .as_item()
72            .and_then(|id| self.translated.item_names.get(&id))
73        {
74            Some(name) => name.clone(),
75            None => {
76                let name = self.translate_name(item_src)?;
77                if let Some(trans_id) = trans_id.as_item() {
78                    self.translated.item_names.insert(trans_id, name.clone());
79                }
80                name
81            }
82        };
83        let opacity = self.opacity_for_name(&name);
84        // We always translate at least a skeleton of impls, so that names render.
85        if opacity.is_invisible() && !item_src.kind().is_trait_impl() {
86            // Don't even start translating the item. In particular don't call `frontend_def` on it.
87            return Ok(());
88        }
89        let def = self.frontend_def_for_item(item_src)?;
90        let item_meta = self.translate_item_meta(&def, item_src, name, opacity);
91        if item_meta.opacity.is_invisible() && !item_src.kind().is_trait_impl() {
92            return Ok(());
93        }
94
95        // For items in the current crate that have bodies, also enqueue items defined in that
96        // body.
97        if !item_meta.opacity.is_opaque()
98            && let Some(def_id) = def.def_id().derived_base().as_real_def_id()
99            && let Some(ldid) = def_id.as_local()
100            && let node = self.tcx.hir_node_by_def_id(ldid)
101            && let Some(body_id) = node.body_id()
102        {
103            use rustc_hir::intravisit;
104            struct EnqueueNestedItems<'a, 'tcx> {
105                ctx: &'a mut TranslateCtx<'tcx>,
106                parent: ContainmentNode,
107            }
108            impl<'tcx> intravisit::Visitor<'tcx> for EnqueueNestedItems<'_, 'tcx> {
109                fn visit_nested_item(&mut self, id: rustc_hir::ItemId) {
110                    let def_id = id.owner_id.def_id.to_def_id();
111                    let def_id = def_id.sinto(&self.ctx.frontend_state);
112                    self.ctx.enqueue_module_item(&def_id, self.parent);
113                }
114            }
115            let body = self.tcx.hir_body(body_id);
116            intravisit::walk_body(
117                &mut EnqueueNestedItems {
118                    ctx: self,
119                    parent: trans_id.into(),
120                },
121                body,
122            );
123        }
124
125        // Initialize the item translation context
126        let mut bt_ctx = ItemTransCtx::new(item_src.clone(), trans_id, self);
127        trace!(
128            "About to translate item `{:?}`; \
129            target_id={trans_id:?}, mono={}",
130            def.def_id(),
131            bt_ctx.monomorphize(),
132        );
133        let trans_kind = item_src.kind();
134        if !matches!(trans_kind, ItemOrModuleKind::Module) {
135            bt_ctx.translate_item_generics(item_meta.span, &def)?;
136        }
137        match trans_kind {
138            ItemOrModuleKind::Module => bt_ctx.register_module(item_meta, &def),
139            ItemOrModuleKind::Item(ItemKind::Type) => {
140                let id = trans_id.expect_item();
141                let ty = bt_ctx.translate_type_decl(id, item_meta, &def)?;
142                self.translated.type_decls.set_slot(id, ty);
143            }
144            ItemOrModuleKind::Item(ItemKind::Fun) => {
145                let id = trans_id.expect_item();
146                let fun_decl = bt_ctx.translate_fun_decl(id, item_meta, &def)?;
147                self.translated.fun_decls.set_slot(id, fun_decl);
148            }
149            ItemOrModuleKind::Item(ItemKind::Global) => {
150                let id = trans_id.expect_item();
151                let global_decl = bt_ctx.translate_global(id, item_meta, &def)?;
152                self.translated.global_decls.set_slot(id, global_decl);
153            }
154            ItemOrModuleKind::Item(ItemKind::TraitDecl) => {
155                let id = trans_id.expect_item();
156                let trait_decl = bt_ctx.translate_trait_decl(id, item_meta, &def)?;
157                self.translated.trait_decls.set_slot(id, trait_decl);
158            }
159            ItemOrModuleKind::Item(ItemKind::TraitImpl) => {
160                let id = trans_id.expect_item();
161                let trait_impl = bt_ctx.translate_trait_impl(id, item_meta, &def)?;
162                self.translated.trait_impls.set_slot(id, trait_impl);
163            }
164        }
165        Ok(())
166    }
167
168    /// While translating an item you may need the contents of another. Use this to retreive the
169    /// translated version of this item. Use with care as this could create cycles.
170    pub(crate) fn get_or_translate(&mut self, id: ItemId) -> Result<ItemRef<'_>, Error> {
171        // We have to call `get_item` a few times because we're running into the classic `Polonius`
172        // problem case.
173        if self.translated.get_item(id).is_none() {
174            let item_source = self.reverse_id_map.get(&id).unwrap().clone();
175            self.translate_item(&item_source);
176            if self.translated.get_item(id).is_none() {
177                let span = self.def_span(item_source.def_id());
178                let name = id.to_string_with_ctx(&self.into_fmt());
179                // Not a real error, its message won't be displayed.
180                return Err(Error {
181                    span,
182                    msg: format!("Failed to translate item {name}."),
183                });
184                // raise_error!(self, span, "Failed to translate item {name}.")
185            }
186            // Add to avoid the double translation of the same item
187            self.processed.insert(item_source.clone());
188        }
189        let item = self.translated.get_item(id);
190        Ok(item.unwrap())
191    }
192
193    /// Record that `method_id` is an implementation of the given method of the trait. If the
194    /// method is not used anywhere yet we simply record the implementation. If the method is used
195    /// then we enqueue it for translation.
196    pub fn register_method_impl(
197        &mut self,
198        trait_id: TraitDeclId,
199        method_id: TraitMethodId,
200        fun_id: FunDeclId,
201    ) {
202        match &mut self.method_status[trait_id][method_id] {
203            MethodStatus::Unused { implementors } => {
204                implementors.insert(fun_id);
205            }
206            MethodStatus::Used => {
207                self.enqueue_id(fun_id);
208            }
209        }
210    }
211
212    /// Mark the method as "used", which will enqueue for translation all the implementations of
213    /// that method.
214    pub fn mark_method_as_used(&mut self, trait_id: TraitDeclId, method_id: TraitMethodId) {
215        let old_status = mem::replace(
216            &mut self.method_status[trait_id][method_id],
217            MethodStatus::Used,
218        );
219        match old_status {
220            MethodStatus::Unused { implementors } => {
221                for fun_id in implementors {
222                    self.enqueue_id(fun_id);
223                }
224            }
225            MethodStatus::Used => {}
226        }
227    }
228
229    /// Cleanup the trait impls:
230    /// - keep only the methods we marked as "used"
231    /// - mark as lazy the impl vtables we didn't translate
232    pub fn cleanup_impls(&mut self) {
233        let method_is_used = |trait_id: TraitDeclId, method_id: TraitMethodId| {
234            matches!(self.method_status[trait_id][method_id], MethodStatus::Used)
235        };
236        for tdecl in self.translated.trait_decls.iter_mut() {
237            tdecl
238                .methods
239                .retain(|i, _m| method_is_used(tdecl.def_id, i));
240        }
241        for timpl in self.translated.trait_impls.iter_mut() {
242            let trait_id = timpl.impl_trait.id;
243            timpl.methods.retain(|i, _m| method_is_used(trait_id, i));
244            if let VTableDecl::VTable(vtable) = &timpl.vtable
245                && self.translated.global_decls.get(vtable.id).is_none()
246            {
247                timpl.vtable = VTableDecl::Lazy;
248            }
249        }
250    }
251}
252
253enum TraitItemSource {
254    Default {
255        trait_ref: TraitDeclRef,
256        item_id: AssocItemId,
257    },
258    Impl {
259        impl_ref: TraitImplRef,
260        trait_ref: TraitDeclRef,
261        item_id: AssocItemId,
262        reuses_default: bool,
263    },
264}
265
266impl<'tcx> ItemTransCtx<'tcx, '_> {
267    /// Register the items inside this module or inherent impl.
268    // TODO: we may want to accumulate the set of modules we found, to check that all
269    // the opaque modules given as arguments actually exist
270    #[tracing::instrument(skip(self, item_meta, def))]
271    pub(crate) fn register_module(&mut self, item_meta: ItemMeta, def: &front::FullDef<'tcx>) {
272        if !item_meta.opacity.is_transparent() {
273            return;
274        }
275        let this: ContainmentNode = self.item_id.into();
276        match def.kind() {
277            front::FullDefKind::InherentImpl(i) => {
278                for assoc in i.items(self.frontend_state()) {
279                    self.t_ctx.enqueue_module_item(&assoc.def_id, this);
280                }
281            }
282            front::FullDefKind::Mod(m) => {
283                for (_, def_id) in m.items(self.frontend_state()) {
284                    self.t_ctx.enqueue_module_item(def_id, this);
285                }
286            }
287            front::FullDefKind::ForeignMod(m) => {
288                for def_id in m.items() {
289                    self.t_ctx.enqueue_module_item(def_id, this);
290                }
291            }
292            _ => panic!("Item should be a module but isn't: {def:?}"),
293        }
294    }
295
296    fn get_trait_item_source(
297        &mut self,
298        span: Span,
299        def: &front::FullDef<'tcx>,
300    ) -> Result<Option<TraitItemSource>, Error> {
301        let assoc = match def.kind() {
302            front::FullDefKind::AssocConst(c) => c.associated_item(),
303            front::FullDefKind::AssocFn(f) => f.associated_item(),
304            _ => return Ok(None),
305        };
306        Ok(Some(match &assoc.container {
307            // E.g.:
308            // ```
309            // impl<T> List<T> {
310            //   fn new() -> Self { ... } <- inherent method
311            // }
312            // ```
313            front::AssocItemContainer::InherentImplContainer { .. } => return Ok(None),
314            // E.g.:
315            // ```
316            // impl Foo for Bar {
317            //   fn baz(...) { ... } // <- implementation of a trait method
318            // }
319            // ```
320            front::AssocItemContainer::TraitImplContainer {
321                impl_,
322                implemented_trait_ref,
323                ..
324            } => {
325                let impl_ref = self.translate_trait_impl_ref(span, impl_)?;
326                let trait_ref = self.translate_trait_ref(span, implemented_trait_ref)?;
327                let item_id = self.translate_assoc_item_id(trait_ref.id, def.def_id())?;
328                if matches!(def.kind(), front::FullDefKind::AssocFn(_)) {
329                    // If the implementation is getting translated, that means the method is
330                    // getting used.
331                    let method_id = *item_id.as_method().unwrap();
332                    self.mark_method_as_used(trait_ref.id, method_id);
333                }
334                TraitItemSource::Impl {
335                    impl_ref,
336                    trait_ref,
337                    item_id,
338                    reuses_default: false,
339                }
340            }
341            // This method is the *declaration* of a trait item
342            // E.g.:
343            // ```
344            // trait Foo {
345            //   fn baz(...); // <- declaration of a trait method
346            // }
347            // ```
348            front::AssocItemContainer::TraitContainer { trait_ref, .. } => {
349                // The trait id should be Some(...): trait markers (that we may eliminate)
350                // don't have associated items.
351                let trait_ref = self.translate_trait_ref(span, trait_ref)?;
352                let item_id = self.translate_assoc_item_id(trait_ref.id, def.def_id())?;
353                if matches!(def.kind(), front::FullDefKind::AssocFn(_)) {
354                    // If the method fundecl is getting translated, that means the method is
355                    // getting used.
356                    let method_id = *item_id.as_method().unwrap();
357                    self.mark_method_as_used(trait_ref.id, method_id);
358                }
359                debug_assert!(assoc.has_value);
360                TraitItemSource::Default { trait_ref, item_id }
361            }
362        }))
363    }
364
365    /// Translate a type definition.
366    ///
367    /// Note that we translate the types one by one: we don't need to take into
368    /// account the fact that some types are mutually recursive at this point
369    /// (we will need to take that into account when generating the code in a file).
370    #[tracing::instrument(skip(self, item_meta, def))]
371    pub fn translate_type_decl(
372        mut self,
373        trans_id: TypeDeclId,
374        item_meta: ItemMeta,
375        def: &front::FullDef<'tcx>,
376    ) -> Result<TypeDecl, Error> {
377        if let front::FullDefKind::Adt(adt) = def.kind()
378            && matches!(adt.adt_kind(), front::AdtKind::VTable)
379        {
380            let trait_def = self.poly_frontend_def(def.def_id().peel_derived())?;
381            return self.translate_vtable_struct(trans_id, item_meta, &trait_def);
382        }
383        let span = item_meta.span;
384
385        // Get the kind of the type decl.
386        let src = if let front::FullDefKind::Closure(_) = def.kind() {
387            let info = self.translate_closure_info(span, def)?;
388            TypeSource::Closure { info }
389        } else if let Some(builtin) = self.recognize_builtin_adt(def.this()) {
390            TypeSource::Builtin(builtin)
391        } else {
392            TypeSource::Normal
393        };
394
395        // Translate type body
396        let kind = match &def.kind {
397            _ if item_meta.opacity.is_opaque() => Ok(TypeDeclKind::Opaque),
398            front::FullDefKind::OpaqueTy | front::FullDefKind::ForeignTy => {
399                Ok(TypeDeclKind::Opaque)
400            }
401            front::FullDefKind::TyAlias(a) => {
402                // Don't error on missing trait refs.
403                self.error_on_trait_proof_error = false;
404                self.translate_ty(span, a.ty()).map(TypeDeclKind::Alias)
405            }
406            front::FullDefKind::Adt(_) => self.translate_adt_def(trans_id, span, &item_meta, def),
407            front::FullDefKind::Closure(c) => self.translate_closure_adt(span, c),
408            _ => panic!("Unexpected item when translating types: {def:?}"),
409        };
410
411        let kind = match kind {
412            Ok(kind) => kind,
413            Err(err) => TypeDeclKind::Error(err.msg),
414        };
415        let layout = TargetLayouts(
416            self.translate_layout(span, def.this(), Some(&kind))
417                .into_iter()
418                .map(|l| (self.get_target_triple(), l))
419                .collect(),
420        );
421        let ptr_metadata = self.translate_ptr_metadata(span, def.this())?;
422        // We compute the marker traits. We can not compute markers when the type
423        // is generic (because the answer might depend on the markers of the parameters),
424        // but when the only generics are lifetimes we can, since lifetimes do not affect
425        // the marker traits.
426        let marker_traits = (!def.this().mentions_non_lt_param).then(|| {
427            let ty = def.type_of(&self.frontend_state).unwrap();
428            let tcx = self.frontend_state.base().tcx;
429            let typing_env = self.frontend_state.typing_env();
430            let implements = |trait_id| {
431                let tref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_id, [ty]));
432                !front::solve_trait(&self.frontend_state, tref)
433                    .kind
434                    .is_error()
435            };
436            Box::new(ImplementsMarkerTraits {
437                is_sized: ty.is_sized(tcx, typing_env),
438                is_send: implements(tcx.get_diagnostic_item(sym::Send).unwrap()),
439                is_sync: implements(tcx.lang_items().sync_trait().unwrap()),
440                is_freeze: ty.is_freeze(tcx, typing_env),
441                is_unpin: ty.is_unpin(tcx, typing_env),
442            })
443        });
444        Ok(TypeDecl {
445            def_id: trans_id,
446            item_meta,
447            generics: self.into_generics(),
448            kind,
449            src,
450            layout,
451            monomorphic_layouts: Default::default(),
452            ptr_metadata,
453            marker_traits,
454        })
455    }
456
457    /// Translate one function.
458    #[tracing::instrument(skip(self, item_meta, def))]
459    pub fn translate_fun_decl(
460        mut self,
461        def_id: FunDeclId,
462        item_meta: ItemMeta,
463        def: &front::FullDef<'tcx>,
464    ) -> Result<FunDecl, Error> {
465        use front::DerivedItemKind;
466        let span = item_meta.span;
467
468        let src = if def.def_id().as_derived() == Some(&DerivedItemKind::Initializer) {
469            let global_id =
470                self.register_item(span, &def.this().derived_base(self.frontend_state()));
471            FunSource::GlobalInitializer(GlobalDeclRef {
472                id: global_id,
473                generics: Box::new(self.outermost_generics().identity_args()),
474            })
475        } else if matches!(
476            def.def_id().as_derived(),
477            Some(DerivedItemKind::VTableMethodShim | DerivedItemKind::VTableDropShim)
478        ) {
479            FunSource::VTableShim
480        } else if matches!(def.kind(), front::FullDefKind::Ctor(_)) {
481            FunSource::AdtConstructor
482        } else if let front::FullDefKind::AssocFn(f) = def.kind()
483            && let front::AssocItemContainer::InherentImplContainer { self_ty, .. } =
484                &f.associated_item().container
485        {
486            FunSource::InherentImpl {
487                self_ty: self.translate_ty(span, self_ty)?,
488            }
489        } else {
490            match self.get_trait_item_source(span, def)? {
491                None => FunSource::Normal,
492                Some(TraitItemSource::Default { trait_ref, item_id }) => FunSource::TraitDefault {
493                    trait_ref,
494                    item_id: *item_id.as_method().unwrap(),
495                },
496                Some(TraitItemSource::Impl {
497                    impl_ref,
498                    trait_ref,
499                    item_id,
500                    reuses_default,
501                }) => FunSource::TraitImpl {
502                    impl_ref,
503                    trait_ref,
504                    item_id: *item_id.as_method().unwrap(),
505                    reuses_default,
506                },
507            }
508        };
509
510        if let front::FullDefKind::Ctor(ctor) = def.kind() {
511            let signature = FunSig {
512                inputs: ctor
513                    .fields()
514                    .iter()
515                    .map(|field| self.translate_ty(span, &field.ty))
516                    .try_collect()?,
517                output: self.translate_ty(span, ctor.output_ty())?,
518                is_unsafe: false,
519                abi: from_rustc::ExternAbi::rust(),
520                is_variadic: false,
521            };
522
523            let body = if item_meta.opacity.with_private_contents().is_opaque() {
524                Body::Opaque
525            } else {
526                self.build_ctor_body(span, def)?
527            };
528            return Ok(FunDecl {
529                def_id,
530                item_meta,
531                generics: self.into_generics(),
532                signature: Box::new(signature),
533                src,
534                body,
535            });
536        }
537
538        // Translate the function signature
539        trace!("Translating function signature");
540        let signature = match &def.kind {
541            front::FullDefKind::Fn(f) => self.translate_fun_sig(span, &f.sig().value)?,
542            front::FullDefKind::AssocFn(f) => self.translate_fun_sig(span, &f.sig().value)?,
543            _ => panic!("Unexpected definition for function: {def:?}"),
544        };
545
546        let intrinsic_def_id = match def.def_id().as_derived() {
547            Some(DerivedItemKind::IntrinsicFallback) => def.def_id().peel_derived(),
548            _ => def.def_id(),
549        };
550        let intrinsic = intrinsic_def_id
551            .as_real_def_id()
552            .and_then(|id| self.tcx.intrinsic(id));
553
554        let body = if let Some(intrinsic) = intrinsic
555            && intrinsic.name == ty::Intrinsic::Rustc(sym::type_id)
556            && def.def_id().as_derived() == Some(&front::DerivedItemKind::IntrinsicFallback)
557        {
558            self.build_type_id_body(span, &signature)?
559        } else if let Some(intrinsic) = intrinsic
560            && def.def_id().as_derived() != Some(&front::DerivedItemKind::IntrinsicFallback)
561        {
562            // we special-case type_id: we give it a custom fallback that is the spec
563            let is_type_id = intrinsic.name == ty::Intrinsic::Rustc(sym::type_id);
564            let arg_names = self.translate_argument_names(def, signature.inputs.len());
565            let fallback = if intrinsic.must_be_overridden && !is_type_id {
566                None
567            } else {
568                let fallback = def.this().make_derived(
569                    self.frontend_state_with_id(),
570                    front::DerivedItemKind::IntrinsicFallback,
571                );
572                Some(self.translate_item(span, &fallback)?)
573            };
574            // from nightly-2026-10-29 onwards, we can use tcx.tool_attrs for this (https://rust.tf/164900)
575            let fallback_is_spec = item_meta
576                .attr_info
577                .attributes
578                .iter()
579                .filter_map(|a| a.as_unknown())
580                .any(|a| a.path == "miri::intrinsic_fallback_is_spec");
581            Body::Intrinsic {
582                name: intrinsic.name.to_string(),
583                arg_names,
584                fallback,
585                fallback_is_spec: fallback_is_spec || is_type_id,
586            }
587        } else if let Some(symbol) = self.t_ctx.extern_item_symbol_name(def) {
588            let mut definition = LinkedExtern::Unlinked;
589            if self.options.link_extern_fns
590                && let front::FullDefKind::Fn(..) = def.kind()
591            {
592                let exported = self.t_ctx.exported_fns(&symbol);
593                let mut translate_fn = |instance: ty::Instance<'tcx>| {
594                    let item = front::ItemRef::translate(
595                        self.frontend_state_with_id(),
596                        instance.def_id(),
597                        instance.args,
598                    );
599                    self.translate_item(span, &item)
600                };
601                definition = match exported {
602                    ExportedFns::None => LinkedExtern::Unlinked,
603                    ExportedFns::Strong(instance) => {
604                        LinkedExtern::StronglyLinked(translate_fn(instance)?)
605                    }
606                    ExportedFns::Weak(instances) => LinkedExtern::WeaklyLinked(
607                        instances.into_iter().map(translate_fn).try_collect()?,
608                    ),
609                    ExportedFns::AllocatorShim(instance) => {
610                        LinkedExtern::AllocatorShim(translate_fn(instance)?)
611                    }
612                    ExportedFns::Many => {
613                        register_error!(
614                            self,
615                            span,
616                            "several functions are exported under the symbol `{symbol}`"
617                        );
618                        LinkedExtern::Unlinked
619                    }
620                };
621            }
622            Body::Extern { symbol, definition }
623        } else if item_meta.diagnostic_item.as_deref()
624            == Some(names::BOX_ASSUME_INIT_INTO_VEC_UNSAFE)
625            && self.options.treat_box_as_builtin
626        {
627            // FIXME(#865): the MIR we get is unusably optimized. Instead we build our own body
628            // here.
629            self.build_box_assume_init_into_vec_unsafe(span, def)?
630        } else if item_meta.lang_item.as_ref() == Some(&from_rustc::LangItem::DropGlue) {
631            self.build_drop_glue_body(span, def, &signature)?
632        } else if item_meta.opacity.with_private_contents().is_opaque() {
633            Body::Opaque
634        } else if def.def_id().as_derived() == Some(&DerivedItemKind::ClosureAsFnCast) {
635            self.translate_stateless_closure_as_fn_body(span, def, &signature)?
636        } else if def.def_id().as_derived() == Some(&DerivedItemKind::VTableMethodShim) {
637            self.translate_vtable_shim_body(span, def, &signature)?
638        } else if def.def_id().as_derived() == Some(&DerivedItemKind::VTableDropShim) {
639            self.translate_vtable_drop_shim_body(span, def, &signature)?
640        } else if let Some(DerivedItemKind::BuiltinAssocItemImpl(_)) = def.def_id().as_derived() {
641            match def.def_id().peel_derived().as_derived() {
642                Some(DerivedItemKind::FnImpl(kind)) => {
643                    let kind = super::translate_closures::translate_closure_kind(kind);
644                    self.translate_callable_method_body(span, def, kind, &signature)?
645                }
646                Some(DerivedItemKind::DestructImpl) => {
647                    self.translate_drop_glue_method_body(span, def)?
648                }
649                _ => unreachable!("unexpected built-in impl"),
650            }
651        } else if def.def_id().as_derived() == Some(&DerivedItemKind::Initializer) {
652            let base = def.this().peel_derived(self.frontend_state());
653            let base_def = self.frontend_def(&base)?;
654            self.translate_def_body(span, &base_def)
655        } else {
656            // Translate the MIR body for this definition.
657            self.translate_def_body(item_meta.span, def)
658        };
659        Ok(FunDecl {
660            def_id,
661            item_meta,
662            generics: self.into_generics(),
663            signature: Box::new(signature),
664            src,
665            body,
666        })
667    }
668
669    /// Translate one global.
670    #[tracing::instrument(skip(self, item_meta, def))]
671    pub fn translate_global(
672        mut self,
673        def_id: GlobalDeclId,
674        item_meta: ItemMeta,
675        def: &front::FullDef<'tcx>,
676    ) -> Result<GlobalDecl, Error> {
677        let span = item_meta.span;
678
679        // Retrieve the kind
680        let item_source = match self.get_trait_item_source(span, def)? {
681            None if def.def_id().as_derived() == Some(&front::DerivedItemKind::VTableImpl) => {
682                self.get_vtable_instance_source(span, def)?
683            }
684            None => GlobalSource::Normal,
685            Some(TraitItemSource::Default { trait_ref, item_id }) => GlobalSource::TraitDefault {
686                trait_ref,
687                item_id: *item_id.as_const().unwrap(),
688            },
689            Some(TraitItemSource::Impl {
690                impl_ref,
691                trait_ref,
692                item_id,
693                reuses_default,
694            }) => GlobalSource::TraitImpl {
695                impl_ref,
696                trait_ref,
697                item_id: *item_id.as_const().unwrap(),
698                reuses_default,
699            },
700        };
701
702        trace!("Translating global type");
703        let ty = match &def.kind {
704            front::FullDefKind::Const(c) => c.ty(),
705            front::FullDefKind::AssocConst(c) => c.ty(),
706            front::FullDefKind::Static(s) => s.ty(),
707            _ => panic!("Unexpected def for constant: {def:?}"),
708        };
709        let ty = self.translate_ty(span, ty)?;
710
711        let (size, align) = if let front::DefIdBase::Alloc(alloc_id) = def.def_id().base {
712            let tcx = self.t_ctx.tcx;
713            let alloc = rustc_const_uneval::GlobalRef::Alloc(alloc_id)
714                .memory(tcx)
715                .unwrap()
716                .inner();
717            (
718                Size::new(alloc.size().bytes()),
719                Size::new(alloc.align.bytes()),
720            )
721        } else {
722            let mut align = SizeExpr::align_of(&ty);
723            if let front::FullDefKind::Static(_) = def.kind()
724                && let Some(rust_def_id) = def.def_id().as_real_def_id()
725                && let Some(attr_align) = self.t_ctx.tcx.codegen_fn_attrs(rust_def_id).alignment
726            {
727                align = SizeExpr::max_align(vec![
728                    align,
729                    SizeExpr::from_usize(attr_align.bytes().into()),
730                ]);
731            }
732            (
733                Size::from_expr(SizeExpr::size_of(&ty)),
734                Size::from_expr(align),
735            )
736        };
737
738        let global_kind = match &def.kind {
739            front::FullDefKind::Static(_)
740                if def.def_id().as_derived() == Some(&front::DerivedItemKind::VTableImpl) =>
741            {
742                GlobalKind::VTable
743            }
744            front::FullDefKind::Static(s) => {
745                let is_mut = s.mutability() == front::Mutability::Mut;
746                let is_safe = s.safety() == front::Safety::Safe;
747                let is_thread_local = s.thread_local();
748                GlobalKind::Static {
749                    is_mut,
750                    is_safe,
751                    is_thread_local,
752                }
753            }
754            front::FullDefKind::Const(c) if matches!(c.kind(), front::ConstKind::TopLevel) => {
755                GlobalKind::NamedConst
756            }
757            front::FullDefKind::AssocConst(_) => GlobalKind::NamedConst,
758            front::FullDefKind::Const(_) => GlobalKind::AnonConst,
759            _ => panic!("Unexpected def for constant: {def:?}"),
760        };
761
762        // Try to evaluate the constant/static into a value if requested. This isn't always
763        // possible (e.g. for generic constants or recursive statics), in which case we fall back
764        // to a call to the initializer below. Globals that stand for an anonymous allocation have
765        // no initializer, so they are always evaluated.
766        let is_anon_alloc = matches!(def.def_id().base, front::DefIdBase::Alloc(..));
767        let mode = match self.options.consts {
768            ConstHandling::Bytes => Some(front::ReadMode::Bytes),
769            ConstHandling::Values => Some(front::ReadMode::Structured),
770            ConstHandling::Initializers if is_anon_alloc => Some(front::ReadMode::Structured),
771            ConstHandling::Initializers => None,
772        };
773        let value = if global_kind == GlobalKind::VTable {
774            let kind = if item_meta.opacity.with_private_contents().is_opaque() {
775                ConstantExprKind::Opaque("VTable was chosen to be opaque".to_string())
776            } else {
777                self.gen_vtable_value(span, def, ty.kind().as_adt().unwrap().clone())?
778            };
779            ConstantExpr::new(kind, ty.clone())
780        } else if let front::FullDefKind::Static(_) = def.kind()
781            && let Some(rust_def_id) = def.def_id().as_real_def_id()
782            && self
783                .t_ctx
784                .tcx
785                .codegen_fn_attrs(rust_def_id)
786                .import_linkage
787                .is_some()
788            && let Some(symbol) = self.t_ctx.extern_item_symbol_name(def)
789        {
790            // A foreign static with `#[linkage]` holds the address of the symbol it names.
791            let addr = ConstantExpr::new(
792                ConstantExprKind::ExternSymbol(symbol),
793                Ty::new(TyKind::RawPtr(Ty::mk_unit(), RefKind::Shared)),
794            );
795            ConstantExpr::new(
796                ConstantExprKind::Cast(addr, CastKind::Transmute(ty.clone())),
797                ty.clone(),
798            )
799        } else if let Some(evaluated) =
800            mode.and_then(|mode| def.evaluate(self.frontend_state_with_id(), mode))
801        {
802            self.translate_constant_expr(span, &evaluated)?
803        } else {
804            // Default: the value is a call to the initializer function, which uses the same
805            // generic parameters as the global.
806            let initializer = self.register_item(
807                span,
808                &def.this().make_derived(
809                    self.frontend_state_with_id(),
810                    front::DerivedItemKind::Initializer,
811                ),
812            );
813            ConstantExpr::new(
814                ConstantExprKind::Call(
815                    FnPtr::new(
816                        FnPtrKind::Fun(initializer),
817                        self.outermost_generics().identity_args(),
818                    ),
819                    vec![],
820                ),
821                ty.clone(),
822            )
823        };
824
825        Ok(GlobalDecl {
826            def_id,
827            item_meta,
828            generics: self.into_generics(),
829            ty,
830            size,
831            align,
832            ptr_metadata: ConstantExpr::mk_unit(),
833            src: item_source,
834            global_kind,
835            value,
836        })
837    }
838
839    // either Poly or MonoTrait
840    #[tracing::instrument(skip(self, item_meta, def))]
841    pub fn translate_trait_decl(
842        mut self,
843        trait_decl_id: TraitDeclId,
844        item_meta: ItemMeta,
845        def: &front::FullDef<'tcx>,
846    ) -> Result<TraitDecl, Error> {
847        let span = item_meta.span;
848
849        let implied_predicates = match def.kind() {
850            front::FullDefKind::Trait(t) => t.implied_predicates(),
851            front::FullDefKind::TraitAlias(t) => t.implied_predicates(),
852            _ => raise_error!(self, span, "Unexpected definition: {def:?}"),
853        };
854        let (src, is_unsafe, is_auto) = match def.kind() {
855            front::FullDefKind::Trait(tr) => {
856                (TraitDeclSource::Normal, tr.is_unsafe(), tr.is_auto())
857            }
858            front::FullDefKind::TraitAlias(_) => (TraitDeclSource::TraitAlias, false, false),
859            _ => unreachable!(),
860        };
861        let impl_restriction = if let front::FullDefKind::Trait(tr) = def.kind()
862            && let Some(mod_id) = tr.impl_restriction()
863        {
864            let mod_src = TransItemSource::polymorphic(mod_id);
865            ImplRestriction::Restricted(self.translate_name(&mod_src)?)
866        } else {
867            ImplRestriction::Unrestricted
868        };
869
870        // Register implied predicates. We gather the clauses and consider the other predicates as
871        // required since the distinction doesn't matter for non-trait-clauses.
872        let mut implied_clauses = Default::default();
873        self.translate_predicates(
874            implied_predicates,
875            PredicateOrigin::WhereClauseOnTrait,
876            Some(&mut implied_clauses),
877        )?;
878
879        let vtable = self.translate_vtable_struct_ref_no_enqueue(span, def.this())?;
880
881        if let front::FullDefKind::TraitAlias(_) = def.kind() {
882            // Trait aliases don't have any items. Everything interesting is in the parent clauses.
883            return Ok(TraitDecl {
884                def_id: trait_decl_id,
885                item_meta,
886                src,
887                is_unsafe,
888                is_auto,
889                impl_restriction: impl_restriction.clone(),
890                implied_clauses,
891                generics: self.into_generics(),
892                consts: Default::default(),
893                types: Default::default(),
894                methods: Default::default(),
895                vtable,
896            });
897        }
898
899        let t = def.kind().as_trait().unwrap();
900        let self_trait_ref = TraitRef::new(
901            TraitRefKind::SelfId,
902            self.translate_trait_predicate(span, t.self_predicate())?,
903        );
904
905        // Translate the associated items
906        self.register_assoc_items(def.def_id(), trait_decl_id)?;
907        let mut consts: IndexMap<AssocConstId, _> = IndexMap::new();
908        let mut types: IndexMap<AssocTypeId, _> = IndexMap::new();
909        let mut methods: IndexMap<TraitMethodId, _> = IndexMap::new();
910
911        for frontend_item in t.items(self.frontend_state()) {
912            // TODO: support methods and consts in mono mode. For now we only keep the synthetic
913            // `drop_glue` method.
914            if self.monomorphize()
915                && frontend_item.def_id.as_derived()
916                    != Some(&front::DerivedItemKind::DropGlueMethodDef)
917            {
918                continue;
919            }
920            let item_def_id = &frontend_item.def_id;
921            let item_span = self.def_span(item_def_id);
922            let assoc_item_id = self.translate_assoc_item_id(trait_decl_id, item_def_id)?;
923            let item_name = self
924                .translated
925                .assoc_item_name(trait_decl_id, assoc_item_id);
926
927            // In --mono mode, we keep only non-polymorphic items; in not-mono mode, we use the
928            // polymorphic item as usual.
929            let item_def = self.poly_frontend_def(item_def_id)?;
930            let item_src = TransItemSource::polymorphic(item_def_id);
931            let attr_info = self.translate_attr_info(&item_def);
932
933            match item_def.kind() {
934                front::FullDefKind::AssocFn(f) => {
935                    let trait_method_id = *assoc_item_id.as_method().unwrap();
936                    let method_name = self.translate_name(&item_src)?;
937                    let method_opacity = self.opacity_for_name(&method_name);
938                    let method_item_meta =
939                        self.translate_item_meta(&item_def, &item_src, method_name, method_opacity);
940                    let method_containment_id =
941                        ContainmentNode::TraitMethod(trait_decl_id, trait_method_id);
942                    // By default we only enqueue required methods (those that don't have a default
943                    // impl). If the trait is transparent, we enqueue all its methods.
944                    if self.options.translate_all_methods
945                        || item_meta.opacity.is_transparent()
946                        || !frontend_item.has_value
947                    {
948                        self.mark_method_as_used(trait_decl_id, trait_method_id);
949                        self.record_containment(
950                            ItemId::TraitDecl(trait_decl_id),
951                            method_containment_id,
952                        );
953                    }
954                    let default_fun_id = f.associated_item().has_value.then(|| {
955                        let fun_id = self.register_no_enqueue(item_span, &item_src);
956                        // Register this method.
957                        self.register_method_impl(trait_decl_id, trait_method_id, fun_id);
958                        self.record_containment(method_containment_id, ItemId::Fun(fun_id));
959                        fun_id
960                    });
961
962                    let binder_kind = BinderKind::TraitMethod(trait_decl_id, trait_method_id);
963                    let mut method = self.translate_binder_for_def(
964                        item_span,
965                        binder_kind,
966                        &item_def,
967                        |bt_ctx| {
968                            assert_eq!(bt_ctx.binding_levels.len(), 2);
969                            let default = default_fun_id.map(|id| {
970                                let fun_generics = bt_ctx
971                                    .outermost_binder()
972                                    .params
973                                    .identity_args_at_depth(DeBruijnId::one())
974                                    .concat(
975                                        &bt_ctx
976                                            .innermost_binder()
977                                            .params
978                                            .identity_args_at_depth(DeBruijnId::zero()),
979                                    );
980                                FunDeclRef {
981                                    id,
982                                    generics: Box::new(fun_generics),
983                                }
984                            });
985                            // `skip_binder` is allowed because `translate_binder_for_def` puts the
986                            // late bound params in scope.
987                            let signature = if bt_ctx.monomorphize() {
988                                // Can only reach here for the drop glue method.
989                                // FIXME: put something real here
990                                bt_ctx.drop_glue_method_sig(
991                                    Ty::mk_unit(),
992                                    Region::Var(DeBruijnVar::new_at_zero(RegionId::ZERO)),
993                                )
994                            } else {
995                                bt_ctx
996                                    .translate_fun_sig(span, f.sig().frontend_skip_binder_ref())?
997                            };
998                            Ok(TraitMethod {
999                                name: item_name,
1000                                item_meta: method_item_meta,
1001                                signature,
1002                                default,
1003                            })
1004                        },
1005                    )?;
1006                    // In the frontend, associated items take an extra explicit `Self: Trait` clause, but we
1007                    // don't want that to be part of the method clauses. Hence we remove the first
1008                    // bound clause and replace its uses with references to the ambient `Self`
1009                    // clause available in trait declarations.
1010                    struct ReplaceSelfVisitor;
1011                    impl VarsVisitor for ReplaceSelfVisitor {
1012                        fn visit_clause_var(
1013                            &mut self,
1014                            v: ClauseDbVar,
1015                        ) -> Option<ClauseReplacement> {
1016                            if let DeBruijnVar::Bound(DeBruijnId::ZERO, clause_id) = v {
1017                                // Replace clause 0 and decrement the others.
1018                                Some(if let Some(new_id) = clause_id.index().checked_sub(1) {
1019                                    ClauseReplacement::Var(DeBruijnVar::Bound(
1020                                        DeBruijnId::ZERO,
1021                                        TraitClauseId::new(new_id),
1022                                    ))
1023                                } else {
1024                                    ClauseReplacement::Proof(RegionBinder::empty(
1025                                        TraitRefKind::SelfId,
1026                                    ))
1027                                })
1028                            } else {
1029                                None
1030                            }
1031                        }
1032                    }
1033                    method.params.visit_vars(&mut ReplaceSelfVisitor);
1034                    method.skip_binder.visit_vars(&mut ReplaceSelfVisitor);
1035                    method
1036                        .params
1037                        .trait_clauses
1038                        .remove_and_shift_ids(TraitClauseId::ZERO);
1039                    method.params.trait_clauses.iter_mut().for_each(|clause| {
1040                        clause.clause_id -= 1;
1041                    });
1042
1043                    // We insert the `Binder<TraitMethod>` unconditionally here; we'll remove the
1044                    // ones that correspond to unused methods at the end of translation.
1045                    methods.set_slot_extend(trait_method_id, method);
1046                }
1047                front::FullDefKind::AssocConst(c) => {
1048                    let assoc_const_id = *assoc_item_id.as_const().unwrap();
1049                    // The const is defined in a context that has an extra `Self: Trait` clause, so
1050                    // we translate it bound first.
1051                    let bound_assoc_const = self.translate_binder_for_def(
1052                        item_span,
1053                        BinderKind::Other,
1054                        &item_def,
1055                        |ctx| {
1056                            // Check if the constant has a value (i.e., a body).
1057                            let default = frontend_item.has_value.then(|| {
1058                                // The parameters of the constant are the same as those of the item that
1059                                // declares them.
1060                                let id = ctx.register_and_enqueue(item_span, item_src);
1061                                if item_meta.opacity.is_transparent() {
1062                                    ctx.record_containment(
1063                                        ItemId::TraitDecl(trait_decl_id),
1064                                        ItemId::Global(id),
1065                                    );
1066                                }
1067                                let generics = ctx
1068                                    .outermost_binder()
1069                                    .params
1070                                    .identity_args_at_depth(DeBruijnId::one())
1071                                    .concat(
1072                                        &ctx.innermost_binder()
1073                                            .params
1074                                            .identity_args_at_depth(DeBruijnId::zero()),
1075                                    );
1076                                GlobalDeclRef {
1077                                    id,
1078                                    generics: Box::new(generics),
1079                                }
1080                            });
1081                            let ty = ctx.translate_ty(item_span, c.ty())?;
1082                            Ok(TraitAssocConst {
1083                                name: item_name,
1084                                attr_info,
1085                                ty,
1086                                default,
1087                            })
1088                        },
1089                    )?;
1090                    let assoc_const = bound_assoc_const.apply(&{
1091                        let mut generics = GenericArgs::empty();
1092                        // Provide the `Self` clause.
1093                        generics
1094                            .trait_refs
1095                            .push(PolyTraitRef::empty(self_trait_ref.clone()));
1096                        generics
1097                    });
1098                    consts.set_slot_extend(assoc_const_id, assoc_const);
1099                }
1100                front::FullDefKind::AssocTy(assoc_ty_def) => {
1101                    let assoc_type_id = *assoc_item_id.as_type().unwrap();
1102                    let binder_kind = BinderKind::TraitType(trait_decl_id, assoc_type_id);
1103                    let assoc_ty =
1104                        self.translate_binder_for_def(item_span, binder_kind, &item_def, |ctx| {
1105                            // Also add the implied predicates.
1106                            let mut implied_clauses = Default::default();
1107                            ctx.translate_predicates(
1108                                assoc_ty_def.implied_predicates(),
1109                                PredicateOrigin::TraitItem(assoc_type_id),
1110                                Some(&mut implied_clauses),
1111                            )?;
1112
1113                            let default = assoc_ty_def
1114                                .value(ctx.frontend_state())
1115                                .map(|(ty, trait_proofs)| -> Result<_, Error> {
1116                                    let ty = ctx.translate_ty(item_span, &ty)?;
1117                                    let trefs = ctx.translate_trait_proofs(span, &trait_proofs)?;
1118                                    Ok(TraitAssocTyImpl {
1119                                        value: ty,
1120                                        implied_trait_refs: trefs,
1121                                    })
1122                                })
1123                                .transpose()?;
1124                            Ok(TraitAssocTy {
1125                                name: item_name,
1126                                attr_info,
1127                                default,
1128                                implied_clauses,
1129                            })
1130                        })?;
1131                    types.set_slot_extend(assoc_type_id, assoc_ty);
1132                }
1133                _ => panic!("Unexpected definition for trait item: {item_def:?}"),
1134            }
1135        }
1136
1137        Ok(TraitDecl {
1138            def_id: trait_decl_id,
1139            item_meta,
1140            src,
1141            is_unsafe,
1142            is_auto,
1143            impl_restriction,
1144            implied_clauses,
1145            generics: self.into_generics(),
1146            consts,
1147            types,
1148            methods,
1149            vtable,
1150        })
1151    }
1152
1153    #[tracing::instrument(skip(self, item_meta, def))]
1154    pub fn translate_trait_impl(
1155        mut self,
1156        def_id: TraitImplId,
1157        item_meta: ItemMeta,
1158        def: &front::FullDef<'tcx>,
1159    ) -> Result<TraitImpl, Error> {
1160        let span = item_meta.span;
1161
1162        let timpl = def.kind().as_trait_impl().unwrap();
1163
1164        // Retrieve the information about the implemented trait.
1165        let trait_pred = timpl.trait_pred();
1166        let implemented_trait = self.translate_trait_ref(span, &trait_pred.trait_ref)?;
1167        // The trait refs which implement the parent clauses of the implemented trait decl.
1168        let implied_trait_refs = self.translate_trait_proofs(span, timpl.implied_trait_proofs())?;
1169        let trait_id = implemented_trait.id;
1170        let is_negative = !trait_pred.is_positive;
1171        let is_unsafe = timpl.is_unsafe();
1172        let src = match def.def_id().as_derived() {
1173            Some(front::DerivedItemKind::TraitAliasImpl) => TraitImplSource::TraitAlias,
1174            Some(_) => TraitImplSource::Builtin,
1175            None => TraitImplSource::Normal,
1176        };
1177
1178        // Translate the bare minimum needed for names.
1179        if self.is_poly_in_mono(&self.item_src) || item_meta.opacity.is_invisible() {
1180            let msg = if self.is_poly_in_mono(&self.item_src) {
1181                "polymorphic impl in monomorphic mode".into()
1182            } else {
1183                "excluded impl".into()
1184            };
1185            return Ok(TraitImpl {
1186                def_id,
1187                item_meta,
1188                src,
1189                impl_trait: implemented_trait,
1190                is_negative,
1191                is_unsafe,
1192                generics: self.into_generics(),
1193                implied_trait_refs,
1194                consts: Default::default(),
1195                types: Default::default(),
1196                methods: Default::default(),
1197                vtable: VTableDecl::Unknown(msg),
1198            });
1199        }
1200
1201        // A `TraitRef` that points to this impl with the correct generics.
1202        let self_predicate = TraitRef::new(
1203            TraitRefKind::TraitImpl(TraitImplRef {
1204                id: def_id,
1205                generics: Box::new(self.the_only_binder().params.identity_args()),
1206            }),
1207            implemented_trait.clone(),
1208        );
1209
1210        let vtable = self.translate_trait_impl_vtable(span, &trait_pred.trait_ref, def.this())?;
1211
1212        {
1213            // Debugging
1214            let ctx = self.into_fmt();
1215            let refs = implied_trait_refs
1216                .iter()
1217                .map(|c| c.with_ctx(&ctx))
1218                .format("\n");
1219            trace!(
1220                "Trait impl: {:?}\n- implied_trait_refs:\n{}",
1221                def.def_id(),
1222                refs
1223            );
1224        }
1225
1226        let implemented_trait_def = self.poly_frontend_def(&trait_pred.trait_ref.def_id)?;
1227
1228        // Gather the associated items
1229        let mut consts: IndexMap<AssocConstId, _> = IndexMap::new();
1230        let mut types: IndexMap<AssocTypeId, _> = IndexMap::new();
1231        let mut methods: IndexMap<TraitMethodId, _> = IndexMap::new();
1232
1233        // In mono mode, we do not translate any associated items apart from the made-up
1234        // `Destruct::drop_glue` method.
1235        if self.monomorphize() && implemented_trait_def.lang_item != Some(sym::destruct) {
1236            return Ok(TraitImpl {
1237                def_id,
1238                item_meta,
1239                src,
1240                impl_trait: implemented_trait,
1241                is_negative,
1242                is_unsafe,
1243                generics: self.into_generics(),
1244                implied_trait_refs,
1245                consts,
1246                types,
1247                methods,
1248                vtable,
1249            });
1250        }
1251
1252        for impl_item in timpl.items(self.frontend_state()) {
1253            let item_def_id = impl_item.def_id().unwrap_or(impl_item.decl_def_id());
1254            let item_span = self.def_span(item_def_id);
1255            let assoc_item_id = self.translate_assoc_item_id(trait_id, item_def_id)?;
1256
1257            // In not-mono mode, we use the polymorphic item as usual.
1258            let item_src = TransItemSource::polymorphic(item_def_id);
1259            match item_def_id.kind {
1260                front::DefKind::AssocFn => {
1261                    let trait_method_id = *assoc_item_id.as_method().unwrap();
1262                    let binder_kind = BinderKind::TraitMethod(trait_id, trait_method_id);
1263                    let bound_fn_ref = match &impl_item.value {
1264                        Some(value) => {
1265                            // By default we only enqueue required methods (those that don't have a default
1266                            // impl). If the impl is transparent, we enqueue all the implemented methods.
1267                            if item_meta.opacity.is_transparent() {
1268                                self.mark_method_as_used(trait_id, trait_method_id);
1269                            }
1270                            self.translate_trait_item_binder(
1271                                item_span,
1272                                binder_kind,
1273                                value,
1274                                PredicateOrigin::WhereClauseOnFn,
1275                                |ctx, value| {
1276                                    let bound_fn_ptr = ctx.translate_bound_fn_ptr_no_enqueue(
1277                                        item_span,
1278                                        &value.item,
1279                                    )?;
1280                                    // FIXME(#513): the regions may not match.
1281                                    let late_bound_regions: RegionArgs = ctx
1282                                        .innermost_binder()
1283                                        .bound_region_vars
1284                                        .iter()
1285                                        .map(|rid| Region::Var(DeBruijnVar::new_at_zero(*rid)))
1286                                        .collect();
1287                                    let fn_ptr = bound_fn_ptr.apply(late_bound_regions);
1288                                    Ok(FunDeclRef {
1289                                        id: *fn_ptr.kind.as_fun().unwrap(),
1290                                        generics: fn_ptr.generics,
1291                                    })
1292                                },
1293                            )?
1294                        }
1295                        // We fill that in later, in `fill_default_trait_items`.
1296                        None => continue,
1297                    };
1298
1299                    // Register this method.
1300                    self.register_method_impl(
1301                        trait_id,
1302                        trait_method_id,
1303                        bound_fn_ref.skip_binder.id,
1304                    );
1305                    if item_meta.opacity.is_transparent() && impl_item.value.is_some() {
1306                        self.record_containment(
1307                            ItemId::TraitImpl(def_id),
1308                            ItemId::Fun(bound_fn_ref.skip_binder.id),
1309                        );
1310                    }
1311
1312                    // We insert the `Binder<FunDeclRef>` unconditionally here; we'll remove the
1313                    // ones that correspond to unused methods at the end of translation.
1314                    methods.set_slot_extend(trait_method_id, bound_fn_ref);
1315                }
1316                front::DefKind::AssocConst => {
1317                    let assoc_const_id = *assoc_item_id.as_const().unwrap();
1318                    let id = self.register_and_enqueue(item_span, item_src);
1319                    if item_meta.opacity.is_transparent() && impl_item.value.is_some() {
1320                        self.record_containment(ItemId::TraitImpl(def_id), ItemId::Global(id));
1321                    }
1322                    // The parameters of the constant are the same as those of the item that
1323                    // declares them.
1324                    let generics = match &impl_item.value {
1325                        Some(_) => self.the_only_binder().params.identity_args(),
1326                        None => {
1327                            let mut generics = implemented_trait.generics.as_ref().clone();
1328                            // For default consts, we add an extra `Self` predicate.
1329                            generics
1330                                .trait_refs
1331                                .push(PolyTraitRef::empty(self_predicate.clone()));
1332                            generics
1333                        }
1334                    };
1335                    let gref = GlobalDeclRef {
1336                        id,
1337                        generics: Box::new(generics),
1338                    };
1339                    consts.set_slot_extend(assoc_const_id, gref);
1340                }
1341                front::DefKind::AssocTy => {
1342                    let assoc_type_id = *assoc_item_id.as_type().unwrap();
1343                    let binder_kind = BinderKind::TraitType(trait_id, assoc_type_id);
1344                    let assoc_ty = match &impl_item.value {
1345                        Some(impl_value) => self.translate_trait_item_binder(
1346                            item_span,
1347                            binder_kind,
1348                            impl_value,
1349                            PredicateOrigin::WhereClauseOnType,
1350                            |ctx, impl_value| {
1351                                let ty = ctx.translate_ty(
1352                                    item_span,
1353                                    impl_value.assoc_ty_value.as_ref().unwrap(),
1354                                )?;
1355                                let implied_trait_refs = ctx.translate_trait_proofs(
1356                                    item_span,
1357                                    &impl_value.implied_trait_proofs,
1358                                )?;
1359                                Ok(TraitAssocTyImpl {
1360                                    value: ty,
1361                                    implied_trait_refs,
1362                                })
1363                            },
1364                        )?,
1365                        // We fill that in later, in `fill_default_trait_items`.
1366                        None => continue,
1367                    };
1368
1369                    types.set_slot_extend(assoc_type_id, assoc_ty);
1370                }
1371                _ => panic!("Unexpected definition for trait item: {item_def_id:?}"),
1372            }
1373        }
1374
1375        Ok(TraitImpl {
1376            def_id,
1377            item_meta,
1378            src,
1379            impl_trait: implemented_trait,
1380            is_negative,
1381            is_unsafe,
1382            generics: self.into_generics(),
1383            implied_trait_refs,
1384            consts,
1385            types,
1386            methods,
1387            vtable,
1388        })
1389    }
1390}