leo_passes/code_generation/visitor.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::{AleoConstructor, AleoExpr, AleoReg, CompilerState};
18
19use leo_ast::{Function, Program, ProgramId, Variant};
20use leo_span::Symbol;
21
22use snarkvm::prelude::Network;
23
24use indexmap::{IndexMap, IndexSet};
25use itertools::Itertools;
26use std::str::FromStr;
27
28pub struct CodeGeneratingVisitor<'a> {
29 pub state: &'a CompilerState,
30 /// A counter to track the next available register.
31 pub next_register: u64,
32 /// Reference to the current function.
33 pub current_function: Option<&'a Function>,
34 /// Mapping of local variables to registers.
35 /// Because these are local, we can identify them using only a `Symbol` (i.e. a path is not necessary here).
36 pub variable_mapping: IndexMap<Symbol, AleoExpr>,
37 /// Mapping of composite names to a tuple containing metadata associated with the name.
38 /// The first element of the tuple indicate whether the composite is a record or not.
39 pub composite_mapping: IndexMap<Vec<Symbol>, bool>,
40 /// Mapping of global identifiers to their associated names.
41 /// Because we only allow mappings in the top level program scope at this stage, we can identify them using only a
42 /// `Symbol` (i.e. a path is not necessary here currently).
43 pub global_mapping: IndexMap<Symbol, AleoExpr>,
44 /// The variant of the function we are currently traversing.
45 pub variant: Option<Variant>,
46 /// A reference to program. This is needed to look up external programs.
47 pub program: &'a Program,
48 /// The program ID of the current program.
49 pub program_id: Option<ProgramId>,
50 /// A reference to the finalize caller.
51 /// Because `async transition`s can only appear in the top level program scope at this stage,
52 /// it's safe to keep this a `Symbol` (i.e. a path is not necessary).
53 pub finalize_caller: Option<Symbol>,
54 /// A counter to track the next available label.
55 pub next_label: u64,
56 /// The depth of the current conditional block.
57 pub conditional_depth: u64,
58 /// Internal record input registers of the current function.
59 /// This is necessary as if we output them, we need to clone them.
60 pub internal_record_inputs: IndexSet<AleoExpr>,
61}
62
63/// This function checks whether the constructor is well-formed.
64/// If an upgrade configuration is provided, it checks that the constructor matches the configuration.
65pub(crate) fn check_snarkvm_constructor<N: Network>(actual: &AleoConstructor) -> snarkvm::prelude::Result<()> {
66 use snarkvm::synthesizer::program::Constructor as SVMConstructor;
67 // Parse the constructor as a snarkVM constructor.
68 SVMConstructor::<N>::from_str(actual.to_string().trim())?;
69
70 Ok(())
71}
72
73impl CodeGeneratingVisitor<'_> {
74 pub(crate) fn next_register(&mut self) -> AleoReg {
75 self.next_register += 1;
76 AleoReg::R(self.next_register - 1)
77 }
78
79 /// Converts a path into a legal Aleo identifier, if possible.
80 ///
81 /// # Behavior
82 /// - If the path is a single valid Leo identifier (`[a-zA-Z][a-zA-Z0-9_]*`), it's returned as-is.
83 /// - If the last segment matches `Name::[args]` (e.g. `Vec3::[3, 4]`), it's converted to a legal identifier using hashing.
84 /// - If the path has multiple segments, and all segments are valid identifiers except the last one (which may be `Name::[args]`),
85 /// it's hashed using the last segment as base.
86 /// - Returns `None` if:
87 /// - The path is empty
88 /// - Any segment other than the last is not a valid identifier
89 /// - The last segment is invalid and not legalizable
90 ///
91 /// # Parameters
92 /// - `path`: A slice of `Symbol`s representing a path to an item.
93 ///
94 /// # Returns
95 /// - `Some(String)`: A valid Leo identifier.
96 /// - `None`: If the path is invalid or cannot be legalized.
97 pub(crate) fn legalize_path(path: &[Symbol]) -> Option<String> {
98 /// Checks if a string is a legal Leo identifier: [a-zA-Z][a-zA-Z0-9_]*
99 fn is_legal_identifier(s: &str) -> bool {
100 let mut chars = s.chars();
101 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
102 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
103 && s.len() <= 31
104 }
105
106 /// Generates a hashed Leo identifier from the full path, using the given base segment.
107 fn generate_hashed_name(path: &[Symbol], base: &str) -> String {
108 use base62::encode;
109 use sha2::{Digest, Sha256};
110 use std::fmt::Write;
111
112 let full_path = path.iter().format("::").to_string();
113
114 let mut hasher = Sha256::new();
115 hasher.update(full_path.as_bytes());
116 let hash = hasher.finalize();
117
118 let hash_number = u64::from_be_bytes(hash[..8].try_into().unwrap());
119 let hash_base62 = encode(hash_number);
120
121 let fixed_suffix_len = 2 + hash_base62.len(); // "__" + hash
122 let max_ident_len = 31 - fixed_suffix_len;
123
124 let mut result = String::new();
125 write!(&mut result, "{base:.max_ident_len$}__{hash_base62}").unwrap();
126 result
127 }
128
129 let last = path.last()?.to_string();
130
131 // Validate all segments except the last
132 if path.len() > 1 && !path[..path.len() - 1].iter().all(|sym| is_legal_identifier(&sym.to_string())) {
133 return None;
134 }
135
136 // === Case 1: Single, legal identifier ===
137 if path.len() == 1 && is_legal_identifier(&last) {
138 return Some(last);
139 }
140
141 // === Case 2: Storage-generated identifiers ===
142 //
143 // These occur after lowering storage variables into mappings.
144 // They can take the forms:
145 // - `some_var__` (for singleton storage)
146 // - `some_var__len__` (for vector length mapping)
147 //
148 // Both can exceed 31 chars once the "__" or "__len__" suffix is added,
149 // so we truncate the base portion to preserve the suffix and make space
150 // for the hash. The truncation lengths below were chosen so that:
151 // ```
152 // total_length = prefix_len + suffix_len + "__" + hash_len <= 31
153 // ```
154 // where hash_len = 11.
155 if let Some(prefix) = last.strip_suffix("__len__") {
156 // "some_very_long_storage_variable__len__"
157 // - Keep at most 13 chars from the prefix
158 // - Produces something like: "some_very_lon__len__CpUbpLTf1Ow"
159 let truncated_prefix = &prefix[..13.min(prefix.len())];
160 return Some(generate_hashed_name(path, &(truncated_prefix.to_owned() + "__len")));
161 }
162
163 if let Some(prefix) = last.strip_suffix("__") {
164 // "some_very_long_storage_variable__"
165 // - Keep at most 18 chars from the prefix
166 // - Produces something like: "some_very_long_sto__Hn1pThQeV3"
167 let truncated_prefix = &prefix[..18.min(prefix.len())];
168 return Some(generate_hashed_name(path, &(truncated_prefix.to_owned() + "__")));
169 }
170
171 // === Case 3: Matches special form like `path::to::Name::[3, 4]` ===
172 let re = regex::Regex::new(r#"^([a-zA-Z_][\w]*)(?:::\[.*?\])?$"#).unwrap();
173
174 if let Some(captures) = re.captures(&last) {
175 let ident = captures.get(1)?.as_str();
176
177 // The produced name here will be of the form: `<last>__AYMqiUeJeQN`.
178 return Some(generate_hashed_name(path, ident));
179 }
180
181 // === Case 4: Matches special form like `path::to::Name?` (last always ends with `?`) ===
182 if last.ends_with("?\"") {
183 // Because the last segment of `path` always ends with `?` in case 3, we can guarantee
184 // that there will be no conflicts with case 2 (which doesn't allow `?` anywhere).
185 //
186 // The produced name here will be of the form: `Optional__JZCpIGdQvEZ`.
187 // The suffix after the `__` cannot conflict with the suffix in case 2 because of the `?`
188 return Some(generate_hashed_name(path, "Optional"));
189 }
190
191 // Last segment is neither legal nor matches special pattern
192 None
193 }
194}