runes-core 0.1.0

Core types and traits for the Runes language
Documentation
use crate::ast::Program;
use crate::error::{RuneError, Severity};
use crate::span::Span;
use crate::symbol::{SymbolId, SymbolTable};
use crate::value::Value;
use std::any::Any;
use std::collections::BTreeMap;

/// Result type for verb invocations.
pub type VerbResult = Result<Value, RuneError>;

// ---------------------------------------------------------------------------
// Verb
// ---------------------------------------------------------------------------

/// A host-provided function callable from Runes code.
pub trait Verb: Send + Sync {
    /// The verb's name as it appears in Runes code.
    fn name(&self) -> &str;

    /// Execute the verb with the given arguments.
    fn call(&self, args: &[Value], ctx: &mut EvalContext) -> VerbResult;

    /// Optional argument documentation for diagnostics.
    fn signature(&self) -> Option<VerbSignature> { None }
}

/// Documentation for a verb's arguments.
#[derive(Debug, Clone)]
pub struct VerbSignature {
    pub positional: Vec<ArgInfo>,
    pub named: Vec<ArgInfo>,
    pub returns: Option<String>,
}

/// Information about a single argument.
#[derive(Debug, Clone)]
pub struct ArgInfo {
    pub name: String,
    pub expected_type: Option<String>,
    pub required: bool,
}

// ---------------------------------------------------------------------------
// Module
// ---------------------------------------------------------------------------

/// A named collection of verbs and constructs.
pub trait Module: Send + Sync {
    /// The module's name (matches the symbol in `use :name`).
    fn name(&self) -> &str;

    /// The module's version.
    fn version(&self) -> ModuleVersion;

    /// All verbs provided by this module.
    fn verbs(&self) -> &[Box<dyn Verb>];

    /// All constructs provided by this module (default: none).
    /// Constructs are block-accepting calls: `module.name(args) do...end`.
    fn constructs(&self) -> &[Box<dyn Construct>] { &[] }
}

/// Semantic version for a module.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModuleVersion {
    pub major: u16,
    pub minor: u16,
    pub patch: u16,
}

impl ModuleVersion {
    pub fn new(major: u16, minor: u16, patch: u16) -> Self {
        Self { major, minor, patch }
    }
}

impl std::fmt::Display for ModuleVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

// ---------------------------------------------------------------------------
// Construct
// ---------------------------------------------------------------------------

/// A host-provided custom block type.
///
/// Constructs use a two-phase protocol: `enter` runs before the body is
/// evaluated, `exit` runs after. The evaluator drives the sequence:
///
///   construct.enter(args, ctx)
///   evaluator evaluates body statements
///   construct.exit(ctx)
///
/// This allows constructs to set up scope (e.g., push a container onto a
/// builder stack) before children execute, then tear down after.
pub trait Construct: Send + Sync {
    /// The construct's name as it appears in Runes code.
    fn name(&self) -> &str;

    /// Called before the body block is evaluated.
    /// Use this to set up scope, push containers, etc.
    fn enter(
        &self,
        args: &[Value],
        ctx: &mut EvalContext,
    ) -> VerbResult;

    /// Called after the body block has been evaluated.
    /// Use this to tear down scope, pop containers, finalize the element.
    /// `enter_value` is whatever `enter()` returned.
    /// `body_value` is the result of evaluating the body statements.
    fn exit(
        &self,
        enter_value: Value,
        body_value: Value,
        ctx: &mut EvalContext,
    ) -> VerbResult;
}

// ---------------------------------------------------------------------------
// Logger
// ---------------------------------------------------------------------------

/// Syslog-style severity levels for structured logging.
/// Each level maps to a Runes symbol (e.g., `:emergency`, `:info`).
/// 1 byte representation via `#[repr(u8)]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum LogLevel {
    Emergency = 0,
    Alert     = 1,
    Critical  = 2,
    Error     = 3,
    Warning   = 4,
    Notice    = 5,
    Info      = 6,
    Debug     = 7,
}

impl LogLevel {
    /// Resolve a LogLevel from a Runes symbol name.
    pub fn from_symbol_name(name: &str) -> Option<Self> {
        match name {
            "emergency" => Some(Self::Emergency),
            "alert"     => Some(Self::Alert),
            "critical"  => Some(Self::Critical),
            "error"     => Some(Self::Error),
            "warning"   => Some(Self::Warning),
            "notice"    => Some(Self::Notice),
            "info"      => Some(Self::Info),
            "debug"     => Some(Self::Debug),
            _ => None,
        }
    }

    /// The symbol name for this log level.
    pub fn as_symbol_name(&self) -> &'static str {
        match self {
            Self::Emergency => "emergency",
            Self::Alert     => "alert",
            Self::Critical  => "critical",
            Self::Error     => "error",
            Self::Warning   => "warning",
            Self::Notice    => "notice",
            Self::Info      => "info",
            Self::Debug     => "debug",
        }
    }
}

/// Structured context attached to every log entry.
/// Traces the log back to its origin: which module, in which namespace, at what source location.
pub struct LogContext<'a> {
    pub module: &'a str,
    pub namespace: &'a str,
    pub span: Span,
}

/// Host-provided logging backend, scoped per-namespace.
pub trait Logger: Send + Sync {
    fn log(&self, level: LogLevel, message: &str, context: &LogContext);
}

