snarkvm_synthesizer_program/constructor/
parse.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
16use super::*;
17
18impl<N: Network> Parser for ConstructorCore<N> {
19    /// Parses a string into constructor.
20    #[inline]
21    fn parse(string: &str) -> ParserResult<Self> {
22        // Parse the whitespace and comments from the string.
23        let (string, _) = Sanitizer::parse(string)?;
24        // Parse the 'constructor' keyword from the string.
25        let (string, _) = tag(Self::type_name())(string)?;
26        // Parse the whitespace from the string.
27        let (string, _) = Sanitizer::parse_whitespaces(string)?;
28        // Parse the colon ':' keyword from the string.
29        let (string, _) = tag(":")(string)?;
30
31        // Parse the commands from the string.
32        let (string, commands) = many1(Command::parse)(string)?;
33
34        map_res(take(0usize), move |_| {
35            // Initialize a new constructor.
36            let mut constructor = Self { commands: Default::default(), num_writes: 0, positions: Default::default() };
37            if let Err(error) = commands.iter().cloned().try_for_each(|command| constructor.add_command(command)) {
38                eprintln!("{error}");
39                return Err(error);
40            }
41            Ok::<_, Error>(constructor)
42        })(string)
43    }
44}
45
46impl<N: Network> FromStr for ConstructorCore<N> {
47    type Err = Error;
48
49    /// Returns a constructor from a string literal.
50    fn from_str(string: &str) -> Result<Self> {
51        match Self::parse(string) {
52            Ok((remainder, object)) => {
53                // Ensure the remainder is empty.
54                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
55                // Return the object.
56                Ok(object)
57            }
58            Err(error) => bail!("Failed to parse string. {error}"),
59        }
60    }
61}
62
63impl<N: Network> Debug for ConstructorCore<N> {
64    /// Prints the constructor as a string.
65    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
66        Display::fmt(self, f)
67    }
68}
69
70impl<N: Network> Display for ConstructorCore<N> {
71    /// Prints the constructor as a string.
72    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
73        // Write the constructor to a string.
74        write!(f, "{}:", Self::type_name())?;
75        self.commands.iter().try_for_each(|command| write!(f, "\n    {command}"))
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::Constructor;
83    use console::network::MainnetV0;
84
85    type CurrentNetwork = MainnetV0;
86
87    #[test]
88    fn test_constructor_parse() {
89        let constructor = Constructor::<CurrentNetwork>::parse(
90            r"
91constructor:
92    add r0 r1 into r2;",
93        )
94        .unwrap()
95        .1;
96        assert_eq!(1, constructor.commands().len());
97
98        // Constructor with 0 inputs.
99        let constructor = Constructor::<CurrentNetwork>::parse(
100            r"
101constructor:
102    add 1u32 2u32 into r0;",
103        )
104        .unwrap()
105        .1;
106        assert_eq!(1, constructor.commands().len());
107    }
108
109    #[test]
110    fn test_constructor_parse_cast() {
111        let constructor = Constructor::<CurrentNetwork>::parse(
112            r"
113constructor:
114    cast 1u8 2u8 into r1 as token;",
115        )
116        .unwrap()
117        .1;
118        assert_eq!(1, constructor.commands().len());
119    }
120
121    #[test]
122    fn test_constructor_display() {
123        let expected = r"constructor:
124    add r0 r1 into r2;";
125        let constructor = Constructor::<CurrentNetwork>::parse(expected).unwrap().1;
126        assert_eq!(expected, format!("{constructor}"),);
127    }
128
129    #[test]
130    fn test_empty_constructor() {
131        // Test that parsing an empty constructor fails.
132        assert!(Constructor::<CurrentNetwork>::parse("constructor:").is_err());
133        // Test that attempting to serialize an empty constructor fails.
134        let constructor = Constructor::<CurrentNetwork> {
135            commands: Default::default(),
136            num_writes: 0,
137            positions: Default::default(),
138        };
139        assert!(constructor.write_le(Vec::new()).is_err());
140    }
141}