use crate::{
global::stack_index::StackIndex,
runtime::execution::{
ExecutionError,
execution_loop::state::{RuntimeExecutionStack, RuntimeExecutionState},
},
values::value_container::ValueContainer,
};
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeValue {
ValueContainer(ValueContainer),
StackValue(StackIndex),
}
impl From<ValueContainer> for RuntimeValue {
fn from(value: ValueContainer) -> Self {
RuntimeValue::ValueContainer(value)
}
}
impl From<StackIndex> for RuntimeValue {
fn from(index: StackIndex) -> Self {
RuntimeValue::StackValue(index)
}
}
impl RuntimeValue {
pub fn as_value_container<'a>(
&'a self,
slots: &'a RuntimeExecutionStack,
) -> Result<&'a ValueContainer, ExecutionError> {
match self {
RuntimeValue::ValueContainer(vc) => Ok(vc),
RuntimeValue::StackValue(index) => slots.get_stack_value(*index),
}
}
pub fn as_value_container_mut<'a>(
&'a mut self,
slots: &'a mut RuntimeExecutionStack,
) -> Result<&'a mut ValueContainer, ExecutionError> {
match self {
RuntimeValue::ValueContainer(vc) => Ok(vc),
RuntimeValue::StackValue(index) => {
slots.get_stack_value_mut(*index)
}
}
}
pub fn into_value_container(
self,
state: &mut RuntimeExecutionState,
) -> Result<ValueContainer, ExecutionError> {
match self {
RuntimeValue::ValueContainer(vc) => Ok(vc),
RuntimeValue::StackValue(addr) => {
Ok(state.stack.take_stack_value(addr)?)
}
}
}
pub fn into_value_container_with_previous_stack_index(
self,
state: &mut RuntimeExecutionState,
) -> Result<(ValueContainer, Option<StackIndex>), ExecutionError> {
match self {
RuntimeValue::ValueContainer(vc) => Ok((vc, None)),
RuntimeValue::StackValue(addr) => {
Ok((state.stack.take_stack_value(addr)?, Some(addr)))
}
}
}
}