snarkvm_synthesizer_program/logic/instruction/operation/
is.rsuse crate::{
Opcode,
Operand,
traits::{RegistersLoad, RegistersLoadCircuit, RegistersStore, RegistersStoreCircuit, StackMatches, StackProgram},
};
use console::{
network::prelude::*,
program::{Literal, LiteralType, Plaintext, PlaintextType, Register, RegisterType, Value},
types::Boolean,
};
pub type IsEq<N> = IsInstruction<N, { Variant::IsEq as u8 }>;
pub type IsNeq<N> = IsInstruction<N, { Variant::IsNeq as u8 }>;
enum Variant {
IsEq,
IsNeq,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct IsInstruction<N: Network, const VARIANT: u8> {
operands: Vec<Operand<N>>,
destination: Register<N>,
}
impl<N: Network, const VARIANT: u8> IsInstruction<N, VARIANT> {
#[inline]
pub fn new(operands: Vec<Operand<N>>, destination: Register<N>) -> Result<Self> {
ensure!(operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
Ok(Self { operands, destination })
}
#[inline]
pub const fn opcode() -> Opcode {
match VARIANT {
0 => Opcode::Is("is.eq"),
1 => Opcode::Is("is.neq"),
_ => panic!("Invalid 'is' instruction opcode"),
}
}
#[inline]
pub fn operands(&self) -> &[Operand<N>] {
debug_assert!(self.operands.len() == 2, "Instruction '{}' must have two operands", Self::opcode());
&self.operands
}
#[inline]
pub fn destinations(&self) -> Vec<Register<N>> {
vec![self.destination.clone()]
}
}
impl<N: Network, const VARIANT: u8> IsInstruction<N, VARIANT> {
#[inline]
pub fn evaluate(
&self,
stack: &(impl StackMatches<N> + StackProgram<N>),
registers: &mut (impl RegistersLoad<N> + RegistersStore<N>),
) -> Result<()> {
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
let input_a = registers.load(stack, &self.operands[0])?;
let input_b = registers.load(stack, &self.operands[1])?;
let output = match VARIANT {
0 => Literal::Boolean(Boolean::new(input_a == input_b)),
1 => Literal::Boolean(Boolean::new(input_a != input_b)),
_ => bail!("Invalid 'is' variant: {VARIANT}"),
};
registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
}
#[inline]
pub fn execute<A: circuit::Aleo<Network = N>>(
&self,
stack: &(impl StackMatches<N> + StackProgram<N>),
registers: &mut (impl RegistersLoadCircuit<N, A> + RegistersStoreCircuit<N, A>),
) -> Result<()> {
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
let input_a = registers.load_circuit(stack, &self.operands[0])?;
let input_b = registers.load_circuit(stack, &self.operands[1])?;
let output = match VARIANT {
0 => circuit::Literal::Boolean(input_a.is_equal(&input_b)),
1 => circuit::Literal::Boolean(input_a.is_not_equal(&input_b)),
_ => bail!("Invalid 'is' variant: {VARIANT}"),
};
let output = circuit::Value::Plaintext(circuit::Plaintext::Literal(output, Default::default()));
registers.store_circuit(stack, &self.destination, output)
}
#[inline]
pub fn finalize(
&self,
stack: &(impl StackMatches<N> + StackProgram<N>),
registers: &mut (impl RegistersLoad<N> + RegistersStore<N>),
) -> Result<()> {
self.evaluate(stack, registers)
}
#[inline]
pub fn output_types(
&self,
_stack: &impl StackProgram<N>,
input_types: &[RegisterType<N>],
) -> Result<Vec<RegisterType<N>>> {
if input_types.len() != 2 {
bail!("Instruction '{}' expects 2 inputs, found {} inputs", Self::opcode(), input_types.len())
}
if input_types[0] != input_types[1] {
bail!(
"Instruction '{}' expects inputs of the same type. Found inputs of type '{}' and '{}'",
Self::opcode(),
input_types[0],
input_types[1]
)
}
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
match VARIANT {
0 | 1 => Ok(vec![RegisterType::Plaintext(PlaintextType::Literal(LiteralType::Boolean))]),
_ => bail!("Invalid 'is' variant: {VARIANT}"),
}
}
}
impl<N: Network, const VARIANT: u8> Parser for IsInstruction<N, VARIANT> {
#[inline]
fn parse(string: &str) -> ParserResult<Self> {
let (string, _) = tag(*Self::opcode())(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, first) = Operand::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, second) = Operand::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag("into")(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, destination) = Register::parse(string)?;
Ok((string, Self { operands: vec![first, second], destination }))
}
}
impl<N: Network, const VARIANT: u8> FromStr for IsInstruction<N, VARIANT> {
type Err = Error;
#[inline]
fn from_str(string: &str) -> Result<Self> {
match Self::parse(string) {
Ok((remainder, object)) => {
ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
Ok(object)
}
Err(error) => bail!("Failed to parse string. {error}"),
}
}
}
impl<N: Network, const VARIANT: u8> Debug for IsInstruction<N, VARIANT> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network, const VARIANT: u8> Display for IsInstruction<N, VARIANT> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.operands.len() != 2 {
return Err(fmt::Error);
}
write!(f, "{} ", Self::opcode())?;
self.operands.iter().try_for_each(|operand| write!(f, "{operand} "))?;
write!(f, "into {}", self.destination)
}
}
impl<N: Network, const VARIANT: u8> FromBytes for IsInstruction<N, VARIANT> {
fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
let mut operands = Vec::with_capacity(2);
for _ in 0..2 {
operands.push(Operand::read_le(&mut reader)?);
}
let destination = Register::read_le(&mut reader)?;
Ok(Self { operands, destination })
}
}
impl<N: Network, const VARIANT: u8> ToBytes for IsInstruction<N, VARIANT> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
if self.operands.len() != 2 {
return Err(error(format!("The number of operands must be 2, found {}", self.operands.len())));
}
self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
self.destination.write_le(&mut writer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::network::MainnetV0;
type CurrentNetwork = MainnetV0;
#[test]
fn test_parse() {
let (string, is) = IsEq::<CurrentNetwork>::parse("is.eq r0 r1 into r2").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(is.operands.len(), 2, "The number of operands is incorrect");
assert_eq!(is.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(is.operands[1], Operand::Register(Register::Locator(1)), "The second operand is incorrect");
assert_eq!(is.destination, Register::Locator(2), "The destination register is incorrect");
let (string, is) = IsNeq::<CurrentNetwork>::parse("is.neq r0 r1 into r2").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(is.operands.len(), 2, "The number of operands is incorrect");
assert_eq!(is.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(is.operands[1], Operand::Register(Register::Locator(1)), "The second operand is incorrect");
assert_eq!(is.destination, Register::Locator(2), "The destination register is incorrect");
}
}