charon_lib/ast/
llbc_ast_utils.rs

1//! Implementations for [crate::llbc_ast]
2
3use crate::llbc_ast::*;
4use crate::meta;
5use crate::meta::Span;
6use derive_generic_visitor::*;
7use std::mem;
8
9/// Combine the span information from a [Switch]
10pub fn combine_switch_targets_span(targets: &Switch) -> Span {
11    match targets {
12        Switch::If(_, st1, st2) => meta::combine_span(&st1.span, &st2.span),
13        Switch::SwitchInt(_, _, branches, otherwise) => {
14            let branches = branches.iter().map(|b| &b.1.span);
15            let mbranches = meta::combine_span_iter(branches);
16            meta::combine_span(&mbranches, &otherwise.span)
17        }
18        Switch::Match(_, branches, otherwise) => {
19            let branches = branches.iter().map(|b| &b.1.span);
20            let mbranches = meta::combine_span_iter(branches);
21            if let Some(otherwise) = otherwise {
22                meta::combine_span(&mbranches, &otherwise.span)
23            } else {
24                mbranches
25            }
26        }
27    }
28}
29
30impl Switch {
31    pub fn iter_targets(&self) -> impl Iterator<Item = &Block> {
32        use itertools::Either;
33        match self {
34            Switch::If(_, exp1, exp2) => Either::Left([exp1, exp2].into_iter()),
35            Switch::SwitchInt(_, _, targets, otherwise) => Either::Right(Either::Left(
36                targets.iter().map(|(_, tgt)| tgt).chain([otherwise]),
37            )),
38            Switch::Match(_, targets, otherwise) => Either::Right(Either::Right(
39                targets.iter().map(|(_, tgt)| tgt).chain(otherwise.as_ref()),
40            )),
41        }
42    }
43
44    pub fn iter_targets_mut(&mut self) -> impl Iterator<Item = &mut Block> {
45        use itertools::Either;
46        match self {
47            Switch::If(_, exp1, exp2) => Either::Left([exp1, exp2].into_iter()),
48            Switch::SwitchInt(_, _, targets, otherwise) => Either::Right(Either::Left(
49                targets.iter_mut().map(|(_, tgt)| tgt).chain([otherwise]),
50            )),
51            Switch::Match(_, targets, otherwise) => Either::Right(Either::Right(
52                targets
53                    .iter_mut()
54                    .map(|(_, tgt)| tgt)
55                    .chain(otherwise.as_mut()),
56            )),
57        }
58    }
59}
60
61impl Statement {
62    pub fn new(span: Span, content: RawStatement) -> Self {
63        Statement {
64            span,
65            content,
66            comments_before: vec![],
67        }
68    }
69
70    pub fn into_box(self) -> Box<Self> {
71        Box::new(self)
72    }
73
74    pub fn into_block(self) -> Block {
75        Block {
76            span: self.span,
77            statements: vec![self],
78        }
79    }
80}
81
82impl Block {
83    pub fn from_seq(seq: Vec<Statement>) -> Option<Self> {
84        if seq.is_empty() {
85            None
86        } else {
87            let span = seq
88                .iter()
89                .map(|st| st.span)
90                .reduce(|a, b| meta::combine_span(&a, &b))
91                .unwrap();
92            Some(Block {
93                span,
94                statements: seq,
95            })
96        }
97    }
98
99    pub fn merge(mut self, mut other: Self) -> Self {
100        self.span = meta::combine_span(&self.span, &other.span);
101        self.statements.append(&mut other.statements);
102        self
103    }
104
105    pub fn then(mut self, r: Statement) -> Self {
106        self.span = meta::combine_span(&self.span, &r.span);
107        self.statements.push(r);
108        self
109    }
110
111    pub fn then_opt(self, other: Option<Statement>) -> Self {
112        if let Some(other) = other {
113            self.then(other)
114        } else {
115            self
116        }
117    }
118
119    /// Apply a function to all the statements, in a top-down manner.
120    pub fn visit_statements<F: FnMut(&mut Statement)>(&mut self, f: F) {
121        let _ = BlockVisitor::new(|_| {}, f).visit(self);
122    }
123
124    /// Apply a transformer to all the statements, in a bottom-up manner.
125    ///
126    /// The transformer should:
127    /// - mutate the current statement in place
128    /// - return the sequence of statements to introduce before the current statement
129    pub fn transform<F: FnMut(&mut Statement) -> Vec<Statement>>(&mut self, mut f: F) {
130        self.transform_sequences(|slice| f(&mut slice[0]));
131    }
132
133    /// Apply a transformer to all the statements, in a bottom-up manner. Compared to `transform`,
134    /// this also gives access to the following statements if any. Statements that are not part of
135    /// a sequence will be traversed as `[st]`. Statements that are will be traversed twice: once
136    /// as `[st]`, and then as `[st, ..]` with the following statements if any.
137    ///
138    /// The transformer should:
139    /// - mutate the current statements in place
140    /// - return the sequence of statements to introduce before the current statements
141    pub fn transform_sequences<F: FnMut(&mut [Statement]) -> Vec<Statement>>(&mut self, mut f: F) {
142        self.visit_blocks_bwd(|blk: &mut Block| {
143            let mut final_len = blk.statements.len();
144            let mut to_insert = vec![];
145            for i in (0..blk.statements.len()).rev() {
146                let new_to_insert = f(&mut blk.statements[i..]);
147                final_len += new_to_insert.len();
148                to_insert.push((i, new_to_insert));
149            }
150            if !to_insert.is_empty() {
151                to_insert.sort_by_key(|(i, _)| *i);
152                // Make it so the first element is always at the end so we can pop it.
153                to_insert.reverse();
154                // Construct the merged list of statements.
155                let old_statements =
156                    mem::replace(&mut blk.statements, Vec::with_capacity(final_len));
157                for (i, stmt) in old_statements.into_iter().enumerate() {
158                    while let Some((j, _)) = to_insert.last()
159                        && *j == i
160                    {
161                        let (_, mut stmts) = to_insert.pop().unwrap();
162                        blk.statements.append(&mut stmts);
163                    }
164                    blk.statements.push(stmt);
165                }
166            }
167        })
168    }
169
170    /// Visit `self` and its sub-blocks in a bottom-up (post-order) traversal.
171    pub fn visit_blocks_bwd<F: FnMut(&mut Block)>(&mut self, f: F) {
172        let _ = BlockVisitor::new(f, |_| {}).visit(self);
173    }
174}
175
176/// Small visitor to visit statements and blocks.
177#[derive(Visitor)]
178pub struct BlockVisitor<F: FnMut(&mut Block), G: FnMut(&mut Statement)> {
179    exit_blk: F,
180    enter_stmt: G,
181}
182
183impl<F: FnMut(&mut Block), G: FnMut(&mut Statement)> BlockVisitor<F, G> {
184    pub fn new(exit_blk: F, enter_stmt: G) -> Self {
185        Self {
186            exit_blk,
187            enter_stmt,
188        }
189    }
190}
191
192impl<F: FnMut(&mut Block), G: FnMut(&mut Statement)> VisitBodyMut for BlockVisitor<F, G> {
193    fn exit_llbc_block(&mut self, x: &mut Block) {
194        (self.exit_blk)(x)
195    }
196    fn enter_llbc_statement(&mut self, x: &mut Statement) {
197        (self.enter_stmt)(x)
198    }
199}