datex-core 0.0.14

The DATEX Core Rust implementation
Documentation
use crate::ast::expressions::{DatexExpression, VariableKind};

use crate::{prelude::*, types::r#type::Type};
use core::{cell::RefCell, fmt::Display};

#[derive(Clone, Debug)]
pub struct VariableMetadata {
    pub original_realm_index: usize,
    pub is_cross_realm: bool,
    pub shape: VariableShape,
    pub var_type: Option<Type>,
    pub name: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VariableShape {
    Type,
    Entity,
    Value(VariableKind),
}

impl From<VariableKind> for VariableShape {
    fn from(value: VariableKind) -> Self {
        VariableShape::Value(value)
    }
}

impl Display for VariableShape {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            VariableShape::Type => core::write!(f, "type"),
            VariableShape::Entity => core::write!(f, "entity"),
            VariableShape::Value(kind) => core::write!(f, "{kind}"),
        }
    }
}

#[derive(Default, Debug)]
pub struct AstMetadata {
    pub variables: Vec<VariableMetadata>,
    /// Indicates whether the AST is terminated (; at the end)
    /// A terminated script can never return a value
    pub is_terminated: bool,
}

impl AstMetadata {
    pub fn variable_metadata(&self, id: usize) -> Option<&VariableMetadata> {
        self.variables.get(id)
    }

    pub fn variable_metadata_mut(
        &mut self,
        id: usize,
    ) -> Option<&mut VariableMetadata> {
        self.variables.get_mut(id)
    }
}

#[derive(Debug, Clone, Default)]
pub struct RichAst {
    pub ast: DatexExpression,
    pub metadata: Rc<RefCell<AstMetadata>>,
}

impl RichAst {
    pub fn new(
        ast: DatexExpression,
        metadata: &Rc<RefCell<AstMetadata>>,
    ) -> Self {
        RichAst {
            ast,
            metadata: metadata.clone(),
        }
    }

    pub fn new_without_metadata(ast: DatexExpression) -> Self {
        RichAst {
            ast,
            metadata: Rc::new(RefCell::new(AstMetadata::default())),
        }
    }
}