snarkvm_synthesizer_program/mapping/
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 Mapping<N> {
19    /// Parses a string into a mapping.
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 'mapping' 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 mapping name from the string.
29        let (string, name) = Identifier::<N>::parse(string)?;
30        // Parse the whitespace from the string.
31        let (string, _) = Sanitizer::parse_whitespaces(string)?;
32        // Parse the colon ':' keyword from the string.
33        let (string, _) = tag(":")(string)?;
34
35        // Parse the key statement from the string.
36        let (string, key) = MapKey::parse(string)?;
37        // Parse the value statement from the string.
38        let (string, value) = MapValue::parse(string)?;
39
40        // Return the mapping.
41        Ok((string, Self::new(name, key, value)))
42    }
43}
44
45impl<N: Network> FromStr for Mapping<N> {
46    type Err = Error;
47
48    /// Returns a mapping from a string literal.
49    fn from_str(string: &str) -> Result<Self> {
50        match Self::parse(string) {
51            Ok((remainder, object)) => {
52                // Ensure the remainder is empty.
53                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
54                // Return the object.
55                Ok(object)
56            }
57            Err(error) => bail!("Failed to parse string. {error}"),
58        }
59    }
60}
61
62impl<N: Network> Debug for Mapping<N> {
63    /// Prints the mapping as a string.
64    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
65        Display::fmt(self, f)
66    }
67}
68
69impl<N: Network> Display for Mapping<N> {
70    /// Prints the mapping as a string.
71    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
72        // Write the mapping to a string.
73        write!(f, "{} {}:", Self::type_name(), self.name)?;
74        write!(f, "\n    {}", self.key)?;
75        write!(f, "\n    {}", self.value)
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use console::network::MainnetV0;
83
84    type CurrentNetwork = MainnetV0;
85
86    #[test]
87    fn test_mapping_parse() {
88        let mapping = Mapping::<CurrentNetwork>::parse(
89            r"
90mapping foo:
91    key as field.public;
92    value as field.public;",
93        )
94        .unwrap()
95        .1;
96        assert_eq!("foo", mapping.name().to_string());
97        assert_eq!("field", mapping.key.plaintext_type().to_string());
98        assert_eq!("field", mapping.value.plaintext_type().to_string());
99    }
100
101    #[test]
102    fn test_mapping_display() {
103        let expected = r"mapping foo:
104    key as field.public;
105    value as field.public;";
106        let mapping = Mapping::<CurrentNetwork>::parse(expected).unwrap().1;
107        assert_eq!(expected, format!("{mapping}"),);
108    }
109}