Skip to main content

charon_driver/translate/
translate_virtual_impls.rs

1//! Virtual impls are trait impls that rustc considers to exist but which don't have a `DefId`. We generate
2//! a `TraitImpl` and method ourselves, as if they had been normal source-code impls.
3use super::translate_ctx::*;
4use crate::hax;
5use crate::translate::translate_crate::{TransItemSourceKind, VirtualImplKind};
6use charon_lib::ast::*;
7
8impl VirtualImplKind {
9    pub fn virtual_trait(self) -> hax::VirtualTrait {
10        match self {
11            VirtualImplKind::Destruct => hax::VirtualTrait::Destruct,
12            VirtualImplKind::Callable(ClosureKind::FnOnce) => hax::VirtualTrait::FnOnce,
13            VirtualImplKind::Callable(ClosureKind::FnMut) => hax::VirtualTrait::FnMut,
14            VirtualImplKind::Callable(ClosureKind::Fn) => hax::VirtualTrait::Fn,
15        }
16    }
17
18    /// Whether the method we generate takes `self` by reference. If so, it takes an extra lifetime
19    /// parameter for that borrow.
20    pub fn has_self_borrow(self) -> bool {
21        !matches!(self, VirtualImplKind::Callable(ClosureKind::FnOnce))
22    }
23
24    /// The name of the method we generate.
25    pub fn method_path_elem(self) -> PathElem {
26        match self {
27            VirtualImplKind::Destruct => {
28                PathElem::Builtin(BuiltinPathElem::DropGlue, Disambiguator::ZERO)
29            }
30            VirtualImplKind::Callable(kind) => {
31                PathElem::Ident(kind.method_name().into(), Disambiguator::ZERO)
32            }
33        }
34    }
35}
36
37impl<'tcx> ItemTransCtx<'tcx, '_> {
38    fn virtual_method_id(
39        &mut self,
40        kind: VirtualImplKind,
41        vimpl: &hax::VirtualTraitImpl<'tcx>,
42        trait_id: TraitDeclId,
43    ) -> Result<TraitMethodId, Error> {
44        match kind {
45            // Destruct doesn't have a method but we give it a fake one.
46            VirtualImplKind::Destruct => {
47                self.translate_drop_glue_method_id(&vimpl.trait_pred.trait_ref.def_id, trait_id)
48            }
49            _ => self.translate_trait_method_id(trait_id, &vimpl.methods[0].def_id),
50        }
51    }
52
53    fn virtual_method_sig(
54        &mut self,
55        kind: VirtualImplKind,
56        span: Span,
57        vimpl: &hax::VirtualTraitImpl<'tcx>,
58        self_ty: Ty,
59    ) -> Result<FunSig, Error> {
60        let self_borrow_region = self
61            .the_only_binder()
62            .self_borrow_region
63            .map(|rid| Region::Var(DeBruijnVar::new_at_zero(rid)));
64        Ok(match kind {
65            // Destruct doesn't have a method but we give it a fake one.
66            VirtualImplKind::Destruct => {
67                self.drop_glue_method_sig(self_ty, self_borrow_region.unwrap())
68            }
69            _ => self
70                .translate_poly_fun_sig(span, &vimpl.methods[0].sig)?
71                .apply(self_borrow_region.into_iter().collect()),
72        })
73    }
74
75    fn virtual_method_body(
76        &mut self,
77        kind: VirtualImplKind,
78        span: Span,
79        def: &hax::FullDef<'tcx>,
80        signature: &FunSig,
81    ) -> Result<Body, Error> {
82        match kind {
83            VirtualImplKind::Destruct => self.translate_drop_glue_method_body(span, def),
84            VirtualImplKind::Callable(target_kind) => {
85                self.translate_callable_method_body(span, def, target_kind, signature)
86            }
87        }
88    }
89
90    #[tracing::instrument(skip(self, item_meta, def))]
91    pub fn translate_virtual_impl(
92        mut self,
93        impl_id: TraitImplId,
94        item_meta: ItemMeta,
95        def: &hax::FullDef<'tcx>,
96        kind: VirtualImplKind,
97    ) -> Result<TraitImpl, Error> {
98        let span = item_meta.span;
99        let vimpl = def.virtual_impl(self.hax_state(), kind.virtual_trait());
100        let mut timpl = self.translate_virtual_trait_impl(
101            impl_id,
102            item_meta,
103            def.this(),
104            TransImplSource::Virtual(kind),
105            vimpl,
106        )?;
107
108        // In mono mode trait decls have no methods except `Desctruct::drop_glue`
109        if self.monomorphize() && kind != VirtualImplKind::Destruct {
110            return Ok(timpl);
111        }
112
113        // Add the method we generate. It takes the impl generics, plus a lifetime for the borrow
114        // of `self` if it takes `self` by reference.
115        let trait_id = timpl.impl_trait.id;
116        let method_id = self.virtual_method_id(kind, vimpl, trait_id)?;
117        let method_binder = {
118            let fun_id =
119                self.register_item(span, def.this(), TransItemSourceKind::VirtualMethod(kind));
120            let method_params = if kind.has_self_borrow() {
121                Self::self_borrow_params()
122            } else {
123                GenericParams::empty()
124            };
125            let generics = self
126                .outermost_binder()
127                .params
128                .identity_args_at_depth(DeBruijnId::one())
129                .concat(&method_params.identity_args());
130            Binder::new(
131                BinderKind::TraitMethod(trait_id, method_id),
132                method_params,
133                FunDeclRef {
134                    id: fun_id,
135                    generics: Box::new(generics),
136                },
137            )
138        };
139        timpl.methods.set_slot_extend(method_id, method_binder);
140
141        Ok(timpl)
142    }
143
144    /// Translate the method we generate for a virtual impl.
145    #[tracing::instrument(skip(self, item_meta, def))]
146    pub fn translate_virtual_method(
147        mut self,
148        def_id: FunDeclId,
149        item_meta: ItemMeta,
150        def: &hax::FullDef<'tcx>,
151        kind: VirtualImplKind,
152    ) -> Result<FunDecl, Error> {
153        let span = item_meta.span;
154        let vimpl = def.virtual_impl(self.hax_state(), kind.virtual_trait());
155        let trait_pred = &vimpl.trait_pred;
156        let implemented_trait = self.translate_trait_predicate(span, trait_pred)?;
157        let item_id = self.virtual_method_id(kind, vimpl, implemented_trait.id)?;
158        let self_ty = implemented_trait
159            .self_ty(&self.t_ctx.translated)
160            .unwrap()
161            .clone();
162        let signature = self.virtual_method_sig(kind, span, vimpl, self_ty)?;
163
164        let src = {
165            let mut impl_generics = self.the_only_binder().params.identity_args();
166            if kind.has_self_borrow() {
167                impl_generics.regions.pop();
168            }
169            let impl_id = self.register_item(
170                span,
171                def.this(),
172                TransItemSourceKind::TraitImpl(TransImplSource::Virtual(kind)),
173            );
174            FunSource::TraitImpl {
175                impl_ref: TraitImplRef {
176                    id: impl_id,
177                    generics: Box::new(impl_generics),
178                },
179                trait_ref: implemented_trait,
180                item_id,
181                reuses_default: false,
182            }
183        };
184
185        let body = if item_meta.opacity.with_private_contents().is_opaque() {
186            Body::Opaque
187        } else {
188            self.virtual_method_body(kind, span, def, &signature)?
189        };
190
191        Ok(FunDecl {
192            def_id,
193            item_meta,
194            generics: self.into_generics(),
195            signature: Box::new(signature),
196            src,
197            body,
198        })
199    }
200}