snarkvm_synthesizer_program/logic/command/
contains.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::{CallOperator, FinalizeStoreTrait, Opcode, Operand, RegistersTrait, StackTrait};
17use console::{
18    network::prelude::*,
19    program::{Literal, Register, Value},
20    types::Boolean,
21};
22
23/// A contains command, e.g. `contains accounts[r0] into r1;`.
24/// Contains is `true` if a (`key`, `value`) entry exists in `mapping`, stores the result in `destination`.
25#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct Contains<N: Network> {
27    /// The mapping name.
28    mapping: CallOperator<N>,
29    /// The operands.
30    operands: [Operand<N>; 1],
31    /// The destination register.
32    destination: Register<N>,
33}
34
35impl<N: Network> Contains<N> {
36    /// Returns the opcode.
37    #[inline]
38    pub const fn opcode() -> Opcode {
39        Opcode::Command("contains")
40    }
41
42    /// Returns the operands in the operation.
43    #[inline]
44    pub fn operands(&self) -> &[Operand<N>] {
45        &self.operands
46    }
47
48    /// Returns the mapping.
49    #[inline]
50    pub const fn mapping(&self) -> &CallOperator<N> {
51        &self.mapping
52    }
53
54    /// Returns the operand containing the key.
55    #[inline]
56    pub const fn key(&self) -> &Operand<N> {
57        &self.operands[0]
58    }
59
60    /// Returns the destination register.
61    #[inline]
62    pub const fn destination(&self) -> &Register<N> {
63        &self.destination
64    }
65}
66
67impl<N: Network> Contains<N> {
68    /// Finalizes the command.
69    pub fn finalize(
70        &self,
71        stack: &impl StackTrait<N>,
72        store: &impl FinalizeStoreTrait<N>,
73        registers: &mut impl RegistersTrait<N>,
74    ) -> Result<()> {
75        // Determine the program ID and mapping name.
76        let (program_id, mapping_name) = match self.mapping {
77            CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
78            CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
79        };
80
81        // Ensure the mapping exists.
82        if !store.contains_mapping_speculative(&program_id, &mapping_name)? {
83            bail!("Mapping '{program_id}/{mapping_name}' does not exist");
84        }
85
86        // Load the operand as a plaintext.
87        let key = registers.load_plaintext(stack, self.key())?;
88
89        // Determine if the key exists in the mapping.
90        let contains_key = store.contains_key_speculative(program_id, mapping_name, &key)?;
91
92        // Assign the value to the destination register.
93        registers.store(stack, &self.destination, Value::from(Literal::Boolean(Boolean::new(contains_key))))?;
94
95        Ok(())
96    }
97}
98
99impl<N: Network> Parser for Contains<N> {
100    /// Parses a string into an operation.
101    fn parse(string: &str) -> ParserResult<Self> {
102        // Parse the whitespace and comments from the string.
103        let (string, _) = Sanitizer::parse(string)?;
104        // Parse the opcode from the string.
105        let (string, _) = tag(*Self::opcode())(string)?;
106        // Parse the whitespace from the string.
107        let (string, _) = Sanitizer::parse_whitespaces(string)?;
108
109        // Parse the mapping name from the string.
110        let (string, mapping) = CallOperator::parse(string)?;
111        // Parse the "[" from the string.
112        let (string, _) = tag("[")(string)?;
113        // Parse the whitespace from the string.
114        let (string, _) = Sanitizer::parse_whitespaces(string)?;
115        // Parse the key operand from the string.
116        let (string, key) = Operand::parse(string)?;
117        // Parse the whitespace from the string.
118        let (string, _) = Sanitizer::parse_whitespaces(string)?;
119        // Parse the "]" from the string.
120        let (string, _) = tag("]")(string)?;
121
122        // Parse the whitespace from the string.
123        let (string, _) = Sanitizer::parse_whitespaces(string)?;
124        // Parse the "into" keyword from the string.
125        let (string, _) = tag("into")(string)?;
126        // Parse the whitespace from the string.
127        let (string, _) = Sanitizer::parse_whitespaces(string)?;
128        // Parse the destination register from the string.
129        let (string, destination) = Register::parse(string)?;
130
131        // Parse the whitespace from the string.
132        let (string, _) = Sanitizer::parse_whitespaces(string)?;
133        // Parse the ";" from the string.
134        let (string, _) = tag(";")(string)?;
135
136        Ok((string, Self { mapping, operands: [key], destination }))
137    }
138}
139
140impl<N: Network> FromStr for Contains<N> {
141    type Err = Error;
142
143    /// Parses a string into the command.
144    #[inline]
145    fn from_str(string: &str) -> Result<Self> {
146        match Self::parse(string) {
147            Ok((remainder, object)) => {
148                // Ensure the remainder is empty.
149                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
150                // Return the object.
151                Ok(object)
152            }
153            Err(error) => bail!("Failed to parse string. {error}"),
154        }
155    }
156}
157
158impl<N: Network> Debug for Contains<N> {
159    /// Prints the command as a string.
160    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
161        Display::fmt(self, f)
162    }
163}
164
165impl<N: Network> Display for Contains<N> {
166    /// Prints the command to a string.
167    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
168        // Print the command.
169        write!(f, "{} ", Self::opcode())?;
170        // Print the mapping and key operand.
171        write!(f, "{}[{}] into ", self.mapping, self.key())?;
172        // Print the destination register.
173        write!(f, "{};", self.destination)
174    }
175}
176
177impl<N: Network> FromBytes for Contains<N> {
178    /// Reads the command from a buffer.
179    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
180        // Read the mapping name.
181        let mapping = CallOperator::read_le(&mut reader)?;
182        // Read the key operand.
183        let key = Operand::read_le(&mut reader)?;
184        // Read the destination register.
185        let destination = Register::read_le(&mut reader)?;
186        // Return the command.
187        Ok(Self { mapping, operands: [key], destination })
188    }
189}
190
191impl<N: Network> ToBytes for Contains<N> {
192    /// Writes the operation to a buffer.
193    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
194        // Write the mapping name.
195        self.mapping.write_le(&mut writer)?;
196        // Write the key operand.
197        self.key().write_le(&mut writer)?;
198        // Write the destination register.
199        self.destination.write_le(&mut writer)
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use console::{network::MainnetV0, program::Register};
207
208    type CurrentNetwork = MainnetV0;
209
210    #[test]
211    fn test_parse() {
212        let (string, contains) = Contains::<CurrentNetwork>::parse("contains account[r0] into r1;").unwrap();
213        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
214        assert_eq!(contains.mapping, CallOperator::from_str("account").unwrap());
215        assert_eq!(contains.operands().len(), 1, "The number of operands is incorrect");
216        assert_eq!(contains.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
217        assert_eq!(contains.destination, Register::Locator(1), "The second operand is incorrect");
218
219        let (string, contains) =
220            Contains::<CurrentNetwork>::parse("contains credits.aleo/account[r0] into r1;").unwrap();
221        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
222        assert_eq!(contains.mapping, CallOperator::from_str("credits.aleo/account").unwrap());
223        assert_eq!(contains.operands().len(), 1, "The number of operands is incorrect");
224        assert_eq!(contains.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
225        assert_eq!(contains.destination, Register::Locator(1), "The second operand is incorrect");
226    }
227
228    #[test]
229    fn test_from_bytes() {
230        let (string, contains) = Contains::<CurrentNetwork>::parse("contains account[r0] into r1;").unwrap();
231        assert!(string.is_empty());
232        let bytes_le = contains.to_bytes_le().unwrap();
233        let result = Contains::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
234        assert!(result.is_ok())
235    }
236}