Skip to main content

charon_driver/translate/
translate_trait_objects.rs

1use itertools::Itertools;
2use rustc_attr_ir::LangItem;
3use rustc_span::kw;
4use std::mem;
5
6use super::{
7    translate_closures::recognize_fn_trait_impl_proof, translate_ctx::*,
8    translate_generics::BindingLevel,
9};
10use crate::frontend as front;
11use charon_lib::formatter::IntoFormatter;
12use charon_lib::pretty::FmtWithCtx;
13use charon_lib::ullbc_ast::*;
14
15/// A vtable method pointer.
16///
17/// In monomorphized mode, it must be cast to the erased field type.
18enum VtableMethodValue {
19    Const(FnPtr),
20    /// The type of the shim function pointer and shim function pointer.
21    Cast(Ty, FnPtr),
22}
23
24/// Takes a `T` valid in the context of a trait ref and transforms it into a `T` valid in the
25/// context of its vtable definition, i.e. no longer mentions the `Self` type or `Self` clause. If
26/// `new_self` is `Some`, we replace any mention of the `Self` type with it; otherwise we panic if
27/// `Self` is mentioned.
28/// If `for_method` is true, we're handling a value coming from a `AssocFn`, which takes the `Self`
29/// clause as its first clause parameter. Otherwise we're in trait scope, where the `Self` clause
30/// is represented with `TraitRefKind::SelfId`.
31fn dynify<T: TyVisitable>(mut x: T, new_self: Option<Ty>, for_method: bool) -> T {
32    struct ReplaceSelfVisitor {
33        new_self: Option<Ty>,
34        for_method: bool,
35    }
36    impl VarsVisitor for ReplaceSelfVisitor {
37        fn visit_type_var(&mut self, v: TypeDbVar) -> Option<Ty> {
38            if let DeBruijnVar::Bound(DeBruijnId::ZERO, type_id) = v {
39                // Replace type 0 and decrement the others.
40                Some(if let Some(new_id) = type_id.index().checked_sub(1) {
41                    TyKind::TypeVar(DeBruijnVar::Bound(DeBruijnId::ZERO, TypeVarId::new(new_id)))
42                        .into_ty()
43                } else {
44                    self.new_self.clone().expect(
45                        "Found unexpected `Self`
46                        type when constructing vtable",
47                    )
48                })
49            } else {
50                None
51            }
52        }
53
54        fn visit_clause_var(&mut self, v: ClauseDbVar) -> Option<ClauseReplacement> {
55            if let DeBruijnVar::Bound(DeBruijnId::ZERO, clause_id) = v {
56                if self.for_method && clause_id == TraitClauseId::ZERO {
57                    // That's the `Self` clause.
58                    Some(ClauseReplacement::Proof(RegionBinder::empty(
59                        TraitRefKind::Dyn,
60                    )))
61                } else {
62                    panic!("Found unexpected clause var when constructing vtable: {v}")
63                }
64            } else {
65                None
66            }
67        }
68
69        fn visit_self_clause(&mut self) -> Option<TraitRefKind> {
70            Some(TraitRefKind::Dyn)
71        }
72    }
73    x.visit_vars(&mut ReplaceSelfVisitor {
74        new_self,
75        for_method,
76    });
77    x
78}
79
80/// Translate the `dyn Trait` type.
81impl<'tcx> ItemTransCtx<'tcx, '_> {
82    pub fn check_at_most_one_pred_has_methods(
83        &mut self,
84        span: Span,
85        preds: &front::GenericPredicates<'tcx>,
86    ) -> Result<(), Error> {
87        // Only the first clause is allowed to have methods.
88        for pred in preds.predicates.iter().skip(1) {
89            if let front::ClauseKind::Trait(trait_predicate) =
90                pred.clause.kind.frontend_skip_binder_ref()
91            {
92                let trait_def_id = &trait_predicate.trait_ref.def_id;
93                let trait_def = self.poly_frontend_def(trait_def_id)?;
94                let has_methods = match trait_def.kind() {
95                    front::FullDefKind::Trait(t) => t
96                        .items(self.frontend_state())
97                        .iter()
98                        .any(|assoc| matches!(assoc.kind, front::AssocKind::Fn { .. })),
99                    front::FullDefKind::TraitAlias(_) => false,
100                    _ => unreachable!(),
101                };
102                if has_methods {
103                    raise_error!(
104                        self,
105                        span,
106                        "`dyn Trait` with multiple method-bearing predicates is not supported"
107                    );
108                }
109            }
110        }
111        Ok(())
112    }
113
114    pub fn translate_dyn_binder<T, U>(
115        &mut self,
116        span: Span,
117        binder: &front::DynBinder<'tcx, T>,
118        f: impl FnOnce(&mut Self, Ty, &T) -> Result<U, Error>,
119    ) -> Result<Binder<U>, Error> {
120        // This is a robustness check: the current version of Rustc
121        // accepts at most one method-bearing predicate in a trait object.
122        // But things may change in the future.
123        self.check_at_most_one_pred_has_methods(span, &binder.predicates)?;
124
125        // Add a binder that contains the existentially quantified type.
126        self.binding_levels.push(BindingLevel::new_dyn());
127
128        // Add the existentially quantified type.
129        let ty_id = self.innermost_binder_mut().push_type_var(
130            binder.existential_ty.index,
131            binder.existential_ty.name,
132            Variance::Unknown,
133        );
134        let ty = TyKind::TypeVar(DeBruijnVar::new_at_zero(ty_id)).into_ty();
135
136        self.register_predicates(&binder.predicates, PredicateOrigin::Dyn)?;
137
138        let val = f(self, ty, &binder.val)?;
139
140        // As illustrated inside translate_trait_decl, associated items take an extra explicit `Self: Trait` clause in the frontend.
141        // Therefore, in mono mode, projection predicates in dyn binders may refer to clause vars with an
142        // extra slot (e.g. `Bound(0, 1)` instead of `Bound(0, 0)`).
143        // Hence, we normalize them so that associated type constraints point to trait clauses in the scope.
144        if self.monomorphize() {
145            struct ShiftDynClauseVars;
146            impl VarsVisitor for ShiftDynClauseVars {
147                fn visit_clause_var(&mut self, v: ClauseDbVar) -> Option<ClauseReplacement> {
148                    if let DeBruijnVar::Bound(DeBruijnId::ZERO, clause_id) = v
149                        && let Some(new_id) = clause_id.index().checked_sub(1)
150                    {
151                        return Some(ClauseReplacement::Var(DeBruijnVar::Bound(
152                            DeBruijnId::ZERO,
153                            TraitClauseId::new(new_id),
154                        )));
155                    }
156                    None
157                }
158            }
159
160            self.innermost_generics_mut()
161                .trait_type_constraints
162                .iter_mut()
163                .for_each(|pred| pred.visit_vars(&mut ShiftDynClauseVars));
164        }
165
166        let params = self.binding_levels.pop().unwrap().params;
167        Ok(Binder {
168            params,
169            skip_binder: val,
170            kind: BinderKind::Dyn,
171        })
172    }
173}
174
175/// Vtable field info used for translation (same deal as `charon_lib::VTableField` but with
176/// different data).
177#[derive(Debug)]
178pub enum TrVTableField<'tcx> {
179    Size,
180    Align,
181    Drop,
182    Method(
183        TraitMethodId,
184        front::Binder<front::TyFnSig<'tcx>>,
185        MetadataPath,
186    ),
187    SuperTrait(TraitClauseId, front::Clause<'tcx>),
188}
189
190pub struct VTableData<'tcx> {
191    pub fields: IndexVec<FieldId, TrVTableField<'tcx>>,
192    pub supertrait_map: IndexVec<TraitClauseId, Option<FieldId>>,
193}
194
195/// Generate the vtable struct.
196impl<'tcx> ItemTransCtx<'tcx, '_> {
197    /// Query whether a trait is dyn compatible.
198    /// TODO(dyn): for now we return `false` if the trait has any associated types, as we don't
199    /// handle associated types in vtables.
200    pub fn trait_is_dyn_compatible(&mut self, def_id: &front::DefId) -> bool {
201        matches!(
202            def_id.kind,
203            front::DefKind::Trait | front::DefKind::TraitAlias
204        ) && def_id
205            .as_real_def_id()
206            .is_some_and(|id| self.tcx.is_dyn_compatible(id))
207    }
208
209    /// Check whether this trait ref is of the form `Self: Trait<...>`.
210    fn pred_is_for_self(&self, tref: &front::TraitRef<'tcx>) -> bool {
211        let first_ty = tref
212            .generic_args
213            .iter()
214            .filter_map(|arg| match arg {
215                front::GenericArg::Type(ty) => Some(ty),
216                _ => None,
217            })
218            .next();
219        match first_ty {
220            None => false,
221            Some(first_ty) => match first_ty.kind() {
222                front::TyKind::Param(param_ty) if param_ty.index == 0 => {
223                    assert_eq!(param_ty.name, kw::SelfUpper);
224                    true
225                }
226                _ => false,
227            },
228        }
229    }
230
231    pub fn translate_vtable_struct_ref(
232        &mut self,
233        span: Span,
234        tref: &front::TraitRef<'tcx>,
235    ) -> Result<TypeDeclRef, Error> {
236        let Some(vtable) = self.translate_vtable_struct_ref_maybe_enqueue(true, span, tref)? else {
237            raise_error!(self, span, "Trait {:?} is not dyn-compatible", tref.def_id);
238        };
239        Ok(vtable)
240    }
241
242    pub fn translate_vtable_struct_ref_no_enqueue(
243        &mut self,
244        span: Span,
245        tref: &front::TraitRef<'tcx>,
246    ) -> Result<Option<TypeDeclRef>, Error> {
247        self.translate_vtable_struct_ref_maybe_enqueue(false, span, tref)
248    }
249
250    /// Given a trait ref, return a reference to its vtable struct, if it is dyn compatible.
251    /// The tref must be valid in ths current frontend state: we call frontend functions to resolve
252    /// associated types on it.
253    pub fn translate_vtable_struct_ref_maybe_enqueue(
254        &mut self,
255        enqueue: bool,
256        span: Span,
257        tref: &front::TraitRef<'tcx>,
258    ) -> Result<Option<TypeDeclRef>, Error> {
259        if !self.trait_is_dyn_compatible(&tref.def_id) {
260            return Ok(None);
261        }
262
263        // Don't enqueue the vtable for translation by default. It will be enqueued if used in a
264        // `dyn Trait`.
265        let vtable_ref = self.translate_type_decl_ref_maybe_enqueue(
266            span,
267            &tref.make_derived(
268                self.frontend_state_with_id(),
269                front::DerivedItemKind::VTableDef,
270            ),
271            enqueue,
272        )?;
273        Ok(Some(vtable_ref))
274    }
275
276    fn prepare_vtable_fields(
277        &mut self,
278        poly_trait_def: &front::FullDef<'tcx>,
279        trait_id: TraitDeclId,
280        implied_predicates: &front::GenericPredicates<'tcx>,
281    ) -> Result<VTableData<'tcx>, Error> {
282        let mut supertrait_map: IndexVec<TraitClauseId, _> =
283            (0..implied_predicates.predicates.len())
284                .map(|_| None)
285                .collect();
286        let mut fields = IndexVec::new();
287
288        // Basic fields.
289        fields.push(TrVTableField::Size);
290        fields.push(TrVTableField::Align);
291        fields.push(TrVTableField::Drop);
292
293        // Method fields.
294        if let front::FullDefKind::Trait(t) = poly_trait_def.kind() {
295            for item in t.items(self.frontend_state()) {
296                let item_def_id = &item.def_id;
297                // This is ok because dyn-compatible methods don't have generics.
298                let poly_item_def = self.poly_frontend_def(item_def_id)?;
299                if let front::FullDefKind::AssocFn(f) = poly_item_def.kind()
300                    && let Some(sig) = f.vtable_sig(self.frontend_state())
301                {
302                    let id = self.translate_trait_method_id_no_enqueue(trait_id, item_def_id)?;
303                    let path = self
304                        .translate_metadata_path(&f.vtable_receiver_path(self.frontend_state()));
305                    fields.push(TrVTableField::Method(id, sig, path));
306                }
307            }
308        }
309
310        // Supertrait fields.
311        for (i, pred) in implied_predicates.iter_trait_clauses().enumerate() {
312            let trait_clause_id = TraitClauseId::from_usize(i); // One trait clause id per trait clause
313            let clause = &pred.clause;
314            let front::ClauseKind::Trait(pred) = clause.kind.frontend_skip_binder_ref() else {
315                unreachable!()
316            };
317            // If a clause looks like `Self: OtherTrait<...>`, we consider it a supertrait.
318            if self.pred_is_for_self(&pred.trait_ref) {
319                if !self.trait_is_dyn_compatible(&pred.trait_ref.def_id) {
320                    // We add fake `Destruct` supertraits, but these are not dyn-compatible.
321                    self.assert_is_destruct(&pred.trait_ref);
322                    continue;
323                }
324                supertrait_map[trait_clause_id] = Some(fields.next_idx());
325                fields.push(TrVTableField::SuperTrait(trait_clause_id, clause.clone()));
326            }
327        }
328
329        Ok(VTableData {
330            fields,
331            supertrait_map,
332        })
333    }
334
335    /// The Charon+frontend machinery will add Destruct super-traits to trait bounds,
336    /// however for `dyn Trait` the Destruct super-trait is unexepcted, as it is not
337    /// dyn-compatible.
338    /// We use this function to ensure that any non dyn-compatible super-trait is
339    /// Destruct and can be safely ignored.
340    fn assert_is_destruct(&self, tref: &front::TraitRef<'tcx>) {
341        assert!(
342            tref.def_id
343                .as_real_def_id()
344                .is_some_and(|id| self.tcx.is_lang_item(id, LangItem::Destruct)),
345            "unexpected non-dyn compatible supertrait: {:?}",
346            tref.def_id
347        );
348    }
349
350    fn gen_vtable_struct_fields(
351        &mut self,
352        span: Span,
353        self_trait_ref: &TraitRef,
354        vtable_data: &VTableData<'tcx>,
355    ) -> Result<IndexVec<FieldId, Field>, Error> {
356        let mut fields = IndexVec::new();
357        let mut supertrait_counter = 0..;
358        for field in &vtable_data.fields {
359            let (name, ty) = match field {
360                TrVTableField::Size => ("size".into(), Ty::mk_usize()),
361                TrVTableField::Align => ("align".into(), Ty::mk_usize()),
362                TrVTableField::Drop => {
363                    // In Mono mode, drop shims are opaque function pointers.
364                    if self.monomorphize() {
365                        let erased_ptr_ty = Ty::new(TyKind::RawPtr(Ty::mk_unit(), RefKind::Shared));
366                        ("drop".into(), erased_ptr_ty)
367                    } else {
368                        let self_ty =
369                            TyKind::TypeVar(DeBruijnVar::new_at_zero(TypeVarId::ZERO)).into_ty();
370                        let drop_ty = Ty::new(TyKind::FnPtr(self.drop_glue_fn_ptr_sig(self_ty)));
371                        ("drop".into(), drop_ty)
372                    }
373                }
374                TrVTableField::Method(item_id, sig, _) => {
375                    let item_name = self
376                        .translated
377                        .assoc_item_name(self_trait_ref.trait_id(), *item_id);
378                    let field_name = format!("method_{}", item_name.0);
379                    // In Mono mode, method shims are opaque function pointers.
380                    if self.monomorphize() {
381                        let erased_ptr_ty = Ty::new(TyKind::RawPtr(Ty::mk_unit(), RefKind::Shared));
382                        (field_name, erased_ptr_ty)
383                    } else {
384                        let sig = self.translate_poly_fun_sig(span, sig)?;
385                        let ty = TyKind::FnPtr(sig).into_ty();
386                        (field_name, ty)
387                    }
388                }
389                TrVTableField::SuperTrait(_, clause) => {
390                    let vtbl_struct =
391                        self.translate_region_binder(span, &clause.kind, |ctx, kind| {
392                            let front::ClauseKind::Trait(pred) = kind else {
393                                unreachable!()
394                            };
395                            ctx.translate_vtable_struct_ref(span, &pred.trait_ref)
396                        })?;
397                    let vtbl_struct = self.erase_region_binder(vtbl_struct);
398                    let ty = Ty::new(TyKind::Ref(
399                        Region::Static,
400                        Ty::new(TyKind::Adt(vtbl_struct)),
401                        RefKind::Shared,
402                    ));
403                    let name = format!("super_trait_{}", supertrait_counter.next().unwrap());
404                    (name, ty)
405                }
406            };
407            fields.push(Field {
408                span,
409                attr_info: AttrInfo::dummy_public(),
410                name,
411                is_positional: false,
412                ty,
413            });
414        }
415        Ok(fields)
416    }
417
418    /// Construct the type of the vtable for this trait.
419    ///
420    /// It's a struct that has for generics the generics of the trait + one parameter for each
421    /// associated type of the trait and its parents.
422    ///
423    /// struct TraitVTable<TraitArgs.., AssocTys..> {
424    ///   size: usize,
425    ///   align: usize,
426    ///   drop: fn(*mut dyn Trait<...>),
427    ///   method_name: fn(&dyn Trait<...>, Args..) -> Output,
428    ///   by_value_method: fn(*mut dyn Trait<...>, Args..) -> Output,
429    ///   ... other methods
430    ///   super_trait_0: &'static SuperTrait0VTable
431    ///   ... other supertraits
432    /// }
433    pub(crate) fn translate_vtable_struct(
434        mut self,
435        type_id: TypeDeclId,
436        item_meta: ItemMeta,
437        trait_def: &front::FullDef<'tcx>,
438    ) -> Result<TypeDecl, Error> {
439        let mono = self.monomorphize();
440        let span = item_meta.span;
441        if !self.trait_is_dyn_compatible(trait_def.def_id()) {
442            raise_error!(
443                self,
444                span,
445                "Trying to compute the vtable type \
446                for a non-dyn-compatible trait"
447            );
448        }
449
450        let (self_predicate, dyn_self, implied_predicates) = match trait_def.kind() {
451            front::FullDefKind::Trait(t) => {
452                (t.self_predicate(), t.dyn_self(), t.implied_predicates())
453            }
454            front::FullDefKind::TraitAlias(t) => {
455                (t.self_predicate(), t.dyn_self(), t.implied_predicates())
456            }
457            _ => panic!(),
458        };
459        let Some(dyn_self) = dyn_self else {
460            panic!("Trying to generate a vtable for a non-dyn-compatible trait")
461        };
462
463        let self_trait_ref = TraitRef::new(
464            TraitRefKind::SelfId,
465            self.translate_trait_predicate(span, self_predicate)?,
466        );
467        let trait_id = self_trait_ref.trait_id();
468
469        let mut field_map = IndexVec::new();
470        let mut supertrait_map: IndexVec<TraitClauseId, _> =
471            (0..implied_predicates.predicates.len())
472                .map(|_| None)
473                .collect();
474        let (mut kind, layout) = if item_meta.opacity.with_private_contents().is_opaque() {
475            (TypeDeclKind::Opaque, TargetLayouts::default())
476        } else {
477            // First construct fields that use the real method signatures (which may use the `Self`
478            // type). We fixup the types and generics below.
479            let vtable_data =
480                self.prepare_vtable_fields(trait_def, trait_id, implied_predicates)?;
481            let fields = self.gen_vtable_struct_fields(span, &self_trait_ref, &vtable_data)?;
482
483            let kind = TypeDeclKind::Struct(fields);
484            let l = self.generate_naive_layout(span, &kind)?;
485            supertrait_map = vtable_data.supertrait_map;
486            field_map = vtable_data.fields.map_ref(|tr_field| match tr_field {
487                TrVTableField::Size => VTableField::Size,
488                TrVTableField::Align => VTableField::Align,
489                TrVTableField::Drop => VTableField::Drop,
490                TrVTableField::Method(id, _, path) => VTableField::Method(*id, path.clone()),
491                TrVTableField::SuperTrait(clause_id, ..) => VTableField::SuperTrait(*clause_id),
492            });
493            let layout = TargetLayouts(SeqHashMap::from_iter([(self.get_target_triple(), l)]));
494            (kind, layout)
495        };
496
497        let mut generics = Default::default();
498
499        let dyn_predicate = if mono {
500            DynPredicate {
501                binder: Binder {
502                    params: GenericParams::empty(),
503                    skip_binder: TyKind::Error(
504                        "mono vtable dyn predicate is intentionally erased".to_string(),
505                    )
506                    .into_ty(),
507                    kind: BinderKind::Dyn,
508                },
509            }
510        } else {
511            // The `dyn Trait<Args..>` type for this trait.
512            // This is only used in poly mode
513            let mut dyn_self = {
514                let dyn_self = self.translate_ty(span, dyn_self)?;
515                let TyKind::DynTrait(mut dyn_pred) = dyn_self.kind().clone() else {
516                    panic!("incorrect `dyn_self`")
517                };
518
519                // Add one generic parameter for each associated type of this trait and its parents. We
520                // then use that in `dyn_self`
521                for (i, ty_constraint) in dyn_pred
522                    .binder
523                    .params
524                    .trait_type_constraints
525                    .iter_mut()
526                    .enumerate()
527                {
528                    let name = format!("Ty{i}");
529                    let new_ty = self
530                        .the_only_binder_mut()
531                        .params
532                        .types
533                        .push_with(|index| TypeParam::new(index, name, Variance::Invariant));
534                    // Moving that type under two levels of binders: the `DynPredicate` binder and the
535                    // type constraint binder.
536                    let new_ty =
537                        TyKind::TypeVar(DeBruijnVar::bound(DeBruijnId::new(2), new_ty)).into_ty();
538                    ty_constraint.skip_binder.ty = new_ty;
539                }
540                TyKind::DynTrait(dyn_pred).into_ty()
541            };
542
543            // Replace any use of `Self` with `dyn Trait<...>`, and remove the `Self` type variable
544            // from the generic parameters.
545            generics = self.into_generics();
546            {
547                dyn_self = dynify(dyn_self, None, false);
548                generics = dynify(generics, Some(dyn_self.clone()), false);
549                kind = dynify(kind, Some(dyn_self.clone()), true);
550                generics.types.remove_and_shift_ids(TypeVarId::ZERO);
551                generics.types.iter_mut().for_each(|ty| {
552                    ty.index -= 1;
553                });
554            }
555
556            dyn_self
557                .kind()
558                .as_dyn_trait()
559                .expect("incorrect `dyn_self`")
560                .clone()
561        };
562        Ok(TypeDecl {
563            def_id: type_id,
564            item_meta,
565            generics,
566            src: TypeSource::VTable {
567                dyn_predicate,
568                field_map,
569                supertrait_map,
570            },
571            kind,
572            layout,
573            monomorphic_layouts: Default::default(),
574            // A vtable struct is always sized
575            ptr_metadata: PtrMetadata::None,
576            marker_traits: Some(Box::new(ImplementsMarkerTraits {
577                is_sized: true,
578                is_send: true,
579                is_sync: true,
580                is_freeze: true,
581                is_unpin: true,
582            })),
583        })
584    }
585}
586
587/// Generate a vtable value.
588impl<'tcx> ItemTransCtx<'tcx, '_> {
589    /// Construct a constant that represents a reference to the vtable corresponding to this this trait proof.
590    pub fn translate_vtable_instance_const(
591        &mut self,
592        span: Span,
593        trait_proof: &front::TraitProof<'tcx>,
594    ) -> Result<ConstantExpr, Error> {
595        let tref = trait_proof.pred.frontend_skip_binder_ref();
596        if !self.trait_is_dyn_compatible(&tref.def_id) {
597            raise_error!(
598                self,
599                span,
600                "Trait {:?} should be dyn-compatible",
601                tref.def_id
602            );
603        }
604
605        let vtbl_ty = {
606            let vtbl_ty = self.translate_region_binder(span, &trait_proof.pred, |ctx, tref| {
607                ctx.translate_vtable_struct_ref(span, tref)
608            })?;
609            let vtbl_ty = self.erase_region_binder(vtbl_ty);
610            TyKind::Adt(vtbl_ty).into_ty()
611        };
612        let ty = TyKind::Ref(Region::Static, vtbl_ty.clone(), RefKind::Shared).into_ty();
613
614        let fn_trait_impl = recognize_fn_trait_impl_proof(trait_proof);
615        let kind = match &trait_proof.kind {
616            front::TraitProofKind::Concrete { .. } | front::TraitProofKind::Builtin { .. } => {
617                // We could return `VTableRef` but we need to enqueue the translation of the static
618                // so may as well reuse that to normalize a bit.
619                let vtable_instance =
620                    self.translate_region_binder(span, &trait_proof.pred, |ctx, tref| {
621                        let s = ctx.frontend_state_with_id();
622                        // We're inside the binder of `trait_proof.pred`, so we can skip the
623                        // binder of the `Self` type.
624                        let impl_item = match (&trait_proof.kind, fn_trait_impl) {
625                            (front::TraitProofKind::Concrete(impl_item), _) => impl_item,
626                            // This is a builtin `Fn*` impl for a callable.
627                            (_, Some((self_ty, kind))) => {
628                                let Some(item) = self_ty.frontend_skip_binder_ref().callable_item()
629                                else {
630                                    unreachable!("builtin `Fn*` impl for {self_ty:?}")
631                                };
632                                &item.make_derived(s, front::DerivedItemKind::FnImpl(kind.into()))
633                            }
634                            (_, None) => &tref.make_derived(s, front::DerivedItemKind::MarkerImpl),
635                        };
636                        ctx.translate_vtable_instance_ref(span, tref, impl_item)
637                    })?;
638                let vtable_instance = self.erase_region_binder(vtable_instance);
639                let vtable_instance = GlobalPlace::new_global(vtable_instance, vtbl_ty);
640                ConstantExprKind::Ref(vtable_instance, None)
641            }
642            _ => ConstantExprKind::VTableRef(self.translate_trait_proof(span, trait_proof)?),
643        };
644
645        Ok(ConstantExpr::new(kind, ty))
646    }
647
648    /// You may want `translate_vtable_instance_const` instead.
649    pub fn translate_vtable_instance_ref(
650        &mut self,
651        span: Span,
652        trait_ref: &front::TraitRef<'tcx>,
653        vtable_item: &front::ItemRef<'tcx>,
654    ) -> Result<GlobalDeclRef, Error> {
655        Ok(self
656            .translate_vtable_instance_ref_maybe_enqueue(true, span, trait_ref, vtable_item)?
657            .expect("trait should be dyn-compatible"))
658    }
659
660    pub fn translate_vtable_instance_ref_no_enqueue(
661        &mut self,
662        span: Span,
663        trait_ref: &front::TraitRef<'tcx>,
664        vtable_item: &front::ItemRef<'tcx>,
665    ) -> Result<Option<GlobalDeclRef>, Error> {
666        self.translate_vtable_instance_ref_maybe_enqueue(false, span, trait_ref, vtable_item)
667    }
668
669    /// Compute the `vtable` field of a trait impl. If `--eager-vtables` is set, this enqueues the
670    /// vtable for translation.
671    pub fn translate_trait_impl_vtable(
672        &mut self,
673        span: Span,
674        trait_ref: &front::TraitRef<'tcx>,
675        vtable_item: &front::ItemRef<'tcx>,
676    ) -> Result<VTableDecl, Error> {
677        let Some(vtable_struct) = self.translate_vtable_struct_ref_no_enqueue(span, trait_ref)?
678        else {
679            return Ok(VTableDecl::NotDynCompatible);
680        };
681        // The vtable initializer needs the fields of the vtable struct.
682        let struct_name = &self.translated.item_names[&ItemId::Type(vtable_struct.id)];
683        if self.opacity_for_name(struct_name).is_invisible() {
684            return Ok(VTableDecl::Unknown(
685                "the vtable struct of the trait is excluded".into(),
686            ));
687        }
688        let vtable = self
689            .translate_vtable_instance_ref_maybe_enqueue(
690                self.options.eager_vtables,
691                span,
692                trait_ref,
693                vtable_item,
694            )?
695            .unwrap();
696        Ok(VTableDecl::VTable(vtable))
697    }
698
699    pub fn translate_vtable_instance_ref_maybe_enqueue(
700        &mut self,
701        enqueue: bool,
702        span: Span,
703        trait_ref: &front::TraitRef<'tcx>,
704        vtable_item: &front::ItemRef<'tcx>,
705    ) -> Result<Option<GlobalDeclRef>, Error> {
706        if !self.trait_is_dyn_compatible(&trait_ref.def_id) {
707            return Ok(None);
708        }
709        // Don't enqueue the vtable for translation by default. It will be enqueued if used in a
710        // `dyn Trait` coercion.
711        // TODO(dyn): To do this properly we'd need to know for each clause whether it ultimately
712        // ends up used in a vtable cast.
713        let vtable_ref: GlobalDeclRef = self.translate_item_maybe_enqueue(
714            span,
715            &vtable_item.make_derived(
716                self.frontend_state_with_id(),
717                front::DerivedItemKind::VTableImpl,
718            ),
719            enqueue,
720        )?;
721        Ok(Some(vtable_ref))
722    }
723
724    pub(crate) fn get_vtable_instance_source(
725        &mut self,
726        span: Span,
727        vtable_static_def: &front::FullDef<'tcx>,
728    ) -> Result<GlobalSource, Error> {
729        let impl_item = vtable_static_def.this().peel_derived(self.frontend_state());
730        let impl_def = self.frontend_def(&impl_item)?;
731        let timpl = impl_def.kind().as_trait_impl().unwrap();
732        let implemented_trait = &timpl.trait_pred().trait_ref;
733
734        let self_ty =
735            self.translate_ty(span, implemented_trait.generic_args[0].as_type().unwrap())?;
736        let trait_ref = self.translate_trait_decl_ref(span, implemented_trait)?;
737        let impl_ref = if self.monomorphize() {
738            None
739        } else {
740            Some(self.translate_item(span, &impl_item)?)
741        };
742        Ok(GlobalSource::VTableInstance {
743            self_ty,
744            trait_ref,
745            impl_ref,
746        })
747    }
748
749    /// The shim to store in the next method field of a vtable.
750    fn vtable_method_value(
751        &mut self,
752        span: Span,
753        trait_id: TraitDeclId,
754        method_id: TraitMethodId,
755        implemented_trait: &front::TraitRef<'tcx>,
756        methods: &IndexVec<TraitMethodId, &front::ImplAssocItem<'tcx>>,
757    ) -> Result<VtableMethodValue, Error> {
758        let s = self.frontend_state_with_id();
759        let item = methods[method_id];
760        // The method is vtable safe so it has no generics, hence we can skip the binder.
761        let item_ref = match &item.value {
762            Some(value) => value.skip_binder.item.clone(),
763            // The impl doesn't provide this method, so we get the trait's default.
764            None => {
765                let trait_args = implemented_trait.rustc_args(s);
766                front::ItemRef::translate_from_frontend_def_id(
767                    s,
768                    item.decl_def_id.clone(),
769                    trait_args,
770                )
771            }
772        };
773        let shim_item = item_ref.make_derived(s, front::DerivedItemKind::VTableMethodShim);
774        let shim = self.translate_fn_ptr(span, &shim_item)?;
775
776        // In mono mode the vtable fields are erased pointers, so we must compute the real type of
777        // each shim to cast it from.
778        if !self.monomorphize() {
779            return Ok(VtableMethodValue::Const(shim));
780        }
781
782        // Manually translate region params for dyn trait.
783        // We create a new binding level by `translate_item_generics`
784        // and restore the orginal one after computing `method_ty`.
785        assert!(self.binding_levels.len() == 1);
786        let orginal_binding = self.binding_levels.pop();
787        let assoc_fun_def = self.frontend_def(&shim_item)?;
788        self.translate_item_generics(span, &assoc_fun_def)?;
789        let sig = assoc_fun_def.kind().as_fn().unwrap().sig();
790        let signature = self.translate_fun_sig(span, &sig.value)?;
791        // Add regions. this is ad-hoc...
792        let method_ty = Ty::new(TyKind::FnPtr(RegionBinder {
793            regions: self.outermost_generics().regions.clone(),
794            outlives: self.outermost_generics().outlives.clone(),
795            skip_binder: signature,
796        }));
797
798        // Restore the orignal binding_levels.
799        self.binding_levels.pop();
800        if let Some(binding_level) = orginal_binding {
801            self.binding_levels.push(binding_level);
802        }
803
804        self.mark_method_as_used(trait_id, method_id);
805        Ok(VtableMethodValue::Cast(method_ty, shim))
806    }
807
808    /// Generate the vtable value.
809    /// ```
810    /// global {impl Trait for Foo}::vtable<Args..>: Trait::{vtable}<TraitArgs.., AssocTys..> {
811    ///     size: size_of(Foo),
812    ///     align: align_of(Foo),
813    ///     drop: <Foo as Destruct>::drop_glue,
814    ///     method_0: <Foo as Trait>::method_0::{shim},
815    ///     method_1: <Foo as Trait>::method_1::{shim},
816    ///     ...
817    ///     super_trait_0: SuperImpl0<..>::{vtable_instance}::<..>,
818    ///     super_trait_1: SuperImpl1<..>::{vtable_instance}::<..>,
819    ///     ...
820    /// }
821    /// ```
822    pub(crate) fn gen_vtable_value(
823        &mut self,
824        span: Span,
825        vtable_def: &front::FullDef<'tcx>,
826        vtable_struct_ref: TypeDeclRef,
827    ) -> Result<ConstantExprKind, Error> {
828        let impl_ref = vtable_def.this().peel_derived(self.frontend_state());
829        let impl_def = self.frontend_def(&impl_ref)?;
830        let timpl = impl_def.kind().as_trait_impl().unwrap();
831        let implemented_trait_ref = &timpl.trait_pred().trait_ref;
832        let implied_trait_proofs = timpl.implied_trait_proofs();
833        let methods: IndexVec<TraitMethodId, _> = timpl
834            .items(self.frontend_state_with_id())
835            .iter()
836            .filter(|item| matches!(item.decl_def_id.kind, front::DefKind::AssocFn))
837            .collect();
838        let trait_def = self.frontend_def(implemented_trait_ref)?;
839        // We use `poly_trait_def` to fetch `implied_preds`, which is used to fetch supertrait in `prepare_vtable_fields`.
840        let poly_trait_def = self.poly_frontend_def(&implemented_trait_ref.def_id)?;
841        let implied_predicates = match poly_trait_def.kind() {
842            front::FullDefKind::Trait(t) => t.implied_predicates(),
843            front::FullDefKind::TraitAlias(t) => t.implied_predicates(),
844            _ => unreachable!(),
845        };
846
847        let implemented_trait = self.translate_trait_decl_ref(span, implemented_trait_ref)?;
848        let trait_id = implemented_trait.id;
849        // The type this impl is for.
850        let self_ty = &implemented_trait.generics.types[0];
851
852        let vtable_data =
853            self.prepare_vtable_fields(&poly_trait_def, trait_id, implied_predicates)?;
854        // Retrieve the expected field types from the struct definition. This avoids complicated
855        // substitutions.
856        let field_tys = {
857            let ItemRef::Type(vtable_def) =
858                self.t_ctx.get_or_translate(vtable_struct_ref.id.into())?
859            else {
860                unreachable!()
861            };
862            let fields = match &vtable_def.kind {
863                TypeDeclKind::Struct(fields) => fields,
864                TypeDeclKind::Opaque => {
865                    return Ok(ConstantExprKind::Opaque(
866                        "VTable was chosen to be opaque".to_string(),
867                    ));
868                }
869                TypeDeclKind::Error(error) => return Err(Error::new(span, error.clone())),
870                _ => unreachable!(),
871            };
872            fields
873                .iter()
874                .map(|f| &f.ty)
875                .cloned()
876                .map(|ty| ty.substitute(&vtable_struct_ref.generics))
877                .collect_vec()
878        };
879
880        // Construct a list with one operand per vtable field.
881        let mut aggregate_fields = IndexVec::new();
882        for (field, ty) in vtable_data.fields.into_iter().zip(field_tys) {
883            let mk = |kind| ConstantExpr::new(kind, ty.clone());
884            let constant = match field {
885                TrVTableField::Size => mk(ConstantExprKind::SizeOf(self_ty.clone())),
886                TrVTableField::Align => mk(ConstantExprKind::AlignOf(self_ty.clone())),
887                TrVTableField::Drop => {
888                    let s = self.frontend_state_with_id();
889                    let drop_shim = self.translate_item(
890                        span,
891                        &impl_ref.make_derived(s, front::DerivedItemKind::VTableDropShim),
892                    )?;
893                    if self.monomorphize() {
894                        let dyn_self = match trait_def.kind() {
895                            front::FullDefKind::Trait(t) => t.dyn_self(),
896                            front::FullDefKind::TraitAlias(t) => t.dyn_self(),
897                            _ => unreachable!(),
898                        }
899                        .expect("vtable trait must be dyn-compatible");
900                        let dyn_self = self.translate_ty(span, dyn_self)?;
901                        let shim_ty = TyKind::FnPtr(self.drop_glue_fn_ptr_sig(dyn_self)).into_ty();
902                        let shim =
903                            ConstantExpr::new(ConstantExprKind::FnPtr(drop_shim), shim_ty.clone());
904                        mk(ConstantExprKind::Cast(shim, CastKind::RawPtr(ty.clone())))
905                    } else {
906                        mk(ConstantExprKind::FnPtr(drop_shim))
907                    }
908                }
909                TrVTableField::Method(method_id, ..) => {
910                    let value = self.vtable_method_value(
911                        span,
912                        trait_id,
913                        method_id,
914                        implemented_trait_ref,
915                        &methods,
916                    )?;
917                    match value {
918                        VtableMethodValue::Const(method) => mk(ConstantExprKind::FnPtr(method)),
919                        VtableMethodValue::Cast(cast_ty, method) => {
920                            let method =
921                                ConstantExpr::new(ConstantExprKind::FnPtr(method), cast_ty.clone());
922                            mk(ConstantExprKind::Cast(method, CastKind::RawPtr(ty.clone())))
923                        }
924                    }
925                }
926                TrVTableField::SuperTrait(clause_id, _) => {
927                    let trait_proof = &implied_trait_proofs[clause_id.index()];
928                    self.translate_vtable_instance_const(span, trait_proof)?
929                }
930            };
931            aggregate_fields.push(constant);
932        }
933
934        Ok(ConstantExprKind::Adt(None, aggregate_fields))
935    }
936
937    /// The target vtable shim body looks like:
938    /// ```ignore
939    /// local ret@0 : ReturnTy;
940    /// // the shim receiver of this shim function
941    /// local shim_self@1 : ShimReceiverTy;
942    /// // the arguments of the impl function
943    /// local arg1@2 : Arg1Ty;
944    /// ...
945    /// local argN@N : ArgNTy;
946    /// // the target receiver of the impl function
947    /// local target_self@(N+1) : TargetReceiverTy;
948    /// // perform some conversion to cast / re-box the shim receiver to the target receiver
949    /// ...
950    /// target_self@(N+1) := concretize<TargetReceiverTy>(shim_self@1);
951    /// // call the impl function and assign the result to ret@0
952    /// ret@0 := impl_func(target_self@(N+1), arg1@2, ..., argN@N);
953    /// ```
954    ///
955    /// For a method that takes `self: Self` by value, the shim receiver is `*mut dyn Trait`, so
956    /// we concretize the pointer and move out of it:
957    /// ```ignore
958    /// target_self@(N+1) := concretize<*mut TargetReceiverTy>(shim_self@1);
959    /// ret@0 := impl_func(move (*target_self@(N+1)), arg1@2, ..., argN@N);
960    /// ```
961    pub(crate) fn translate_vtable_shim_body(
962        &mut self,
963        span: Span,
964        def: &front::FullDef<'tcx>,
965        signature: &FunSig,
966    ) -> Result<Body, Error> {
967        let s = self.frontend_state();
968
969        let method_ref = def.this().peel_derived(s);
970        let method_def = self.frontend_def(&method_ref)?;
971        let front::FullDefKind::AssocFn(f) = method_def.kind() else {
972            raise_error!(
973                self,
974                span,
975                "Trying to generate a vtable shim for a non-vtable-safe method"
976            );
977        };
978        // The concrete receiver we will cast to.
979        let target_receiver = self.translate_ty(span, &f.sig().value.inputs[0])?;
980        let receiver_is_by_value = f.vtable_receiver_is_by_value(self.frontend_state());
981        // The path to the pointer carrying the vtable in the receiver.
982        let receiver_path =
983            self.translate_metadata_path(&f.vtable_receiver_path(self.frontend_state()));
984
985        trace!(
986            "[VtableShim] Obtained dyn signature with receiver type: {}",
987            signature.inputs[0].with_ctx(&self.into_fmt())
988        );
989
990        let fun_id = self.register_item(span, &method_ref);
991        let target_fn = FnPtr::new(
992            FnPtrKind::Fun(fun_id),
993            self.outermost_binder().params.identity_args(),
994        );
995
996        let mut builder = BodyBuilder::new(span, signature.inputs.len());
997
998        let ret_place = builder.new_var(None, signature.output.clone());
999        let mut method_args = signature
1000            .inputs
1001            .iter()
1002            .map(|ty| builder.new_var(None, ty.clone()))
1003            .collect_vec();
1004
1005        let cast_target_ty = if receiver_is_by_value {
1006            TyKind::RawPtr(target_receiver.clone(), RefKind::Mut).into_ty()
1007        } else {
1008            target_receiver.clone()
1009        };
1010        let target_self = builder.new_var(None, cast_target_ty);
1011
1012        // Replace the `dyn Trait` receiver with the concrete one.
1013        let receiver_arg = if receiver_is_by_value {
1014            target_self.clone().deref()
1015        } else {
1016            target_self.clone()
1017        };
1018        let shim_self = mem::replace(&mut method_args[0], receiver_arg);
1019
1020        // Perform the core concretization cast.
1021        // FIXME: need to unpack & re-pack the structure for cases like `Rc`, `Arc`, `Pin` and
1022        // (when --raw-boxes is on) `Box`
1023        let rval = Rvalue::UnaryOp(
1024            UnOp::Cast(CastKind::Concretize(
1025                target_self.ty().clone(),
1026                receiver_path,
1027            )),
1028            Operand::Move(shim_self.clone()),
1029        );
1030        builder.push_statement(StatementKind::Assign(target_self.clone(), rval));
1031
1032        builder.call(
1033            ret_place,
1034            Call {
1035                func: FnOperand::Regular(target_fn),
1036                args: method_args.into_iter().map(Operand::Move).collect(),
1037                safety: CallSafety::Inherit,
1038            },
1039        );
1040
1041        Ok(Body::Unstructured(builder.build()))
1042    }
1043
1044    /// The target vtable drop_shim body looks like:
1045    /// ```ignore
1046    /// local ret@0 : ();
1047    /// // the shim receiver of this drop_shim function
1048    /// local shim_self@1 : ShimReceiverTy;
1049    /// // the target receiver of the drop_shim
1050    /// local target_self@2 : TargetReceiverTy;
1051    /// // perform some conversion to cast / re-box the drop_shim receiver to the target receiver
1052    /// target_self@2 := concretize<TargetReceiverTy>(shim_self@1);
1053    /// Drop(*target_self@2);
1054    /// ```
1055    pub(crate) fn translate_vtable_drop_shim_body(
1056        &mut self,
1057        span: Span,
1058        def: &front::FullDef<'tcx>,
1059        signature: &FunSig,
1060    ) -> Result<Body, Error> {
1061        let impl_ref = def.this().peel_derived(self.frontend_state());
1062        let impl_def = self.frontend_def(&impl_ref)?;
1063        let trait_pred = impl_def.kind().as_trait_impl().unwrap().trait_pred();
1064        let TyKind::Ref(borrow_region, _, _) = signature.inputs[0].kind() else {
1065            unreachable!();
1066        };
1067
1068        // `&mut T` for `impl Trait for T`
1069        let target_self_ref = {
1070            let impl_trait = self.translate_trait_ref(span, &trait_pred.trait_ref)?;
1071            TyKind::Ref(
1072                borrow_region.clone(),
1073                impl_trait.generics.types[0].clone(),
1074                RefKind::Mut,
1075            )
1076            .into_ty()
1077        };
1078
1079        let mut builder = BodyBuilder::new(span, 1);
1080
1081        let ret = builder.new_var(Some("ret".into()), Ty::mk_unit());
1082        builder.push_statement(StatementKind::Assign(ret, Rvalue::unit_value()));
1083        let dyn_self = builder.new_var(Some("dyn_self".into()), signature.inputs[0].clone());
1084        let target_self = builder.new_var(Some("target_self".into()), target_self_ref);
1085
1086        // Perform the core concretization cast.
1087        let rval = Rvalue::UnaryOp(
1088            UnOp::Cast(CastKind::Concretize(
1089                target_self.ty().clone(),
1090                MetadataPath::new(),
1091            )),
1092            Operand::Move(dyn_self.clone()),
1093        );
1094        builder.push_statement(StatementKind::Assign(target_self.clone(), rval));
1095
1096        let rustc_trait_args = trait_pred
1097            .trait_ref
1098            .rustc_args(self.frontend_state_with_id());
1099        let rustc_self_ty = rustc_trait_args[0].as_type().unwrap();
1100        let fn_ptr = self.translate_drop_glue_method_call(span, rustc_self_ty)?;
1101
1102        // Drop(*target_self)
1103        let drop_arg = target_self.clone().deref();
1104        builder.insert_drop(drop_arg, fn_ptr);
1105
1106        Ok(Body::Unstructured(builder.build()))
1107    }
1108}