leo_passes/loop_unrolling/
duplicate.rs1use leo_ast::{AstReconstructor, Block, Statement, *};
18
19use crate::SymbolTable;
20
21pub fn duplicate(block: Block, symbol_table: &mut SymbolTable, node_builder: &NodeBuilder) -> Block {
24 Duplicator { symbol_table, node_builder }.reconstruct_block(block).0
25}
26
27struct Duplicator<'a> {
28 symbol_table: &'a mut SymbolTable,
29 node_builder: &'a NodeBuilder,
30}
31
32impl Duplicator<'_> {
33 fn in_scope_duped<T>(&mut self, new_id: NodeID, old_id: NodeID, func: impl FnOnce(&mut Self) -> T) -> T {
34 self.symbol_table.enter_scope_duped(new_id, old_id);
35 let result = func(self);
36 self.symbol_table.enter_parent();
37 result
38 }
39}
40
41impl AstReconstructor for Duplicator<'_> {
42 type AdditionalInput = ();
43 type AdditionalOutput = ();
44
45 fn reconstruct_statement(&mut self, input: Statement) -> (Statement, Self::AdditionalOutput) {
47 match input {
48 Statement::Block(stmt) => {
49 let (stmt, output) = self.reconstruct_block(stmt);
50 (stmt.into(), output)
51 }
52 Statement::Conditional(stmt) => self.reconstruct_conditional(stmt),
53 Statement::Iteration(stmt) => self.reconstruct_iteration(*stmt),
54 stmt => (stmt, Default::default()),
55 }
56 }
57
58 fn reconstruct_block(&mut self, mut input: Block) -> (Block, Self::AdditionalOutput) {
59 let next_id = self.node_builder.next_id();
60 self.in_scope_duped(next_id, input.id(), |slf| {
61 input.id = next_id;
62 input.statements = input.statements.into_iter().map(|stmt| slf.reconstruct_statement(stmt).0).collect();
63 (input, Default::default())
64 })
65 }
66
67 fn reconstruct_conditional(&mut self, mut input: ConditionalStatement) -> (Statement, Self::AdditionalOutput) {
68 input.then = self.reconstruct_block(input.then).0;
69 if let Some(mut otherwise) = input.otherwise {
70 *otherwise = self.reconstruct_statement(*otherwise).0;
71 input.otherwise = Some(otherwise);
72 }
73
74 (input.into(), Default::default())
75 }
76
77 fn reconstruct_iteration(&mut self, mut input: IterationStatement) -> (Statement, Self::AdditionalOutput) {
78 let next_id = self.node_builder.next_id();
79 self.in_scope_duped(next_id, input.id(), |slf| {
80 input.id = next_id;
81 input.block = slf.reconstruct_block(input.block).0;
82 (input.into(), Default::default())
83 })
84 }
85}