leo_passes/destructuring/mod.rs
1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17//! The destructuring pass traverses the AST and destructures tuples into individual variables.
18//! This pass assumes that tuples have a depth of 1, which is ensured by the type checking pass.
19
20use crate::Pass;
21
22use leo_ast::ProgramReconstructor as _;
23
24use leo_errors::Result;
25
26mod ast;
27
28mod program;
29
30mod visitor;
31use visitor::*;
32
33/// A pass to rewrite tuple creation and accesses into other code.
34///
35/// This pass must be run after SSA, because it depends on identifiers being unique.
36/// It must be run before flattening, because flattening cannot handle assignment statements.
37pub struct Destructuring;
38
39impl Pass for Destructuring {
40 type Input = ();
41 type Output = ();
42
43 const NAME: &str = "Destructuring";
44
45 fn do_pass(_input: Self::Input, state: &mut crate::CompilerState) -> Result<Self::Output> {
46 let mut ast = std::mem::take(&mut state.ast);
47 let mut visitor = DestructuringVisitor { state, tuples: Default::default(), is_async: false };
48 ast.ast = visitor.reconstruct_program(ast.ast);
49 visitor.state.handler.last_err().map_err(|e| *e)?;
50 visitor.state.ast = ast;
51 Ok(())
52 }
53}