Skip to main content

charon_driver/translate/
translate_closures.rs

1//! In rust, closures behave like ADTs that implement the FnOnce/FnMut/Fn traits automatically.
2//! Function item types also implement those traits automatically.
3//!
4//! Here we convert closures to a struct containing the closure's state (upvars), along with
5//! matching trait impls and fun decls (e.g. a Fn closure will have a trait impl for Fn, FnMut and
6//! FnOnce, along with 3 matching method implementations for call, call_mut and call_once).
7//! Function item types reuse the same generated trait impls and methods, with an empty state that
8//! forwards to the original function item.
9//!
10//! For example, given the following Rust code:
11//! ```ignore
12//! pub fn test_closure_capture<T: Clone>() {
13//!     let mut v = vec![];
14//!     let mut add = |x: &u32| v.push(*x);
15//!     add(&0);
16//!     add(&1);
17//! }
18//! ```
19//!
20//! We generate the equivalent desugared code:
21//! ```text
22//! struct {test_closure_capture::closure#0}<'a, T: Clone> (&'a mut Vec<u32>);
23//!
24//! // The 'a comes from captured variables, the 'b comes from the closure higher-kinded signature.
25//! impl<'a, 'b, T: Clone> FnMut<(&'b u32,)> for {test_closure_capture::closure#0}<'a, T> {
26//!     fn call_mut<'c>(&'c mut self, arg: (&'b u32,)) {
27//!         self.0.push(*arg.0);
28//!     }
29//! }
30//!
31//! impl<'a, 'b, T: Clone> FnOnce<(&'b u32,)> for {test_closure_capture::closure#0}<'a, T> {
32//!     type Output = ();
33//!     ...
34//! }
35//!
36//! pub fn test_closure_capture<T: Clone>() {
37//!     let mut v = vec![];
38//!     let mut add = {test_closure_capture::closure#0} (&mut v);
39//!     state.call_mut(&0);
40//!     state.call_mut(&1);
41//! }
42//! ```
43
44use crate::frontend as front;
45use itertools::Itertools;
46use std::mem;
47
48use super::translate_ctx::*;
49use charon_lib::ullbc_ast::*;
50
51pub fn translate_closure_kind(kind: &front::ClosureKind) -> ClosureKind {
52    match kind {
53        front::ClosureKind::Fn => ClosureKind::Fn,
54        front::ClosureKind::FnMut => ClosureKind::FnMut,
55        front::ClosureKind::FnOnce => ClosureKind::FnOnce,
56    }
57}
58
59impl From<ClosureKind> for front::ClosureKind {
60    fn from(kind: ClosureKind) -> Self {
61        match kind {
62            ClosureKind::Fn => Self::Fn,
63            ClosureKind::FnMut => Self::FnMut,
64            ClosureKind::FnOnce => Self::FnOnce,
65        }
66    }
67}
68
69/// If this trait proof is a built-in impl of a `Fn*` trait, return the `Self` type it is
70/// implemented for and the kind of the implemented trait.
71pub fn recognize_fn_trait_impl_proof<'a, 'tcx>(
72    trait_proof: &'a front::TraitProof<'tcx>,
73) -> Option<(front::Binder<&'a front::Ty<'tcx>>, ClosureKind)> {
74    let front::TraitProofKind::Builtin {
75        trait_data: front::BuiltinTraitData::Other(lang_item),
76        ..
77    } = &trait_proof.kind
78    else {
79        return None;
80    };
81    let kind = match lang_item {
82        front::SolverTraitLangItem::FnOnce => ClosureKind::FnOnce,
83        front::SolverTraitLangItem::FnMut => ClosureKind::FnMut,
84        front::SolverTraitLangItem::Fn => ClosureKind::Fn,
85        _ => return None,
86    };
87    let Some(front::GenericArg::Type(self_ty)) = trait_proof
88        .pred
89        .frontend_skip_binder_ref()
90        .generic_args
91        .first()
92    else {
93        unreachable!("no `Self` type arg on a `Fn*` trait ref")
94    };
95    Some((trait_proof.pred.rebind(self_ty), kind))
96}
97
98#[derive(Copy, Clone)]
99enum CallableKind {
100    Closure(ClosureKind),
101    FnDef,
102    FnPtr,
103}
104
105#[derive(Copy, Clone)]
106struct Callable<'tcx, 'a> {
107    kind: CallableKind,
108    item: &'a front::ItemRef<'tcx>,
109    sig: &'a front::PolyFnSig<'tcx>,
110}
111
112impl<'tcx, 'a> Callable<'tcx, 'a> {
113    fn for_closure(
114        s: &impl front::BaseState<'tcx>,
115        closure: &'a front::ClosureTy<'tcx>,
116        sig: &'a front::PolyFnSig<'tcx>,
117    ) -> Self {
118        Self {
119            item: &closure.item,
120            kind: CallableKind::Closure(translate_closure_kind(&closure.kind(s))),
121            sig,
122        }
123    }
124
125    fn for_closure_def(def: &'a front::FullDef<'tcx>) -> Self {
126        let closure = def.kind().as_closure().unwrap();
127        Self {
128            item: def.this(),
129            kind: CallableKind::Closure(translate_closure_kind(closure.kind())),
130            sig: closure.sig(),
131        }
132    }
133
134    fn from_def(def: &'a front::FullDef<'tcx>) -> Option<Self> {
135        let (kind, sig) = match def.kind() {
136            front::FullDefKind::Closure(_) => return Some(Self::for_closure_def(def)),
137            front::FullDefKind::Fn(f) => (CallableKind::FnDef, f.sig()),
138            front::FullDefKind::AssocFn(f) => (CallableKind::FnDef, f.sig()),
139            front::FullDefKind::Ctor(f) => (CallableKind::FnDef, f.sig()),
140            front::FullDefKind::FnPtr(f) => (CallableKind::FnPtr, f.sig()),
141            _ => return None,
142        };
143        Some(Self {
144            kind,
145            item: def.this(),
146            sig,
147        })
148    }
149
150    fn kind(self) -> CallableKind {
151        self.kind
152    }
153
154    fn item(self) -> &'a front::ItemRef<'tcx> {
155        self.item
156    }
157
158    fn sig(self) -> &'a front::PolyFnSig<'tcx> {
159        self.sig
160    }
161}
162
163/// References to callable items are subtle because there are three sources of lifetimes on top of
164/// the normal generics: closure upvars, the higher-kindedness of the callable itself, and the
165/// late-bound generics of the `call`/`call_mut` methods. One must be careful to choose the right
166/// method from these.
167impl<'tcx> ItemTransCtx<'tcx, '_> {
168    /// Translate a reference to a callable item that takes late-bound lifetimes. The binder binds
169    /// the late-bound lifetimes of the callable itself, if it is higher-kinded.
170    fn translate_callable_bound_ref_with_late_bound(
171        &mut self,
172        span: Span,
173        callable: Callable<'tcx, '_>,
174    ) -> Result<RegionBinder<DeclRef<ItemId>>, Error> {
175        if !matches!(
176            callable.item().def_id.as_derived(),
177            Some(front::DerivedItemKind::FnImpl(_) | front::DerivedItemKind::ClosureAsFnCast)
178        ) {
179            raise_error!(
180                self,
181                span,
182                "Called `translate_callable_bound_ref_with_late_bound` on `{:?}`; \
183                use `translate_closure_ref_with_upvars` instead",
184                callable.item().def_id
185            )
186        }
187        let dref: DeclRef<ItemId> = self.translate_item(span, callable.item())?;
188        self.translate_region_binder(span, callable.sig(), |ctx, _| {
189            let mut dref = dref.move_under_binder();
190            // The regions for these item kinds have the fn late bound regions at the end.
191            dref.generics
192                .set_trailing_regions_to_identity(&ctx.innermost_binder().params);
193            Ok(dref)
194        })
195    }
196}
197
198impl<'tcx> ItemTransCtx<'tcx, '_> {
199    /// Translate a reference to the closure ADT.
200    pub fn translate_closure_type_ref(
201        &mut self,
202        span: Span,
203        closure: &front::ItemRef<'tcx>,
204    ) -> Result<TypeDeclRef, Error> {
205        self.translate_type_decl_ref(span, closure)
206    }
207
208    /// For stateless closures, translate a function reference to the top-level function that
209    /// executes the closure code without taking the state as parameter.If you want to instantiate
210    /// the binder, use the lifetimes from `self.closure_late_regions`.
211    pub fn translate_stateless_closure_as_fn_ref(
212        &mut self,
213        span: Span,
214        closure: &front::ClosureTy<'tcx>,
215    ) -> Result<RegionBinder<FunDeclRef>, Error> {
216        let item = closure.item.make_derived(
217            self.frontend_state_with_id(),
218            front::DerivedItemKind::ClosureAsFnCast,
219        );
220        let sig = closure.fn_sig(self.frontend_state());
221        let callable = Callable {
222            item: &item,
223            ..Callable::for_closure(self.frontend_state(), closure, &sig)
224        };
225        let bound_dref = self.translate_callable_bound_ref_with_late_bound(span, callable)?;
226        Ok(bound_dref.map(|dref| dref.try_into().unwrap()))
227    }
228
229    /// Translate a reference to the chosen closure impl. The resulting value needs lifetime
230    /// arguments for late-bound lifetimes. If you want to instantiate the binder, use the
231    /// lifetimes from `self.closure_late_regions`.
232    pub fn translate_closure_bound_impl_ref(
233        &mut self,
234        span: Span,
235        def: &front::FullDef<'tcx>,
236        target_kind: ClosureKind,
237    ) -> Result<RegionBinder<TraitImplRef>, Error> {
238        let impl_item = def.this().make_derived(
239            self.frontend_state_with_id(),
240            front::DerivedItemKind::FnImpl(target_kind.into()),
241        );
242        let callable = Callable {
243            item: &impl_item,
244            ..Callable::for_closure_def(def)
245        };
246        let bound_dref = self.translate_callable_bound_ref_with_late_bound(span, callable)?;
247        Ok(bound_dref.map(|dref| dref.try_into().unwrap()))
248    }
249
250    /// Translate a reference to the chosen callable impl.
251    pub fn translate_callable_impl_ref(
252        &mut self,
253        span: Span,
254        item: &front::ItemRef<'tcx>,
255        target_kind: ClosureKind,
256    ) -> Result<TraitImplRef, Error> {
257        let item = item.make_derived(
258            self.frontend_state_with_id(),
259            front::DerivedItemKind::FnImpl(target_kind.into()),
260        );
261        self.translate_item(span, &item)
262    }
263
264    pub fn translate_closure_info(
265        &mut self,
266        span: Span,
267        def: &front::FullDef<'tcx>,
268    ) -> Result<ClosureInfo, Error> {
269        use ClosureKind::*;
270        let closure = def.kind().as_closure().unwrap();
271        let kind = translate_closure_kind(closure.kind());
272
273        let method_item = def
274            .this()
275            .make_derived_fn_call_method(self.frontend_state_with_id(), kind.into());
276        let closure_body = self.translate_item(span, &method_item)?;
277
278        let fn_once_impl = self.translate_closure_bound_impl_ref(span, def, FnOnce)?;
279        let fn_mut_impl = if matches!(kind, FnMut | Fn) {
280            Some(self.translate_closure_bound_impl_ref(span, def, FnMut)?)
281        } else {
282            None
283        };
284        let fn_impl = if matches!(kind, Fn) {
285            Some(self.translate_closure_bound_impl_ref(span, def, Fn)?)
286        } else {
287            None
288        };
289        let signature = self.translate_poly_fun_sig(span, closure.sig())?;
290        Ok(ClosureInfo {
291            kind,
292            closure_body,
293            fn_once_impl,
294            fn_mut_impl,
295            fn_impl,
296            signature,
297        })
298    }
299
300    fn get_callable_state_ty(
301        &mut self,
302        span: Span,
303        callable: Callable<'tcx, '_>,
304    ) -> Result<Ty, Error> {
305        Ok(match callable.kind() {
306            CallableKind::Closure(..) => {
307                let tref = self.translate_closure_type_ref(span, callable.item())?;
308                TyKind::Adt(tref).into_ty()
309            }
310            CallableKind::FnDef => {
311                let fn_ref = self.translate_bound_fn_ptr(span, callable.item())?;
312                TyKind::FnDef(fn_ref).into_ty()
313            }
314            CallableKind::FnPtr => {
315                TyKind::FnPtr(self.translate_poly_fun_sig(span, callable.sig())?).into_ty()
316            }
317        })
318    }
319
320    pub fn translate_closure_adt(
321        &mut self,
322        span: Span,
323        closure: &front::Closure<'tcx>,
324    ) -> Result<TypeDeclKind, Error> {
325        let fields = closure
326            .upvar_tys()
327            .iter()
328            .enumerate()
329            .map(|(field_id, ty)| -> Result<_, Error> {
330                Ok(Field {
331                    span,
332                    attr_info: AttrInfo::dummy_private(),
333                    name: format!("_{field_id}"),
334                    is_positional: true,
335                    ty: self.translate_ty(span, ty)?,
336                })
337            })
338            .try_collect()?;
339        Ok(TypeDeclKind::Struct(fields))
340    }
341
342    pub(crate) fn translate_callable_method_body(
343        &mut self,
344        span: Span,
345        method_def: &front::FullDef<'tcx>,
346        target_kind: ClosureKind,
347        signature: &FunSig,
348    ) -> Result<Body, Error> {
349        let base = method_def.this().derived_base(self.frontend_state());
350        let def = &self.frontend_def(&base)?;
351        let callable = Callable::from_def(def).unwrap();
352        match callable.kind() {
353            CallableKind::Closure(source_kind) => self.translate_closure_method_body(
354                span,
355                def,
356                source_kind,
357                target_kind,
358                &callable.item().derived_base(self.frontend_state()),
359                signature,
360            ),
361            CallableKind::FnDef | CallableKind::FnPtr => {
362                let method = method_def.kind().as_assoc_fn().unwrap();
363                let Some(body) = method.shim_body(self.frontend_state()) else {
364                    panic!("missing shim for function item or pointer")
365                };
366                Ok(self.translate_body(span, body, &def.source_text(self.tcx)))
367            }
368        }
369    }
370
371    fn translate_closure_method_body(
372        &mut self,
373        span: Span,
374        def: &front::FullDef<'tcx>,
375        source_kind: ClosureKind,
376        target_kind: ClosureKind,
377        closure: &front::ItemRef<'tcx>,
378        signature: &FunSig,
379    ) -> Result<Body, Error> {
380        use ClosureKind::*;
381        Ok(match (target_kind, source_kind) {
382            (Fn, Fn) | (FnMut, FnMut) | (FnOnce, FnOnce) => {
383                // Translate the function's body normally
384                let mut body = self.translate_def_body(span, def);
385                // The body is translated as if the locals are: ret value, state, arg-1,
386                // ..., arg-N, rest...
387                // However, there is only one argument with the tupled closure arguments;
388                // we must thus shift all locals with index >=2 by 1, and add a new local
389                // for the tupled arg, giving us: ret value, state, args, arg-1, ...,
390                // arg-N, rest...
391                // We then add N statements of the form `locals[N+3] := move locals[2].N`,
392                // to destructure the arguments.
393                let Body::Unstructured(inner_body) = &mut body else {
394                    return Ok(body);
395                };
396
397                inner_body.dyn_visit_in_body_mut(|local: &mut LocalId| {
398                    if local.index() >= 2 {
399                        *local += 1;
400                    }
401                });
402
403                let GExprBody {
404                    locals,
405                    body: blocks,
406                    ..
407                } = inner_body;
408
409                // The (Arg1, Arg2, ..) type.
410                let tupled_ty = &signature.inputs[1];
411
412                // Remember how many arguments there are
413                let closure_arg_count = locals.arg_count - 1;
414                let mut old_locals = mem::take(&mut locals.locals).into_iter();
415                locals.arg_count = 2;
416                locals.locals.push(old_locals.next().unwrap()); // ret
417                locals.locals.push(old_locals.next().unwrap()); // state
418                let tupled_arg = locals.new_var(Some("tupled_args".to_string()), tupled_ty.clone());
419                locals.locals.extend(old_locals);
420
421                let untupled_args = locals
422                    .locals
423                    .iter()
424                    .skip(3)
425                    .take(closure_arg_count)
426                    .map(|l| &l.ty)
427                    .cloned();
428                let new_stts = untupled_args.enumerate().map(|(i, ty)| {
429                    let nth_field = tupled_arg
430                        .clone()
431                        .project(ProjectionElem::Field(None, FieldId::new(i)), ty);
432                    let local_id = LocalId::new(i + 3);
433                    Statement::new(
434                        span,
435                        StatementKind::Assign(
436                            locals.place_for_var(local_id),
437                            Rvalue::Use(Operand::Move(nth_field), WithRetag::No),
438                        ),
439                    )
440                });
441                blocks[BlockId::ZERO].statements.splice(0..0, new_stts);
442
443                body
444            }
445            // Target translation:
446            //
447            // fn call_once(state: Self, args: Args) -> Output {
448            //   let temp_ref = &[mut] state;
449            //   let ret = self.call[_mut](temp, args);
450            //   drop state;
451            //   return ret;
452            // }
453            //
454            (FnOnce, Fn | FnMut) => {
455                // The frontend (via rustc) gives us the MIR to do this.
456                let method_item = closure
457                    .make_derived_fn_call_method(self.frontend_state_with_id(), FnOnce.into());
458                let method_def = self.frontend_def(&method_item)?;
459                let method = method_def.kind().as_assoc_fn().unwrap();
460                let Some(body) = method.shim_body(self.frontend_state()) else {
461                    panic!("missing shim for closure")
462                };
463                let mut body = self.translate_body(span, body, &def.source_text(self.tcx));
464                if let Some(body) = body.as_unstructured_mut() {
465                    // The shim generated by rustc doesn't declare its receiver mutable.
466                    body.locals.locals[LocalId::new(1)].mutable = true;
467                }
468                body
469            }
470            // Target translation:
471            //
472            // fn call_mut(state: &mut Self, args: Args) -> Output {
473            //   let reborrow = &*state;
474            //   self.call(reborrow, args)
475            // }
476            (FnMut, Fn) => {
477                let method_item = closure
478                    .make_derived_fn_call_method(self.frontend_state_with_id(), source_kind.into());
479                let fun_id: FunDeclId = self.register_item(span, &method_item);
480                let impl_ref = self.translate_callable_impl_ref(span, closure, source_kind)?;
481                // TODO: make a trait call to avoid needing to concatenate things ourselves.
482                // TODO: can we ask the frontend for the trait ref?
483                let fn_op = FnOperand::Regular(FnPtr::new(
484                    fun_id.into(),
485                    impl_ref.generics.concat(&GenericArgs {
486                        regions: vec![self.translate_erased_region()].into(),
487                        ..GenericArgs::empty()
488                    }),
489                ));
490
491                let mut builder = BodyBuilder::new(span, 2);
492
493                let output = builder.new_var(None, signature.output.clone());
494                let state = builder.new_var(Some("state".to_string()), signature.inputs[0].clone());
495                let args = builder.new_var(Some("args".to_string()), signature.inputs[1].clone());
496                let deref_state = state.deref();
497                let reborrow_ty = TyKind::Ref(
498                    self.translate_erased_region(),
499                    deref_state.ty.clone(),
500                    RefKind::Shared,
501                )
502                .into_ty();
503                let reborrow = builder.new_var(None, reborrow_ty);
504
505                builder.push_statement(StatementKind::Assign(
506                    reborrow.clone(),
507                    Rvalue::Ref {
508                        place: deref_state,
509                        kind: BorrowKind::Shared,
510                        // The state must be Sized, hence `()` as ptr-metadata
511                        ptr_metadata: Operand::mk_const_unit(),
512                    },
513                ));
514
515                builder.call(
516                    output,
517                    Call {
518                        func: fn_op,
519                        args: vec![Operand::Move(reborrow), Operand::Move(args)],
520                        safety: CallSafety::Inherit,
521                    },
522                );
523
524                Body::Unstructured(builder.build())
525            }
526            (Fn, FnOnce) | (Fn, FnMut) | (FnMut, FnOnce) => {
527                panic!(
528                    "Can't make a closure body for a more restrictive kind \
529                    than the closure kind"
530                )
531            }
532        })
533    }
534
535    /// Given an item that is a non-capturing closure, generate the equivalent function,
536    /// by removing the state from the parameters and untupling the arguments.
537    #[tracing::instrument(skip(self, def, signature))]
538    pub(crate) fn translate_stateless_closure_as_fn_body(
539        &mut self,
540        span: Span,
541        def: &front::FullDef<'tcx>,
542        signature: &FunSig,
543    ) -> Result<Body, Error> {
544        let closure_item = def.this().peel_derived(self.frontend_state());
545        let base_def = self.frontend_def(&closure_item)?;
546        let closure = base_def.kind().as_closure().unwrap();
547
548        trace!("About to translate closure as fn:\n{:?}", def.def_id());
549
550        assert!(
551            closure.upvar_tys().is_empty(),
552            "Only stateless closures can be translated as functions"
553        );
554        let callable = Callable {
555            item: &closure_item,
556            ..Callable::for_closure_def(&base_def)
557        };
558        let state_ty = self.get_callable_state_ty(span, callable)?;
559
560        // Target translation:
561        //
562        // fn call_fn(arg0: Args[0], ..., argN: Args[N]) -> Output {
563        //   let closure: Closure = {};
564        //   let args = (arg0, ..., argN);
565        //   closure.call(args)
566        // }
567        let method_item = closure_item
568            .make_derived_fn_call_method(self.frontend_state_with_id(), front::ClosureKind::FnOnce);
569        let fun_id: FunDeclId = self.register_item(span, &method_item);
570        let impl_ref =
571            self.translate_callable_impl_ref(span, &closure_item, ClosureKind::FnOnce)?;
572        let fn_op = FnOperand::Regular(FnPtr::new(fun_id.into(), impl_ref.generics.clone()));
573
574        let mut builder = BodyBuilder::new(span, signature.inputs.len());
575
576        let output = builder.new_var(None, signature.output.clone());
577        let args: Vec<Place> = signature
578            .inputs
579            .iter()
580            .enumerate()
581            .map(|(i, ty)| builder.new_var(Some(format!("arg{}", i + 1)), ty.clone()))
582            .collect();
583        let args_tupled_ty =
584            self.translate_ty(span, &closure.tupled_inputs(&self.frontend_state))?;
585        let args_tupled = builder.new_var(Some("args".to_string()), args_tupled_ty.clone());
586        let state = builder.new_var(Some("state".to_string()), state_ty.clone());
587
588        builder.push_statement(StatementKind::Assign(
589            args_tupled.clone(),
590            Rvalue::Aggregate(
591                AggregateKind::Adt(args_tupled_ty.as_adt().unwrap().clone(), None, None),
592                args.into_iter().map(Operand::Move).collect(),
593            ),
594        ));
595
596        let state_ty_adt = state_ty.as_adt().unwrap();
597        builder.push_statement(StatementKind::Assign(
598            state.clone(),
599            Rvalue::Aggregate(AggregateKind::Adt(state_ty_adt.clone(), None, None), vec![]),
600        ));
601
602        builder.call(
603            output,
604            Call {
605                func: fn_op,
606                args: vec![Operand::Move(state), Operand::Move(args_tupled)],
607                safety: CallSafety::Inherit,
608            },
609        );
610
611        Ok(Body::Unstructured(builder.build()))
612    }
613}