leo_passes/write_transforming/
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
17use crate::Pass;
18
19use leo_ast::ProgramReconstructor as _;
20
21use leo_errors::Result;
22
23mod ast;
24
25mod program;
26
27mod visitor;
28use visitor::*;
29
30/// A pass to rewrite assignments to array accesses and struct accesses.
31///
32/// This pass makes variables for members of arrays and structs that are written to,
33/// changes assignments to those members into assignments to those variables, and,
34/// whenever the arrays or structs are accessed, reconstructs them from the variables.
35/// So code like this:
36///
37/// let s = S { a: 1u8, b: [2u8, 3u8] };
38/// s.a = 1u8;
39/// s.b[0u8] = 4u8;
40/// return s;
41///
42/// will be changed into something like this:
43///
44/// let s_a = 1u8;
45/// let s_b_0 = 2u8;
46/// let s_b_1 = 3u8;
47/// s_b_1 = 4u8;
48/// return S { a: s_a, b: [s_b_0, s_b_1] };
49///
50/// The pass requires that the AST is in SSA form (so that sub-expressions are always
51/// variables or literals) and that tuples have been destructured.
52/// Since the pass will create new assignments, `SsaForming` must be run again afterwards.
53///
54/// A note on the semantics of the language as implemented by this pass:
55/// assignments and definitions in essence copy structs and arrays. Thus if we do
56/// ```leo
57/// let x = [0u8, 1u8];
58/// let y = x;
59/// y[0u8] = 12u8;
60/// ```
61/// x is still `[0u8, 1u8];`
62pub struct WriteTransforming;
63
64impl Pass for WriteTransforming {
65    type Input = ();
66    type Output = ();
67
68    const NAME: &str = "WriteTransforming";
69
70    fn do_pass(_input: Self::Input, state: &mut crate::CompilerState) -> Result<Self::Output> {
71        let mut ast = std::mem::take(&mut state.ast);
72        let mut visitor = WriteTransformingVisitor::new(state, ast.as_repr());
73        ast.ast = visitor.reconstruct_program(ast.ast);
74        visitor.state.handler.last_err()?;
75        visitor.state.ast = ast;
76        Ok(())
77    }
78}