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, old_id: NodeID, func: impl FnOnce(&mut Self, NodeID) -> T) -> T {
34 let new_id = self.symbol_table.enter_scope_duped(old_id, self.node_builder);
35 let result = func(self, new_id);
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 self.in_scope_duped(input.id(), |slf, new_id| {
60 input.id = new_id;
61 input.statements = input.statements.into_iter().map(|stmt| slf.reconstruct_statement(stmt).0).collect();
62 (input, Default::default())
63 })
64 }
65
66 fn reconstruct_conditional(&mut self, mut input: ConditionalStatement) -> (Statement, Self::AdditionalOutput) {
67 input.then = self.reconstruct_block(input.then).0;
68 if let Some(mut otherwise) = input.otherwise {
69 *otherwise = self.reconstruct_statement(*otherwise).0;
70 input.otherwise = Some(otherwise);
71 }
72
73 (input.into(), Default::default())
74 }
75
76 fn reconstruct_iteration(&mut self, mut input: IterationStatement) -> (Statement, Self::AdditionalOutput) {
77 self.in_scope_duped(input.id(), |slf, new_id| {
78 input.id = new_id;
79 input.block = slf.reconstruct_block(input.block).0;
80 (input.into(), Default::default())
81 })
82 }
83}