mod command;
pub use command::*;
mod input;
use input::*;
mod output;
use output::*;
mod bytes;
mod parse;
use crate::Instruction;
use console::{
network::prelude::*,
program::{FinalizeType, Identifier, Register},
};
use indexmap::IndexSet;
#[derive(Clone, PartialEq, Eq)]
pub struct Finalize<N: Network> {
name: Identifier<N>,
inputs: IndexSet<Input<N>>,
commands: Vec<Command<N>>,
outputs: IndexSet<Output<N>>,
}
impl<N: Network> Finalize<N> {
pub fn new(name: Identifier<N>) -> Self {
Self { name, inputs: IndexSet::new(), commands: Vec::new(), outputs: IndexSet::new() }
}
pub const fn name(&self) -> &Identifier<N> {
&self.name
}
pub const fn inputs(&self) -> &IndexSet<Input<N>> {
&self.inputs
}
pub fn input_types(&self) -> Vec<FinalizeType<N>> {
self.inputs.iter().map(|input| *input.finalize_type()).collect()
}
pub fn commands(&self) -> &[Command<N>] {
&self.commands
}
pub const fn outputs(&self) -> &IndexSet<Output<N>> {
&self.outputs
}
pub fn output_types(&self) -> Vec<FinalizeType<N>> {
self.outputs.iter().map(|output| *output.finalize_type()).collect()
}
}
impl<N: Network> Finalize<N> {
#[inline]
fn add_input(&mut self, input: Input<N>) -> Result<()> {
ensure!(self.commands.is_empty(), "Cannot add inputs after commands have been added");
ensure!(self.outputs.is_empty(), "Cannot add inputs after outputs have been added");
ensure!(self.inputs.len() <= N::MAX_INPUTS, "Cannot add more than {} inputs", N::MAX_INPUTS);
ensure!(!self.inputs.contains(&input), "Cannot add duplicate input statement");
ensure!(matches!(input.register(), Register::Locator(..)), "Input register must be a locator");
self.inputs.insert(input);
Ok(())
}
#[inline]
pub fn add_command(&mut self, command: Command<N>) -> Result<()> {
ensure!(self.commands.len() <= N::MAX_COMMANDS, "Cannot add more than {} commands", N::MAX_COMMANDS);
if let Command::Instruction(instruction) = &command {
ensure!(
!matches!(instruction, Instruction::Call(..)),
"Forbidden operation: Finalize cannot invoke a 'call'"
);
for register in instruction.destinations() {
ensure!(matches!(register, Register::Locator(..)), "Destination register must be a locator");
}
}
self.commands.push(command);
Ok(())
}
#[inline]
fn add_output(&mut self, output: Output<N>) -> Result<()> {
ensure!(!self.commands.is_empty(), "Cannot add outputs before commands have been added");
ensure!(self.outputs.len() <= N::MAX_OUTPUTS, "Cannot add more than {} outputs", N::MAX_OUTPUTS);
ensure!(!self.outputs.contains(&output), "Cannot add duplicate output statement");
self.outputs.insert(output);
Ok(())
}
}
impl<N: Network> TypeName for Finalize<N> {
#[inline]
fn type_name() -> &'static str {
"finalize"
}
}