use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::{model::{DataRef, Func, Graph}, runtime::{instruction::{Instruction, Instructions}, instructions::Base, proc::ProcEnv, Error, Val}};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FuncLit {
pub dref: DataRef,
pub func: Func,
}
#[typetag::serde(name = "FuncLit")]
impl Instruction for FuncLit {
fn exec(&self, env: &mut ProcEnv, graph: &mut Graph) -> Result<Option<Instructions>, Error> {
let mut instructions = Instructions::default();
if self.dref.data_exists(&graph) {
instructions.push(Arc::new(Base::Literal(Val::Fn(self.dref.clone()))));
} else {
let mut self_ptr = env.self_ptr();
if let Some(ns) = env.new_stack.last() {
self_ptr = ns.clone(); }
if let Some(dref) = graph.insert_stof_data(&self_ptr, &self.dref, Box::new(self.func.clone()), Some(self.dref.clone())) {
instructions.push(Arc::new(Base::Literal(Val::Fn(dref))));
}
}
Ok(Some(instructions))
}
}