use std::sync::Arc;
use arcstr::ArcStr;
use imbl::Vector;
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
use crate::{model::Graph, runtime::{instruction::{Instruction, Instructions}, instructions::Base, proc::ProcEnv, Error}};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TryCatchIns {
pub try_ins: Vector<Arc<dyn Instruction>>,
pub err_ins: Vector<Arc<dyn Instruction>>,
pub catch_ins: Vector<Arc<dyn Instruction>>,
}
#[typetag::serde(name = "TryCatchIns")]
impl Instruction for TryCatchIns {
fn exec(&self, env: &mut ProcEnv, _graph: &mut Graph) -> Result<Option<Instructions>, Error> {
let catch_tag: ArcStr = nanoid!(10).into();
let end_tag: ArcStr = nanoid!(10).into();
let size = env.stack.len();
let try_depth = env.try_stack.len();
let mut instructions = Instructions::default();
instructions.push(Arc::new(Base::Try(catch_tag.clone()))); instructions.append(&self.try_ins);
instructions.push(Arc::new(Base::PopTryUntilDepth(try_depth)));
instructions.push(Arc::new(Base::CtrlForwardTo(end_tag.clone())));
instructions.push(Arc::new(Base::Tag(catch_tag))); instructions.push(Arc::new(Base::PopTryUntilDepth(try_depth))); instructions.append(&self.err_ins);
instructions.push(Arc::new(Base::PopUntilStackCount(size)));
instructions.append(&self.catch_ins);
instructions.push(Arc::new(Base::Tag(end_tag)));
Ok(Some(instructions))
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use crate::{model::Graph, runtime::{instructions::{trycatch::TryCatchIns, Base}, Num, Runtime, Val}};
#[test]
fn no_catch() {
let mut try_catch = TryCatchIns::default();
try_catch.try_ins.push_back(Arc::new(Base::Literal(Val::Num(Num::Float(42.2)))));
try_catch.catch_ins.push_back(Arc::new(Base::Literal(Val::Num(Num::Float(1242.2)))));
let mut graph = Graph::default();
let res = Runtime::eval(&mut graph, Arc::new(try_catch)).unwrap();
assert_eq!(res, 42.2.into());
}
}