Skip to main content

snarkvm_synthesizer_program/view/input/
parse.rs

1// Copyright (c) 2019-2026 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 Input<N> {
19    /// Parses a string into an input statement.
20    /// The input statement is of the form `input {register} as {plaintext_type}.public;`.
21    #[inline]
22    fn parse(string: &str) -> ParserResult<Self> {
23        // Parse the whitespace and comments from the string.
24        let (string, _) = Sanitizer::parse(string)?;
25        // Parse the input keyword from the string.
26        let (string, _) = tag(Self::type_name())(string)?;
27        // Parse the whitespace from the string.
28        let (string, _) = Sanitizer::parse_whitespaces(string)?;
29        // Parse the register from the string.
30        let (string, register) = map_res(Register::parse, |register| match &register {
31            Register::Locator(..) => Ok(register),
32            Register::Access(..) => Err(error(format!("Input register {register} cannot be a register member"))),
33        })(string)?;
34        // Parse the whitespace from the string.
35        let (string, _) = Sanitizer::parse_whitespaces(string)?;
36        // Parse the "as" from the string.
37        let (string, _) = tag("as")(string)?;
38        // Parse the whitespace from the string.
39        let (string, _) = Sanitizer::parse_whitespaces(string)?;
40        // Parse the finalize type from the string.
41        let (string, finalize_type) = FinalizeType::parse(string)?;
42        // Parse the whitespace from the string.
43        let (string, _) = Sanitizer::parse_whitespaces(string)?;
44        // Parse the semicolon from the string.
45        let (string, _) = tag(";")(string)?;
46        // Return the input statement.
47        Ok((string, Self { register, finalize_type }))
48    }
49}
50
51impl<N: Network> FromStr for Input<N> {
52    type Err = Error;
53
54    #[inline]
55    fn from_str(string: &str) -> Result<Self> {
56        match Self::parse(string) {
57            Ok((remainder, object)) => {
58                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
59                Ok(object)
60            }
61            Err(error) => bail!("Failed to parse string. {error}"),
62        }
63    }
64}
65
66impl<N: Network> Debug for Input<N> {
67    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
68        Display::fmt(self, f)
69    }
70}
71
72impl<N: Network> Display for Input<N> {
73    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
74        write!(f, "{} {} as {};", Self::type_name(), self.register, self.finalize_type)
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use console::network::MainnetV0;
82
83    type CurrentNetwork = MainnetV0;
84
85    #[test]
86    fn test_input_parse() -> Result<()> {
87        let input = Input::<CurrentNetwork>::parse("input r0 as field.public;").unwrap().1;
88        assert_eq!(input.register(), &Register::<CurrentNetwork>::Locator(0));
89        assert_eq!(input.finalize_type(), &FinalizeType::<CurrentNetwork>::from_str("field.public")?);
90
91        let input = Input::<CurrentNetwork>::parse("input r1 as u64.public;").unwrap().1;
92        assert_eq!(input.register(), &Register::<CurrentNetwork>::Locator(1));
93        assert_eq!(input.finalize_type(), &FinalizeType::<CurrentNetwork>::from_str("u64.public")?);
94
95        let input = Input::<CurrentNetwork>::parse("input r2 as address.public;").unwrap().1;
96        assert_eq!(input.register(), &Register::<CurrentNetwork>::Locator(2));
97        assert_eq!(input.finalize_type(), &FinalizeType::<CurrentNetwork>::from_str("address.public")?);
98
99        Ok(())
100    }
101
102    #[test]
103    fn test_input_display() -> Result<()> {
104        let input = Input::<CurrentNetwork>::from_str("input r0 as field.public;")?;
105        assert_eq!("input r0 as field.public;", input.to_string());
106
107        let input = Input::<CurrentNetwork>::from_str("input r3 as u64.public;")?;
108        assert_eq!("input r3 as u64.public;", input.to_string());
109
110        Ok(())
111    }
112
113    #[test]
114    fn test_input_parse_fails() {
115        // Register member is rejected (must be a locator).
116        assert!(Input::<CurrentNetwork>::from_str("input r0.x as field.public;").is_err());
117        // Missing trailing semicolon.
118        assert!(Input::<CurrentNetwork>::from_str("input r0 as field.public").is_err());
119        // Missing 'as' keyword.
120        assert!(Input::<CurrentNetwork>::from_str("input r0 field.public;").is_err());
121        // Missing register.
122        assert!(Input::<CurrentNetwork>::from_str("input as field.public;").is_err());
123        // Missing 'input' keyword.
124        assert!(Input::<CurrentNetwork>::from_str("r0 as field.public;").is_err());
125        // Missing finalize type.
126        assert!(Input::<CurrentNetwork>::from_str("input r0 as ;").is_err());
127    }
128}