snarkvm_synthesizer_program/logic/command/
await_.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 crate::Opcode;
17use console::{network::prelude::*, program::Register};
18
19/// An await command, e.g. `await r0;`.
20/// Awaits the result of an asynchronous call (a future).
21/// Note that asynchronous calls currently do not return a value.
22#[derive(Clone, PartialEq, Eq, Hash)]
23pub struct Await<N: Network> {
24    /// The register containing the future.
25    register: Register<N>,
26}
27
28impl<N: Network> Await<N> {
29    /// Returns the opcode.
30    #[inline]
31    pub const fn opcode() -> Opcode {
32        Opcode::Command("await")
33    }
34
35    /// Returns the register containing the future.
36    #[inline]
37    pub const fn register(&self) -> &Register<N> {
38        &self.register
39    }
40}
41
42impl<N: Network> Parser for Await<N> {
43    /// Parses a string into an operation.
44    #[inline]
45    fn parse(string: &str) -> ParserResult<Self> {
46        // Parse the whitespace and comments from the string.
47        let (string, _) = Sanitizer::parse(string)?;
48        // Parse the opcode from the string.
49        let (string, _) = tag(*Self::opcode())(string)?;
50        // Parse the whitespace from the string.
51        let (string, _) = Sanitizer::parse_whitespaces(string)?;
52        // Parse the register from the string.
53        let (string, register) = Register::parse(string)?;
54        // Parse the whitespace from the string.
55        let (string, _) = Sanitizer::parse_whitespaces(string)?;
56        // Parse the ';' from the string.
57        let (string, _) = tag(";")(string)?;
58
59        Ok((string, Self { register }))
60    }
61}
62
63impl<N: Network> FromStr for Await<N> {
64    type Err = Error;
65
66    /// Parses a string into the command.
67    #[inline]
68    fn from_str(string: &str) -> Result<Self> {
69        match Self::parse(string) {
70            Ok((remainder, object)) => {
71                // Ensure the remainder is empty.
72                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
73                // Return the object.
74                Ok(object)
75            }
76            Err(error) => bail!("Failed to parse string. {error}"),
77        }
78    }
79}
80
81impl<N: Network> Debug for Await<N> {
82    /// Prints the command as a string.
83    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
84        Display::fmt(self, f)
85    }
86}
87
88impl<N: Network> Display for Await<N> {
89    /// Prints the command to a string.
90    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
91        // Print the command.
92        write!(f, "await {};", self.register)
93    }
94}
95
96impl<N: Network> FromBytes for Await<N> {
97    /// Reads the command from a buffer.
98    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
99        // Read the register.
100        let register = Register::read_le(&mut reader)?;
101
102        Ok(Self { register })
103    }
104}
105
106impl<N: Network> ToBytes for Await<N> {
107    /// Writes the operation to a buffer.
108    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
109        // Write the register.
110        self.register.write_le(&mut writer)?;
111        Ok(())
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use console::{network::MainnetV0, program::Register};
119
120    type CurrentNetwork = MainnetV0;
121
122    #[test]
123    fn test_parse() {
124        let (string, await_) = Await::<CurrentNetwork>::parse("await r1;").unwrap();
125        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
126        assert_eq!(await_.register(), &Register::Locator(1));
127    }
128}