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 expression;
27
28mod program;
29
30mod statement;
31
32mod visitor;
33use visitor::*;
34
35/// A pass to rewrite tuple creation and accesses into other code.
36///
37/// This pass must be run after SSA, because it depends on identifiers being unique.
38/// It must be run before flattening, because flattening cannot handle assignment statements.
39pub struct Destructuring;
40
41impl Pass for Destructuring {
42 type Input = ();
43 type Output = ();
44
45 const NAME: &str = "Destructuring";
46
47 fn do_pass(_input: Self::Input, state: &mut crate::CompilerState) -> Result<Self::Output> {
48 let mut ast = std::mem::take(&mut state.ast);
49 let mut visitor = DestructuringVisitor { state, tuples: Default::default(), is_async: false };
50 ast.ast = visitor.reconstruct_program(ast.ast);
51 visitor.state.handler.last_err().map_err(|e| *e)?;
52 visitor.state.ast = ast;
53 Ok(())
54 }
55}