datex-core 0.0.14

The DATEX Core Rust implementation
Documentation
use crate::{
    global::stack_index::StackIndex,
    runtime::execution::{
        ExecutionError,
        execution_loop::state::{RuntimeExecutionStack, RuntimeExecutionState},
    },
    values::value_container::ValueContainer,
};

/// Represents a value in the runtime execution context, which can either be a direct
/// `ValueContainer` or a reference to a slot address where the value is stored.
#[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)
            }
        }
    }

    /// Creates an owned `ValueContainer` from the `RuntimeValue`.
    /// If the runtime value is inside a slot, it is popped
    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)?)
            }
        }
    }

    /// Creates an owned `ValueContainer` from the `RuntimeValue`.
    /// If the runtime value is inside a slot, it is popped and the previous stack index is returned as well
    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)))
            }
        }
    }
}