charon_lib/transform/resugar/
reconstruct_asserts.rs1use crate::name_matcher::NamePattern;
7use crate::transform::ctx::UllbcPass;
8use crate::transform::{CowBox, TransformCtx};
9use crate::ullbc_ast::*;
10
11pub struct Transform {
12 unreachable: Option<Call>,
13}
14
15impl Transform {
16 pub fn new(ctx: &TransformCtx) -> CowBox<dyn UllbcPass> {
17 let unreachable_pattern = NamePattern::parse("core::hint::unreachable_unchecked").unwrap();
18 let unreachable = ctx
19 .translated
20 .fun_decls
21 .iter_indexed()
22 .find(|(_, decl)| unreachable_pattern.matches(&ctx.translated, &decl.item_meta.name))
23 .map(|(id, _)| Call {
24 func: FnOperand::Regular(FnPtr::new(FnPtrKind::Fun(id), GenericArgs::empty())),
25 args: vec![],
26 safety: CallSafety::Inherit,
27 });
28 CowBox::Owned(Box::new(Self { unreachable }))
29 }
30}
31
32impl UllbcPass for Transform {
33 fn should_run(&self, options: &crate::options::TranslateOptions) -> bool {
34 options.reconstruct_asserts
35 }
36
37 fn transform_body(&self, _ctx: &mut TransformCtx, b: &mut ExprBody) {
38 let Some(unreachable) = &self.unreachable else {
39 return;
40 };
41 let panics = b.as_abort_map();
45
46 for block in b.body.iter_mut() {
47 if let TerminatorKind::Switch { data, branches } = &block.terminator.kind
48 && let Some((true_id, false_id)) = data.as_if()
49 && let SwitchScrutinee::Value(discr) = data.scrutinee.clone()
50 {
51 let (true_bid, false_bid) = (branches[true_id], branches[false_id]);
52 let (nbid, expected, (abort, call)) = if let Some(abort) = panics.get(&true_bid) {
53 (false_bid, false, abort)
54 } else if let Some(abort) = panics.get(&false_bid) {
55 (true_bid, true, abort)
56 } else {
57 continue;
58 };
59
60 let call = match abort {
61 AbortKind::Panic | AbortKind::UnwindTerminate(..) => call
62 .clone()
63 .expect("panics and unwind terminates always have a call"),
64 AbortKind::UndefinedBehavior => unreachable.clone(),
65 };
66 let _ = std::mem::replace(
67 &mut block.terminator.kind,
68 TerminatorKind::Goto { target: nbid },
69 );
70 block.statements.push(Statement::new(
71 block.terminator.span,
72 StatementKind::Assert {
73 assert: Assert {
74 cond: discr,
75 expected,
76 check_kind: None,
77 call: Box::new(call),
78 },
79 on_failure: abort.clone(),
80 },
81 ));
82 }
83 }
84 }
85}