runes-core 0.1.0

Core types and traits for the Runes language
Documentation
use std::collections::{HashMap, HashSet};

use crate::error::RuneErrorCatalog;
use crate::symbol::SymbolTable;
use crate::traits::{
    Constraint, Construct, ErrorCatalog, FoundationClass, Logger, Module, Verb,
};

/// A registered namespace with its modules, constructs, and constraints.
pub struct Namespace {
    pub name: String,
    pub modules: Vec<Box<dyn Module>>,
    pub constructs: Vec<Box<dyn Construct>>,
    pub foundation_classes: Vec<Box<dyn FoundationClass>>,
    pub constraints: Vec<Box<dyn Constraint>>,
    pub logger: Option<Box<dyn Logger>>,
}

impl Namespace {
    /// Find a module by name.
    pub fn find_module(&self, name: &str) -> Option<&dyn Module> {
        self.modules.iter().find(|m| m.name() == name).map(|m| m.as_ref())
    }

    /// Find a construct by name.
    pub fn find_construct(&self, name: &str) -> Option<&dyn Construct> {
        self.constructs.iter().find(|c| c.name() == name).map(|c| c.as_ref())
    }

    /// Find a verb by name across all modules. Returns the verb and its module name.
    pub fn find_verb(&self, name: &str) -> Option<(&dyn Verb, &str)> {
        for module in &self.modules {
            for verb in module.verbs() {
                if verb.name() == name {
                    return Some((verb.as_ref(), module.name()));
                }
            }
        }
        None
    }
}

/// The Runes engine — entry point for evaluating programs.
pub struct Engine {
    pub(crate) namespaces: HashMap<String, Namespace>,
    pub(crate) symbol_table: SymbolTable,
    pub(crate) error_catalog: Box<dyn ErrorCatalog>,
}

impl Engine {
    /// Create a new EngineBuilder.
    pub fn builder() -> EngineBuilder {
        EngineBuilder {
            namespaces: HashMap::new(),
            error_catalog: None,
        }
    }

    /// Look up a namespace by name.
    pub fn namespace(&self, name: &str) -> Option<&Namespace> {
        self.namespaces.get(name)
    }

    /// Access the shared symbol table.
    pub fn symbol_table(&self) -> &SymbolTable {
        &self.symbol_table
    }

    /// Access the shared symbol table mutably.
    pub fn symbol_table_mut(&mut self) -> &mut SymbolTable {
        &mut self.symbol_table
    }

    /// Access the error catalog (always present — defaults to RuneErrorCatalog).
    pub fn error_catalog(&self) -> &dyn ErrorCatalog {
        self.error_catalog.as_ref()
    }

    /// Find a foundation class by name across all namespaces.
    pub fn find_foundation_class(&self, name: &str) -> Option<&dyn FoundationClass> {
        for ns in self.namespaces.values() {
            for fc in &ns.foundation_classes {
                if fc.name() == name {
                    return Some(fc.as_ref());
                }
            }
        }
        None
    }
}

/// Error returned when building an Engine fails.
#[derive(Debug)]
pub struct BuildError {
    pub message: String,
}

impl std::fmt::Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Engine build error: {}", self.message)
    }
}

impl std::error::Error for BuildError {}

/// Fluent builder for constructing an Engine with registered extensions.
pub struct EngineBuilder {
    namespaces: HashMap<String, NamespaceBuilder>,
    error_catalog: Option<Box<dyn ErrorCatalog>>,
}

impl EngineBuilder {
    /// Begin defining a namespace.
    pub fn namespace(self, name: &str) -> NamespaceScope {
        NamespaceScope {
            builder: self,
            namespace: name.to_string(),
        }
    }

    /// Set the error catalog. If not called, the built-in RuneErrorCatalog is used.
    pub fn error_catalog(mut self, catalog: impl ErrorCatalog + 'static) -> Self {
        self.error_catalog = Some(Box::new(catalog));
        self
    }