// ---------------------------------------------------------------------------
// Constraint
// ---------------------------------------------------------------------------

/// When a constraint runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstraintPhase {
    /// Runs after parsing, before evaluation.
    Load,
    /// Runs during evaluation, triggered by events.
    Eval,
    /// Runs at both phases.
    Both,
}

/// A host-defined validation rule.
pub trait Constraint: Send + Sync {
    /// Unique error code (e.g., "ASTRO_001", "TSIG_001").
    fn code(&self) -> &str;

    /// When this constraint runs.
    fn phase(&self) -> ConstraintPhase;

    /// Validate at load time against parsed AST and metadata.
    fn validate_load(
        &self,
        _metadata: &ProgramMetadata,
        _program: &Program,
        _ctx: &ConstraintContext,
    ) -> Result<(), ConstraintViolation> {
        Ok(())
    }

    /// Validate during evaluation at host-defined trigger points.
    fn validate_eval(
        &self,
        _event: &ConstraintEvent,
        _ctx: &ConstraintContext,
    ) -> Result<(), ConstraintViolation> {
        Ok(())
    }
}

/// Parsed metadata from a `rune` block, available to constraints.
#[derive(Debug, Clone)]
pub struct ProgramMetadata {
    pub name: String,
    pub version: Option<i64>,
    pub namespace: Option<String>,
    pub requires: Vec<RequireEntry>,
    pub custom: BTreeMap<String, Value>,
}

/// A `requires :module, ">=1.0"` entry.
#[derive(Debug, Clone)]
pub struct RequireEntry {
    pub module: String,
    pub version_constraint: Option<String>,
}

/// Context available to constraints during validation.
pub struct ConstraintContext<'a> {
    /// The error catalog for rendering messages.
    pub catalog: &'a dyn ErrorCatalog,
}

/// An event that triggers eval-phase constraints.
#[derive(Debug, Clone)]
pub struct ConstraintEvent {
    pub kind: String,
    pub span: Span,
    pub data: BTreeMap<String, Value>,
}

/// A constraint violation result.
#[derive(Debug, Clone)]
pub struct ConstraintViolation {
    pub code: String,
    pub severity: Severity,
    pub message: String,
    pub span: Option<Span>,
    pub suggestion: Option<String>,
}

// ---------------------------------------------------------------------------
// Error Catalog
// ---------------------------------------------------------------------------

/// Registry of error codes with message templates.
pub trait ErrorCatalog: Send + Sync {
    /// All registered error entries.
    fn entries(&self) -> &[ErrorEntry];

    /// Look up an entry by code.
    fn get(&self, code: &str) -> Option<&ErrorEntry>;

    /// Render an error message from a template with substitutions.
    fn render(&self, code: &str, params: &[(&str, &str)]) -> String;
}

/// A single error catalog entry.
#[derive(Debug, Clone)]
pub struct ErrorEntry {
    pub code: String,
    pub prefix: String,
    pub title: String,
    pub template: String,
    pub severity: Severity,
    pub reference: Option<String>,
}

// ---------------------------------------------------------------------------
// Foundation Class
// ---------------------------------------------------------------------------

/// A Rust-backed class type that appears as a class in Runes.
pub trait FoundationClass: Send + Sync {
    /// The class name (PascalCase).
    fn name(&self) -> &str;

    /// Field definitions.
    fn fields(&self) -> &[FoundationField];

    /// Create a new instance from field values.
    fn instantiate(&self, fields: &BTreeMap<SymbolId, Value>) -> Result<Value, RuneError>;

    /// Methods available on instances.
    fn methods(&self) -> &[Box<dyn Verb>];
}

/// A field definition for a foundation class.
#[derive(Debug, Clone)]
pub struct FoundationField {
    pub name: String,
    pub type_hint: String,
    pub required: bool,
    pub default: Option<Value>,
}

// ---------------------------------------------------------------------------
// EvalContext (placeholder — full implementation in runes-eval)
// ---------------------------------------------------------------------------

/// Evaluation context passed to verbs and constructs.
/// This is a minimal definition — runes-eval provides the full implementation.
pub struct EvalContext<'a> {
    pub host: &'a mut dyn Any,
    pub span: Span,
    pub symbols: &'a SymbolTable,
    named_args: Option<BTreeMap<SymbolId, Value>>,
}

impl<'a> EvalContext<'a> {
    pub fn new(host: &'a mut dyn Any, span: Span, symbols: &'a SymbolTable) -> Self {
        Self { host, span, symbols, named_args: None }
    }

    /// Downcast host state to the expected type.
    pub fn host_ref<T: 'static>(&self) -> Result<&T, RuneError> {
        self.host.downcast_ref::<T>().ok_or_else(|| {
            RuneError::type_error("Host state type mismatch", Some(self.span))
        })
    }

    /// Downcast host state mutably.
    pub fn host_mut<T: 'static>(&mut self) -> Result<&mut T, RuneError> {
        let span = self.span;
        self.host.downcast_mut::<T>().ok_or_else(|| {
            RuneError::type_error("Host state type mismatch", Some(span))
        })
    }

    pub fn set_named_args(&mut self, args: BTreeMap<SymbolId, Value>) {
        self.named_args = Some(args);
    }

    pub fn named_args(&self) -> Option<&BTreeMap<SymbolId, Value>> {
        self.named_args.as_ref()
    }
}