snarkvm_synthesizer_program/logic/instruction/operation/
is.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, RegistersCircuit, RegistersTrait, StackTrait};
17use console::{
18    network::prelude::*,
19    program::{Literal, LiteralType, Plaintext, PlaintextType, Register, RegisterType, Value},
20    types::Boolean,
21};
22
23/// Computes whether `first` equals `second` as a boolean, storing the outcome in `destination`.
24pub type IsEq<N> = IsInstruction<N, { Variant::IsEq as u8 }>;
25/// Computes whether `first` does **not** equals `second` as a boolean, storing the outcome in `destination`.
26pub type IsNeq<N> = IsInstruction<N, { Variant::IsNeq as u8 }>;
27
28enum Variant {
29    IsEq,
30    IsNeq,
31}
32
33/// Computes an equality operation on two operands, and stores the outcome in `destination`.
34#[derive(Clone, PartialEq, Eq, Hash)]
35pub struct IsInstruction<N: Network, const VARIANT: u8> {
36    /// The operands.
37    operands: Vec<Operand<N>>,
38    /// The destination register.
39    destination: Register<N>,
40}
41
42impl<N: Network, const VARIANT: u8> IsInstruction<N, VARIANT> {
43    /// Initializes a new `is` instruction.
44    pub fn new(operands: Vec<Operand<N>>, destination: Register<N>) -> Result<Self> {
45        // Sanity check the number of operands.
46        ensure!(operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
47        // Return the instruction.
48        Ok(Self { operands, destination })
49    }
50
51    /// Returns the opcode.
52    pub const fn opcode() -> Opcode {
53        match VARIANT {
54            0 => Opcode::Is("is.eq"),
55            1 => Opcode::Is("is.neq"),
56            _ => panic!("Invalid 'is' instruction opcode"),
57        }
58    }
59
60    /// Returns the operands in the operation.
61    #[inline]
62    pub fn operands(&self) -> &[Operand<N>] {
63        // Sanity check that the operands is exactly two inputs.
64        debug_assert!(self.operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
65        // Return the operands.
66        &self.operands
67    }
68
69    /// Returns the destination register.
70    #[inline]
71    pub fn destinations(&self) -> Vec<Register<N>> {
72        vec![self.destination.clone()]
73    }
74}
75
76impl<N: Network, const VARIANT: u8> IsInstruction<N, VARIANT> {
77    /// Evaluates the instruction.
78    pub fn evaluate(&self, stack: &impl StackTrait<N>, registers: &mut impl RegistersTrait<N>) -> Result<()> {
79        // Ensure the number of operands is correct.
80        if self.operands.len() != 2 {
81            bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
82        }
83
84        // Retrieve the inputs.
85        let input_a = registers.load(stack, &self.operands[0])?;
86        let input_b = registers.load(stack, &self.operands[1])?;
87
88        // Check the inputs.
89        let output = match VARIANT {
90            0 => Literal::Boolean(Boolean::new(input_a == input_b)),
91            1 => Literal::Boolean(Boolean::new(input_a != input_b)),
92            _ => bail!("Invalid 'is' variant: {VARIANT}"),
93        };
94        // Store the output.
95        registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
96    }
97
98    /// Executes the instruction.
99    pub fn execute<A: circuit::Aleo<Network = N>>(
100        &self,
101        stack: &impl StackTrait<N>,
102        registers: &mut impl RegistersCircuit<N, A>,
103    ) -> Result<()> {
104        // Ensure the number of operands is correct.
105        if self.operands.len() != 2 {
106            bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
107        }
108
109        // Retrieve the inputs.
110        let input_a = registers.load_circuit(stack, &self.operands[0])?;
111        let input_b = registers.load_circuit(stack, &self.operands[1])?;
112
113        // Check the inputs.
114        let output = match VARIANT {
115            0 => circuit::Literal::Boolean(input_a.is_equal(&input_b)),
116            1 => circuit::Literal::Boolean(input_a.is_not_equal(&input_b)),
117            _ => bail!("Invalid 'is' variant: {VARIANT}"),
118        };
119        // Convert the output to a stack value.
120        let output = circuit::Value::Plaintext(circuit::Plaintext::Literal(output, Default::default()));
121        // Store the output.
122        registers.store_circuit(stack, &self.destination, output)
123    }
124
125    /// Finalizes the instruction.
126    #[inline]
127    pub fn finalize(&self, stack: &impl StackTrait<N>, registers: &mut impl RegistersTrait<N>) -> Result<()> {
128        self.evaluate(stack, registers)
129    }
130
131    /// Returns the output type from the given program and input types.
132    pub fn output_types(
133        &self,
134        _stack: &impl StackTrait<N>,
135        input_types: &[RegisterType<N>],
136    ) -> Result<Vec<RegisterType<N>>> {
137        // Ensure the number of input types is correct.
138        if input_types.len() != 2 {
139            bail!("Instruction '{}' expects 2 inputs, found {} inputs", Self::opcode(), input_types.len())
140        }
141        // Ensure the operands are of the same type.
142        if input_types[0] != input_types[1] {
143            bail!(
144                "Instruction '{}' expects inputs of the same type. Found inputs of type '{}' and '{}'",
145                Self::opcode(),
146                input_types[0],
147                input_types[1]
148            )
149        }
150        // Ensure the number of operands is correct.
151        if self.operands.len() != 2 {
152            bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
153        }
154
155        match VARIANT {
156            0 | 1 => Ok(vec![RegisterType::Plaintext(PlaintextType::Literal(LiteralType::Boolean))]),
157            _ => bail!("Invalid 'is' variant: {VARIANT}"),
158        }
159    }
160}
161
162impl<N: Network, const VARIANT: u8> Parser for IsInstruction<N, VARIANT> {
163    /// Parses a string into an operation.
164    fn parse(string: &str) -> ParserResult<Self> {
165        // Parse the opcode from the string.
166        let (string, _) = tag(*Self::opcode())(string)?;
167        // Parse the whitespace from the string.
168        let (string, _) = Sanitizer::parse_whitespaces(string)?;
169        // Parse the first operand from the string.
170        let (string, first) = Operand::parse(string)?;
171        // Parse the whitespace from the string.
172        let (string, _) = Sanitizer::parse_whitespaces(string)?;
173        // Parse the second operand from the string.
174        let (string, second) = Operand::parse(string)?;
175        // Parse the whitespace from the string.
176        let (string, _) = Sanitizer::parse_whitespaces(string)?;
177        // Parse the "into" from the string.
178        let (string, _) = tag("into")(string)?;
179        // Parse the whitespace from the string.
180        let (string, _) = Sanitizer::parse_whitespaces(string)?;
181        // Parse the destination register from the string.
182        let (string, destination) = Register::parse(string)?;
183
184        Ok((string, Self { operands: vec![first, second], destination }))
185    }
186}
187
188impl<N: Network, const VARIANT: u8> FromStr for IsInstruction<N, VARIANT> {
189    type Err = Error;
190
191    /// Parses a string into an operation.
192    fn from_str(string: &str) -> Result<Self> {
193        match Self::parse(string) {
194            Ok((remainder, object)) => {
195                // Ensure the remainder is empty.
196                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
197                // Return the object.
198                Ok(object)
199            }
200            Err(error) => bail!("Failed to parse string. {error}"),
201        }
202    }
203}
204
205impl<N: Network, const VARIANT: u8> Debug for IsInstruction<N, VARIANT> {
206    /// Prints the operation as a string.
207    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
208        Display::fmt(self, f)
209    }
210}
211
212impl<N: Network, const VARIANT: u8> Display for IsInstruction<N, VARIANT> {
213    /// Prints the operation to a string.
214    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
215        // Ensure the number of operands is 2.
216        if self.operands.len() != 2 {
217            return Err(fmt::Error);
218        }
219        // Print the operation.
220        write!(f, "{} ", Self::opcode())?;
221        self.operands.iter().try_for_each(|operand| write!(f, "{operand} "))?;
222        write!(f, "into {}", self.destination)
223    }
224}
225
226impl<N: Network, const VARIANT: u8> FromBytes for IsInstruction<N, VARIANT> {
227    /// Reads the operation from a buffer.
228    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
229        // Initialize the vector for the operands.
230        let mut operands = Vec::with_capacity(2);
231        // Read the operands.
232        for _ in 0..2 {
233            operands.push(Operand::read_le(&mut reader)?);
234        }
235        // Read the destination register.
236        let destination = Register::read_le(&mut reader)?;
237
238        // Return the operation.
239        Ok(Self { operands, destination })
240    }
241}
242
243impl<N: Network, const VARIANT: u8> ToBytes for IsInstruction<N, VARIANT> {
244    /// Writes the operation to a buffer.
245    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
246        // Ensure the number of operands is 2.
247        if self.operands.len() != 2 {
248            return Err(error(format!("The number of operands must be 2, found {}", self.operands.len())));
249        }
250        // Write the operands.
251        self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
252        // Write the destination register.
253        self.destination.write_le(&mut writer)
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use console::network::MainnetV0;
261
262    type CurrentNetwork = MainnetV0;
263
264    #[test]
265    fn test_parse() {
266        let (string, is) = IsEq::<CurrentNetwork>::parse("is.eq r0 r1 into r2").unwrap();
267        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
268        assert_eq!(is.operands.len(), 2, "The number of operands is incorrect");
269        assert_eq!(is.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
270        assert_eq!(is.operands[1], Operand::Register(Register::Locator(1)), "The second operand is incorrect");
271        assert_eq!(is.destination, Register::Locator(2), "The destination register is incorrect");
272
273        let (string, is) = IsNeq::<CurrentNetwork>::parse("is.neq r0 r1 into r2").unwrap();
274        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
275        assert_eq!(is.operands.len(), 2, "The number of operands is incorrect");
276        assert_eq!(is.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
277        assert_eq!(is.operands[1], Operand::Register(Register::Locator(1)), "The second operand is incorrect");
278        assert_eq!(is.destination, Register::Locator(2), "The destination register is incorrect");
279    }
280}