    /// Build the engine. Validates that all registrations are consistent.
    pub fn build(self) -> Result<Engine, BuildError> {
        let mut namespaces = HashMap::new();
        for (name, ns_builder) in self.namespaces {
            // Check for duplicate module names
            let mut module_names = HashSet::new();
            for module in &ns_builder.modules {
                if !module_names.insert(module.name().to_string()) {
                    return Err(BuildError {
                        message: format!(
                            "Duplicate module '{}' in namespace '{}'",
                            module.name(), name,
                        ),
                    });
                }
            }

            // Check for duplicate construct names
            let mut construct_names = HashSet::new();
            for construct in &ns_builder.constructs {
                if !construct_names.insert(construct.name().to_string()) {
                    return Err(BuildError {
                        message: format!(
                            "Duplicate construct '{}' in namespace '{}'",
                            construct.name(), name,
                        ),
                    });
                }
            }

            // Check for duplicate foundation class names
            let mut class_names = HashSet::new();
            for class in &ns_builder.foundation_classes {
                if !class_names.insert(class.name().to_string()) {
                    return Err(BuildError {
                        message: format!(
                            "Duplicate foundation class '{}' in namespace '{}'",
                            class.name(), name,
                        ),
                    });
                }
            }

            namespaces.insert(name.clone(), Namespace {
                name,
                modules: ns_builder.modules,
                constructs: ns_builder.constructs,
                foundation_classes: ns_builder.foundation_classes,
                constraints: ns_builder.constraints,
                logger: ns_builder.logger,
            });
        }

        let error_catalog = self.error_catalog
            .unwrap_or_else(|| Box::new(RuneErrorCatalog::new()));

        Ok(Engine {
            namespaces,
            symbol_table: SymbolTable::new(),
            error_catalog,
        })
    }
}

struct NamespaceBuilder {
    modules: Vec<Box<dyn Module>>,
    constructs: Vec<Box<dyn Construct>>,
    foundation_classes: Vec<Box<dyn FoundationClass>>,
    constraints: Vec<Box<dyn Constraint>>,
    logger: Option<Box<dyn Logger>>,
}

impl NamespaceBuilder {
    fn new() -> Self {
        Self {
            modules: Vec::new(),
            constructs: Vec::new(),
            foundation_classes: Vec::new(),
            constraints: Vec::new(),
            logger: None,
        }
    }
}

/// Builder scope for registering extensions under a specific namespace.
pub struct NamespaceScope {
    builder: EngineBuilder,
    namespace: String,
}

impl NamespaceScope {
    fn ns_builder(&mut self) -> &mut NamespaceBuilder {
        self.builder
            .namespaces
            .entry(self.namespace.clone())
            .or_insert_with(NamespaceBuilder::new)
    }

    /// Register a module under this namespace.
    pub fn module(mut self, module: impl Module + 'static) -> Self {
        self.ns_builder().modules.push(Box::new(module));
        self
    }

    /// Register a construct under this namespace.
    pub fn construct(mut self, construct: impl Construct + 'static) -> Self {
        self.ns_builder().constructs.push(Box::new(construct));
        self
    }

    /// Register a foundation class under this namespace.
    pub fn foundation_class(mut self, class: impl FoundationClass + 'static) -> Self {
        self.ns_builder().foundation_classes.push(Box::new(class));
        self
    }

    /// Register a constraint under this namespace.
    pub fn constraint(mut self, constraint: impl Constraint + 'static) -> Self {
        self.ns_builder().constraints.push(Box::new(constraint));
        self
    }

    /// Set the logger for this namespace.
    pub fn logger(mut self, logger: impl Logger + 'static) -> Self {
        self.ns_builder().logger = Some(Box::new(logger));
        self
    }

    /// Switch to defining a different namespace.
    pub fn namespace(self, name: &str) -> Self {
        NamespaceScope {
            builder: self.builder,
            namespace: name.to_string(),
        }
    }

    /// Build the engine.
    pub fn build(self) -> Result<Engine, BuildError> {
        self.builder.build()
    }
}