snarkvm_synthesizer_program/function/
mod.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16mod input;
17use input::*;
18
19mod output;
20use output::*;
21
22mod bytes;
23mod parse;
24
25use crate::{Instruction, finalize::FinalizeCore};
26use console::{
27    network::prelude::*,
28    program::{Identifier, Register, ValueType, Variant},
29};
30
31use indexmap::IndexSet;
32
33#[derive(Clone, PartialEq, Eq)]
34pub struct FunctionCore<N: Network> {
35    /// The name of the function.
36    name: Identifier<N>,
37    /// The input statements, added in order of the input registers.
38    /// Input assignments are ensured to match the ordering of the input statements.
39    inputs: IndexSet<Input<N>>,
40    /// The instructions, in order of execution.
41    instructions: Vec<Instruction<N>>,
42    /// The output statements, in order of the desired output.
43    outputs: IndexSet<Output<N>>,
44    /// The optional finalize logic.
45    finalize_logic: Option<FinalizeCore<N>>,
46}
47
48impl<N: Network> FunctionCore<N> {
49    /// Initializes a new function with the given name.
50    pub fn new(name: Identifier<N>) -> Self {
51        Self { name, inputs: IndexSet::new(), instructions: Vec::new(), outputs: IndexSet::new(), finalize_logic: None }
52    }
53
54    /// Returns the name of the function.
55    pub const fn name(&self) -> &Identifier<N> {
56        &self.name
57    }
58
59    /// Returns the function inputs.
60    pub const fn inputs(&self) -> &IndexSet<Input<N>> {
61        &self.inputs
62    }
63
64    /// Returns the function input types.
65    pub fn input_types(&self) -> Vec<ValueType<N>> {
66        self.inputs.iter().map(|input| input.value_type()).cloned().collect()
67    }
68
69    /// Returns the function input type variants.
70    pub fn input_variants(&self) -> Vec<Variant> {
71        self.inputs.iter().map(|input| input.value_type().variant()).collect()
72    }
73
74    /// Returns the function instructions.
75    pub fn instructions(&self) -> &[Instruction<N>] {
76        &self.instructions
77    }
78
79    /// Returns the function outputs.
80    pub const fn outputs(&self) -> &IndexSet<Output<N>> {
81        &self.outputs
82    }
83
84    /// Returns the function output types.
85    pub fn output_types(&self) -> Vec<ValueType<N>> {
86        self.outputs.iter().map(|output| output.value_type()).cloned().collect()
87    }
88
89    /// Returns the function output type variants.
90    pub fn output_variants(&self) -> Vec<Variant> {
91        self.outputs.iter().map(|output| output.value_type().variant()).collect()
92    }
93
94    /// Returns the function finalize logic.
95    pub const fn finalize_logic(&self) -> Option<&FinalizeCore<N>> {
96        self.finalize_logic.as_ref()
97    }
98}
99
100impl<N: Network> FunctionCore<N> {
101    /// Adds the input statement to the function.
102    ///
103    /// # Errors
104    /// This method will halt if there are instructions or output statements already.
105    /// This method will halt if the maximum number of inputs has been reached.
106    /// This method will halt if the input statement was previously added.
107    /// This method will halt if a finalize logic has been added.
108    #[inline]
109    fn add_input(&mut self, input: Input<N>) -> Result<()> {
110        // Ensure there are no instructions or output statements in memory.
111        ensure!(self.instructions.is_empty(), "Cannot add inputs after instructions have been added");
112        ensure!(self.outputs.is_empty(), "Cannot add inputs after outputs have been added");
113
114        // Ensure the maximum number of inputs has not been exceeded.
115        ensure!(self.inputs.len() < N::MAX_INPUTS, "Cannot add more than {} inputs", N::MAX_INPUTS);
116        // Ensure the input statement was not previously added.
117        ensure!(!self.inputs.contains(&input), "Cannot add duplicate input statement");
118
119        // Ensure a finalize logic has not been added.
120        ensure!(self.finalize_logic.is_none(), "Cannot add instructions after finalize logic has been added");
121
122        // Ensure the input register is a locator.
123        ensure!(matches!(input.register(), Register::Locator(..)), "Input register must be a locator");
124
125        // Insert the input statement.
126        self.inputs.insert(input);
127        Ok(())
128    }
129
130    /// Adds the given instruction to the function.
131    ///
132    /// # Errors
133    /// This method will halt if there are output statements already.
134    /// This method will halt if the maximum number of instructions has been reached.
135    /// This method will halt if a finalize logic has been added.
136    #[inline]
137    pub fn add_instruction(&mut self, instruction: Instruction<N>) -> Result<()> {
138        // Ensure that there are no output statements in memory.
139        ensure!(self.outputs.is_empty(), "Cannot add instructions after outputs have been added");
140
141        // Ensure the maximum number of instructions has not been exceeded.
142        ensure!(
143            self.instructions.len() < N::MAX_INSTRUCTIONS,
144            "Cannot add more than {} instructions",
145            N::MAX_INSTRUCTIONS
146        );
147
148        // Ensure a finalize logic has not been added.
149        ensure!(self.finalize_logic.is_none(), "Cannot add instructions after finalize logic has been added");
150
151        // Ensure the destination register is a locator.
152        for register in instruction.destinations() {
153            ensure!(matches!(register, Register::Locator(..)), "Destination register must be a locator");
154        }
155
156        // Insert the instruction.
157        self.instructions.push(instruction);
158        Ok(())
159    }
160
161    /// Adds the output statement to the function.
162    ///
163    /// # Errors
164    /// This method will halt if the maximum number of outputs has been reached.
165    /// This method will halt if a finalize logic has been added.
166    #[inline]
167    fn add_output(&mut self, output: Output<N>) -> Result<()> {
168        // Ensure the maximum number of outputs has not been exceeded.
169        ensure!(self.outputs.len() < N::MAX_OUTPUTS, "Cannot add more than {} outputs", N::MAX_OUTPUTS);
170        // Ensure the output statement was not previously added.
171        ensure!(!self.outputs.contains(&output), "Cannot add duplicate output statement");
172
173        // Ensure that the finalize logic has not been added.
174        ensure!(self.finalize_logic.is_none(), "Cannot add instructions after finalize logic has been added");
175
176        // Insert the output statement.
177        self.outputs.insert(output);
178        Ok(())
179    }
180
181    /// Adds the finalize scope to the function.
182    ///
183    /// # Errors
184    /// This method will halt if a finalize scope has already been added.
185    /// This method will halt if name in the finalize scope does not match the function name.
186    /// This method will halt if the maximum number of finalize inputs has been reached.
187    /// This method will halt if the number of finalize operands does not match the number of finalize inputs.
188    #[inline]
189    fn add_finalize(&mut self, finalize: FinalizeCore<N>) -> Result<()> {
190        // Ensure there is no finalize scope in memory.
191        ensure!(self.finalize_logic.is_none(), "Cannot add multiple finalize scopes to function '{}'", self.name);
192        // Ensure the finalize scope name matches the function name.
193        ensure!(*finalize.name() == self.name, "Finalize scope name must match function name '{}'", self.name);
194        // Ensure the number of finalize inputs has not been exceeded.
195        ensure!(finalize.inputs().len() <= N::MAX_INPUTS, "Cannot add more than {} inputs to finalize", N::MAX_INPUTS);
196
197        // Insert the finalize scope.
198        self.finalize_logic = Some(finalize);
199        Ok(())
200    }
201}
202
203impl<N: Network> TypeName for FunctionCore<N> {
204    /// Returns the type name as a string.
205    #[inline]
206    fn type_name() -> &'static str {
207        "function"
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    use crate::{Function, Instruction};
216
217    type CurrentNetwork = console::network::MainnetV0;
218
219    #[test]
220    fn test_add_input() {
221        // Initialize a new function instance.
222        let name = Identifier::from_str("function_core_test").unwrap();
223        let mut function = Function::<CurrentNetwork>::new(name);
224
225        // Ensure that an input can be added.
226        let input = Input::<CurrentNetwork>::from_str("input r0 as field.private;").unwrap();
227        assert!(function.add_input(input.clone()).is_ok());
228
229        // Ensure that adding a duplicate input will fail.
230        assert!(function.add_input(input).is_err());
231
232        // Ensure that adding more than the maximum number of inputs will fail.
233        for i in 1..CurrentNetwork::MAX_INPUTS * 2 {
234            let input = Input::<CurrentNetwork>::from_str(&format!("input r{i} as field.private;")).unwrap();
235
236            match function.inputs.len() < CurrentNetwork::MAX_INPUTS {
237                true => assert!(function.add_input(input).is_ok()),
238                false => assert!(function.add_input(input).is_err()),
239            }
240        }
241    }
242
243    #[test]
244    fn test_add_instruction() {
245        // Initialize a new function instance.
246        let name = Identifier::from_str("function_core_test").unwrap();
247        let mut function = Function::<CurrentNetwork>::new(name);
248
249        // Ensure that an instruction can be added.
250        let instruction = Instruction::<CurrentNetwork>::from_str("add r0 r1 into r2;").unwrap();
251        assert!(function.add_instruction(instruction).is_ok());
252
253        // Ensure that adding more than the maximum number of instructions will fail.
254        for i in 3..CurrentNetwork::MAX_INSTRUCTIONS * 2 {
255            let instruction = Instruction::<CurrentNetwork>::from_str(&format!("add r0 r1 into r{i};")).unwrap();
256
257            match function.instructions.len() < CurrentNetwork::MAX_INSTRUCTIONS {
258                true => assert!(function.add_instruction(instruction).is_ok()),
259                false => assert!(function.add_instruction(instruction).is_err()),
260            }
261        }
262    }
263
264    #[test]
265    fn test_add_output() {
266        // Initialize a new function instance.
267        let name = Identifier::from_str("function_core_test").unwrap();
268        let mut function = Function::<CurrentNetwork>::new(name);
269
270        // Ensure that an output can be added.
271        let output = Output::<CurrentNetwork>::from_str("output r0 as field.private;").unwrap();
272        assert!(function.add_output(output).is_ok());
273
274        // Ensure that adding more than the maximum number of outputs will fail.
275        for i in 1..CurrentNetwork::MAX_OUTPUTS * 2 {
276            let output = Output::<CurrentNetwork>::from_str(&format!("output r{i} as field.private;")).unwrap();
277
278            match function.outputs.len() < CurrentNetwork::MAX_OUTPUTS {
279                true => assert!(function.add_output(output).is_ok()),
280                false => assert!(function.add_output(output).is_err()),
281            }
282        }
283    }
284}