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