snarkvm_synthesizer_program/constructor/
parse.rs1use super::*;
17
18impl<N: Network> Parser for ConstructorCore<N> {
19 #[inline]
21 fn parse(string: &str) -> ParserResult<Self> {
22 let (string, _) = Sanitizer::parse(string)?;
24 let (string, _) = tag(Self::type_name())(string)?;
26 let (string, _) = Sanitizer::parse_whitespaces(string)?;
28 let (string, _) = tag(":")(string)?;
30
31 let (string, commands) = many1(Command::parse)(string)?;
33
34 map_res(take(0usize), move |_| {
35 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 fn from_str(string: &str) -> Result<Self> {
51 match Self::parse(string) {
52 Ok((remainder, object)) => {
53 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
55 Ok(object)
57 }
58 Err(error) => bail!("Failed to parse string. {error}"),
59 }
60 }
61}
62
63impl<N: Network> Debug for ConstructorCore<N> {
64 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
66 Display::fmt(self, f)
67 }
68}
69
70impl<N: Network> Display for ConstructorCore<N> {
71 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
73 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 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 assert!(Constructor::<CurrentNetwork>::parse("constructor:").is_err());
133 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}