snarkvm_synthesizer_program/logic/instruction/operation/
is.rs1use 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
23pub type IsEq<N> = IsInstruction<N, { Variant::IsEq as u8 }>;
25pub type IsNeq<N> = IsInstruction<N, { Variant::IsNeq as u8 }>;
27
28enum Variant {
29 IsEq,
30 IsNeq,
31}
32
33#[derive(Clone, PartialEq, Eq, Hash)]
35pub struct IsInstruction<N: Network, const VARIANT: u8> {
36 operands: Vec<Operand<N>>,
38 destination: Register<N>,
40}
41
42impl<N: Network, const VARIANT: u8> IsInstruction<N, VARIANT> {
43 pub fn new(operands: Vec<Operand<N>>, destination: Register<N>) -> Result<Self> {
45 ensure!(operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
47 Ok(Self { operands, destination })
49 }
50
51 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 #[inline]
62 pub fn operands(&self) -> &[Operand<N>] {
63 debug_assert!(self.operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
65 &self.operands
67 }
68
69 #[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 pub fn evaluate(&self, stack: &impl StackTrait<N>, registers: &mut impl RegistersTrait<N>) -> Result<()> {
79 if self.operands.len() != 2 {
81 bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
82 }
83
84 let input_a = registers.load(stack, &self.operands[0])?;
86 let input_b = registers.load(stack, &self.operands[1])?;
87
88 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 registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
96 }
97
98 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 if self.operands.len() != 2 {
106 bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
107 }
108
109 let input_a = registers.load_circuit(stack, &self.operands[0])?;
111 let input_b = registers.load_circuit(stack, &self.operands[1])?;
112
113 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 let output = circuit::Value::Plaintext(circuit::Plaintext::Literal(output, Default::default()));
121 registers.store_circuit(stack, &self.destination, output)
123 }
124
125 #[inline]
127 pub fn finalize(&self, stack: &impl StackTrait<N>, registers: &mut impl RegistersTrait<N>) -> Result<()> {
128 self.evaluate(stack, registers)
129 }
130
131 pub fn output_types(
133 &self,
134 _stack: &impl StackTrait<N>,
135 input_types: &[RegisterType<N>],
136 ) -> Result<Vec<RegisterType<N>>> {
137 if input_types.len() != 2 {
139 bail!("Instruction '{}' expects 2 inputs, found {} inputs", Self::opcode(), input_types.len())
140 }
141 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 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 fn parse(string: &str) -> ParserResult<Self> {
165 let (string, _) = tag(*Self::opcode())(string)?;
167 let (string, _) = Sanitizer::parse_whitespaces(string)?;
169 let (string, first) = Operand::parse(string)?;
171 let (string, _) = Sanitizer::parse_whitespaces(string)?;
173 let (string, second) = Operand::parse(string)?;
175 let (string, _) = Sanitizer::parse_whitespaces(string)?;
177 let (string, _) = tag("into")(string)?;
179 let (string, _) = Sanitizer::parse_whitespaces(string)?;
181 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 fn from_str(string: &str) -> Result<Self> {
193 match Self::parse(string) {
194 Ok((remainder, object)) => {
195 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
197 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 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 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
215 if self.operands.len() != 2 {
217 return Err(fmt::Error);
218 }
219 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 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
229 let mut operands = Vec::with_capacity(2);
231 for _ in 0..2 {
233 operands.push(Operand::read_le(&mut reader)?);
234 }
235 let destination = Register::read_le(&mut reader)?;
237
238 Ok(Self { operands, destination })
240 }
241}
242
243impl<N: Network, const VARIANT: u8> ToBytes for IsInstruction<N, VARIANT> {
244 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
246 if self.operands.len() != 2 {
248 return Err(error(format!("The number of operands must be 2, found {}", self.operands.len())));
249 }
250 self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
252 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}