runes-core 0.1.0

Core types and traits for the Runes language
Documentation
use std::collections::BTreeMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};

use crate::ast::Block;
use crate::symbol::SymbolId;

/// Monotonic counter for instance identity.
static INSTANCE_ID_COUNTER: AtomicU64 = AtomicU64::new(1);

/// Data backing a first-class function value.
pub struct FunctionData {
    /// Function name (None for anonymous/lambda).
    pub name: Option<String>,
    /// Parameter names.
    pub params: Vec<String>,
    /// AST body (used by tree-walking evaluator).
    pub body: Block,
    /// Captured bindings from defining scope (evaluator closures, capture-by-value).
    pub captured_bindings: Vec<(SymbolId, Value)>,
    /// Index into the chunk's functions array (VM path).
    pub func_index: Option<u16>,
    /// Captured local values for VM closures.
    pub captured_values: Vec<Value>,
}

impl fmt::Debug for FunctionData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FunctionData")
            .field("name", &self.name)
            .field("params", &self.params)
            .field("captures", &self.captured_bindings.len())
            .finish()
    }
}

/// Data backing a class instance. Wrapped in `Arc` for identity semantics.
pub struct InstanceData {
    /// The class this instance belongs to.
    pub class_name: String,
    /// Unique identity (for Debug/Display, not equality).
    pub id: u64,
    /// Mutable field storage. Interior mutability allows field writes through shared references.
    pub fields: RwLock<BTreeMap<SymbolId, Value>>,
}

impl fmt::Debug for InstanceData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InstanceData")
            .field("class_name", &self.class_name)
            .field("id", &self.id)
            .field("fields", &"<RwLock>")
            .finish()
    }
}

/// A runtime value in the Runes language.
#[derive(Debug, Clone)]
pub enum Value {
    /// Signed 64-bit integer. The primary numeric type.
    Integer(i64),
    /// IEEE 754 double-precision floating-point number.
    Float(f64),
    /// Interned symbol constant.
    Symbol(SymbolId),
    /// Immutable UTF-8 string.
    String(Arc<str>),
    /// Boolean.
    Bool(bool),
    /// Absence of value.
    Nil,
    /// Ordered, heterogeneous collection.
    /// Wrapped in `Arc` for O(1) clone — arrays are the most frequently copied
    /// value type in hot loops (verb dispatch, function calls, scope operations).
    Array(Arc<Vec<Value>>),
    /// Symbol-keyed key-value collection.
    Map(BTreeMap<SymbolId, Value>),
    /// Opaque host-provided reference.
    Handle(HandleType, u64),
    /// Class instance with identity semantics.
    Instance(Arc<InstanceData>),
    /// First-class function value (closure).
    Function(Arc<FunctionData>),
}

/// Type identifier for opaque host handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HandleType(pub u32);

impl Value {
    pub fn is_truthy(&self) -> bool {
        !matches!(self, Value::Nil | Value::Bool(false))
    }

    pub fn is_nil(&self) -> bool {
        matches!(self, Value::Nil)
    }

    pub fn as_integer(&self) -> Option<i64> {
        match self {
            Value::Integer(n) => Some(*n),
            _ => None,
        }
    }

    pub fn as_float(&self) -> Option<f64> {
        match self {
            Value::Float(f) => Some(*f),
            _ => None,
        }
    }

    pub fn as_symbol(&self) -> Option<SymbolId> {
        match self {
            Value::Symbol(id) => Some(*id),
            _ => None,
        }
    }

    pub fn as_string(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[Value]> {
        match self {
            Value::Array(arr) => Some(arr.as_slice()),
            _ => None,
        }
    }

    pub fn as_map(&self) -> Option<&BTreeMap<SymbolId, Value>> {
        match self {
            Value::Map(map) => Some(map),
            _ => None,
        }
    }

    pub fn type_name(&self) -> &str {
        match self {
            Value::Integer(_) => "Integer",
            Value::Float(_) => "Float",
            Value::Symbol(_) => "Symbol",
            Value::String(_) => "String",
            Value::Bool(_) => "Bool",
            Value::Nil => "Nil",
            Value::Array(_) => "Array",
            Value::Map(_) => "Map",
            Value::Handle(_, _) => "Handle",
            Value::Instance(inst) => &inst.class_name,
            Value::Function(_) => "Function",
        }
    }

    pub fn new_instance(class_name: String, fields: BTreeMap<SymbolId, Value>) -> Self {
        let id = INSTANCE_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
        Value::Instance(Arc::new(InstanceData {
            class_name,
            id,
            fields: RwLock::new(fields),
        }))
    }

    pub fn as_instance(&self) -> Option<&Arc<InstanceData>> {
        match self {
            Value::Instance(inst) => Some(inst),
            _ => None,
        }
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Value::Integer(a), Value::Integer(b)) => a == b,
            (Value::Float(a), Value::Float(b)) => a == b,
            (Value::Symbol(a), Value::Symbol(b)) => a == b,
            (Value::String(a), Value::String(b)) => a == b,
            (Value::Bool(a), Value::Bool(b)) => a == b,
            (Value::Nil, Value::Nil) => true,
            (Value::Array(a), Value::Array(b)) => a.as_slice() == b.as_slice(),
            (Value::Map(a), Value::Map(b)) => a == b,
            // Handles compare by identity
            (Value::Handle(ta, a), Value::Handle(tb, b)) => ta == tb && a == b,
            // Instances compare by identity (reference equality)
            (Value::Instance(a), Value::Instance(b)) => Arc::ptr_eq(a, b),
            // Functions compare by identity (reference equality)
            (Value::Function(a), Value::Function(b)) => Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl Eq for Value {}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Integer(n) => write!(f, "{}", n),
            Value::Float(v) => {
                // Always show decimal point to distinguish from integers
                if v.fract() == 0.0 && v.is_finite() {
                    write!(f, "{:.1}", v)
                } else {
                    write!(f, "{}", v)
                }
            }
            Value::Symbol(_) => write!(f, ":<symbol>"),
            Value::String(s) => write!(f, "{}", s),
            Value::Bool(b) => write!(f, "{}", b),
            Value::Nil => write!(f, "nil"),
            Value::Array(arr) => {
                write!(f, "[")?;
                for (i, v) in arr.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", v)?;
                }
                write!(f, "]")
            }
            Value::Map(map) => {
                write!(f, "{{")?;
                for (i, (_, v)) in map.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "<key>: {}", v)?;
                }
                write!(f, "}}")
            }
            Value::Handle(t, id) => write!(f, "<Handle({}, {})>", t.0, id),
            Value::Instance(inst) => write!(f, "<{}#{}>", inst.class_name, inst.id),
            Value::Function(func) => match &func.name {
                Some(name) => write!(f, "<Function {}>", name),
                None => write!(f, "<Function (anonymous)>"),
            },
        }
    }
}