Skip to main content

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, Operand};
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 operands.
25    /// Note: Byte and string parsing guarantees that this is a single register operand.
26    operands: [Operand<N>; 1],
27}
28
29impl<N: Network> Await<N> {
30    /// Returns the opcode.
31    #[inline]
32    pub const fn opcode() -> Opcode {
33        Opcode::Command("await")
34    }
35
36    /// Returns the operands in the command.
37    #[inline]
38    pub fn operands(&self) -> &[Operand<N>] {
39        &self.operands
40    }
41
42    /// Returns the register containing the future.
43    #[inline]
44    pub fn register(&self) -> &Register<N> {
45        // Note: This byte and string parsing guarantees that the operand is a single register.
46        let Operand::Register(register) = &self.operands[0] else {
47            unreachable!("The operands of an await command must be a single register.")
48        };
49        // Return the register.
50        register
51    }
52
53    /// Returns whether this command refers to an external struct.
54    #[inline]
55    pub fn contains_external_struct(&self) -> bool {
56        false
57    }
58}
59
60impl<N: Network> Parser for Await<N> {
61    /// Parses a string into an operation.
62    #[inline]
63    fn parse(string: &str) -> ParserResult<Self> {
64        // Parse the whitespace and comments from the string.
65        let (string, _) = Sanitizer::parse(string)?;
66        // Parse the opcode from the string.
67        let (string, _) = tag(*Self::opcode())(string)?;
68        // Parse the whitespace from the string.
69        let (string, _) = Sanitizer::parse_whitespaces(string)?;
70        // Parse the register from the string.
71        let (string, register) = Register::parse(string)?;
72        // Parse the whitespace from the string.
73        let (string, _) = Sanitizer::parse_whitespaces(string)?;
74        // Parse the ';' from the string.
75        let (string, _) = tag(";")(string)?;
76
77        Ok((string, Self { operands: [Operand::Register(register)] }))
78    }
79}
80
81impl<N: Network> FromStr for Await<N> {
82    type Err = Error;
83
84    /// Parses a string into the command.
85    #[inline]
86    fn from_str(string: &str) -> Result<Self> {
87        match Self::parse(string) {
88            Ok((remainder, object)) => {
89                // Ensure the remainder is empty.
90                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
91                // Return the object.
92                Ok(object)
93            }
94            Err(error) => bail!("Failed to parse string. {error}"),
95        }
96    }
97}
98
99impl<N: Network> Debug for Await<N> {
100    /// Prints the command as a string.
101    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
102        Display::fmt(self, f)
103    }
104}
105
106impl<N: Network> Display for Await<N> {
107    /// Prints the command to a string.
108    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
109        // Print the command.
110        write!(f, "await {};", self.register())
111    }
112}
113
114impl<N: Network> FromBytes for Await<N> {
115    /// Reads the command from a buffer.
116    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
117        // Read the register.
118        let register = Register::read_le(&mut reader)?;
119
120        Ok(Self { operands: [Operand::Register(register)] })
121    }
122}
123
124impl<N: Network> ToBytes for Await<N> {
125    /// Writes the operation to a buffer.
126    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
127        // Write the register.
128        self.register().write_le(&mut writer)?;
129        Ok(())
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use console::{network::MainnetV0, program::Register};
137
138    type CurrentNetwork = MainnetV0;
139
140    #[test]
141    fn test_parse() {
142        let (string, await_) = Await::<CurrentNetwork>::parse("await r1;").unwrap();
143        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
144        assert_eq!(await_.register(), &Register::Locator(1));
145    }
146}