Skip to main content

charon_lib/transform/resugar/
reconstruct_box_drops.rs

1//! Resugar direct calls to `Drop::drop` for `Box`.
2//!
3//! Dropping an initialized Box uses drop terminators like any other value. However Box is special:
4//! it allows being moved out of. When a partially-moved-out-of Box reaches end of scope, drop
5//! elaboration destructs the rest of the value, then calls `Drop::drop` directly, which is atypical.
6//!
7//! This pass recovers this into a builtin operation.
8use crate::transform::{TransformCtx, ctx::UllbcPass};
9use crate::ullbc_ast::*;
10
11pub struct Transform;
12
13fn trait_ref_is_box_drop(krate: &TranslatedCrate, trait_ref: &TraitDeclRef) -> bool {
14    krate
15        .trait_decls
16        .get(trait_ref.id)
17        .is_some_and(|decl| decl.item_meta.lang_item == Some(from_rustc::LangItem::Drop))
18        && trait_ref.self_ty(krate).is_some_and(|ty| ty.is_box())
19}
20
21impl UllbcPass for Transform {
22    fn should_run(&self, options: &crate::options::TranslateOptions) -> bool {
23        options.treat_box_as_builtin && !options.desugar_drops
24    }
25
26    fn transform_body(&self, ctx: &mut TransformCtx, body: &mut ExprBody) {
27        let krate: &TranslatedCrate = &ctx.translated;
28        for block in &mut body.body {
29            if let TerminatorKind::Call {
30                call,
31                target,
32                on_unwind,
33                ..
34            } = &block.terminator.kind
35                && let FnOperand::Regular(fn_ptr) = &call.func
36                && fn_ptr
37                    .as_method_call(krate)
38                    .is_some_and(|(tref, _)| trait_ref_is_box_drop(krate, tref))
39                && let [Operand::Move(argument)] = call.args.as_slice()
40                && let Some(statement) = block.statements.last()
41                && let StatementKind::Assign(
42                    temporary,
43                    Rvalue::Ref {
44                        place,
45                        kind: BorrowKind::Mut,
46                        ..
47                    },
48                ) = &statement.kind
49                && temporary.is_local()
50                && temporary == argument
51                && place.ty().is_box()
52            {
53                let place = place.clone();
54                let target = *target;
55                let on_unwind = *on_unwind;
56                block.statements.pop();
57                block.terminator.kind = TerminatorKind::DropEmptyBox {
58                    place,
59                    target,
60                    on_unwind,
61                };
62            }
63        }
64    }
65}