Skip to main content

runes_core/
traits.rs

1use crate::ast::Program;
2use crate::error::{RuneError, Severity};
3use crate::span::Span;
4use crate::symbol::{SymbolId, SymbolTable};
5use crate::value::Value;
6use std::any::Any;
7use std::collections::BTreeMap;
8
9/// Result type for verb invocations.
10pub type VerbResult = Result<Value, RuneError>;
11
12// ---------------------------------------------------------------------------
13// Verb
14// ---------------------------------------------------------------------------
15
16/// A host-provided function callable from Runes code.
17pub trait Verb: Send + Sync {
18    /// The verb's name as it appears in Runes code.
19    fn name(&self) -> &str;
20
21    /// Execute the verb with the given arguments.
22    fn call(&self, args: &[Value], ctx: &mut EvalContext) -> VerbResult;
23
24    /// Optional argument documentation for diagnostics.
25    fn signature(&self) -> Option<VerbSignature> { None }
26}
27
28/// Documentation for a verb's arguments.
29#[derive(Debug, Clone)]
30pub struct VerbSignature {
31    pub positional: Vec<ArgInfo>,
32    pub named: Vec<ArgInfo>,
33    pub returns: Option<String>,
34}
35
36/// Information about a single argument.
37#[derive(Debug, Clone)]
38pub struct ArgInfo {
39    pub name: String,
40    pub expected_type: Option<String>,
41    pub required: bool,
42}
43
44// ---------------------------------------------------------------------------
45// Module
46// ---------------------------------------------------------------------------
47
48/// A named collection of verbs and constructs.
49pub trait Module: Send + Sync {
50    /// The module's name (matches the symbol in `use :name`).
51    fn name(&self) -> &str;
52
53    /// The module's version.
54    fn version(&self) -> ModuleVersion;
55
56    /// All verbs provided by this module.
57    fn verbs(&self) -> &[Box<dyn Verb>];
58
59    /// All constructs provided by this module (default: none).
60    /// Constructs are block-accepting calls: `module.name(args) do...end`.
61    fn constructs(&self) -> &[Box<dyn Construct>] { &[] }
62}
63
64/// Semantic version for a module.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct ModuleVersion {
67    pub major: u16,
68    pub minor: u16,
69    pub patch: u16,
70}
71
72impl ModuleVersion {
73    pub fn new(major: u16, minor: u16, patch: u16) -> Self {
74        Self { major, minor, patch }
75    }
76}
77
78impl std::fmt::Display for ModuleVersion {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
81    }
82}
83
84// ---------------------------------------------------------------------------
85// Construct
86// ---------------------------------------------------------------------------
87
88/// A host-provided custom block type.
89///
90/// Constructs use a two-phase protocol: `enter` runs before the body is
91/// evaluated, `exit` runs after. The evaluator drives the sequence:
92///
93///   construct.enter(args, ctx)
94///   evaluator evaluates body statements
95///   construct.exit(ctx)
96///
97/// This allows constructs to set up scope (e.g., push a container onto a
98/// builder stack) before children execute, then tear down after.
99pub trait Construct: Send + Sync {
100    /// The construct's name as it appears in Runes code.
101    fn name(&self) -> &str;
102
103    /// Called before the body block is evaluated.
104    /// Use this to set up scope, push containers, etc.
105    fn enter(
106        &self,
107        args: &[Value],
108        ctx: &mut EvalContext,
109    ) -> VerbResult;
110
111    /// Called after the body block has been evaluated.
112    /// Use this to tear down scope, pop containers, finalize the element.
113    /// `enter_value` is whatever `enter()` returned.
114    /// `body_value` is the result of evaluating the body statements.
115    fn exit(
116        &self,
117        enter_value: Value,
118        body_value: Value,
119        ctx: &mut EvalContext,
120    ) -> VerbResult;
121}
122
123// ---------------------------------------------------------------------------
124// Logger
125// ---------------------------------------------------------------------------
126
127/// Syslog-style severity levels for structured logging.
128/// Each level maps to a Runes symbol (e.g., `:emergency`, `:info`).
129/// 1 byte representation via `#[repr(u8)]`.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
131#[repr(u8)]
132pub enum LogLevel {
133    Emergency = 0,
134    Alert     = 1,
135    Critical  = 2,
136    Error     = 3,
137    Warning   = 4,
138    Notice    = 5,
139    Info      = 6,
140    Debug     = 7,
141}
142
143impl LogLevel {
144    /// Resolve a LogLevel from a Runes symbol name.
145    pub fn from_symbol_name(name: &str) -> Option<Self> {
146        match name {
147            "emergency" => Some(Self::Emergency),
148            "alert"     => Some(Self::Alert),
149            "critical"  => Some(Self::Critical),
150            "error"     => Some(Self::Error),
151            "warning"   => Some(Self::Warning),
152            "notice"    => Some(Self::Notice),
153            "info"      => Some(Self::Info),
154            "debug"     => Some(Self::Debug),
155            _ => None,
156        }
157    }
158
159    /// The symbol name for this log level.
160    pub fn as_symbol_name(&self) -> &'static str {
161        match self {
162            Self::Emergency => "emergency",
163            Self::Alert     => "alert",
164            Self::Critical  => "critical",
165            Self::Error     => "error",
166            Self::Warning   => "warning",
167            Self::Notice    => "notice",
168            Self::Info      => "info",
169            Self::Debug     => "debug",
170        }
171    }
172}
173
174/// Structured context attached to every log entry.
175/// Traces the log back to its origin: which module, in which namespace, at what source location.
176pub struct LogContext<'a> {
177    pub module: &'a str,
178    pub namespace: &'a str,
179    pub span: Span,
180}
181
182/// Host-provided logging backend, scoped per-namespace.
183pub trait Logger: Send + Sync {
184    fn log(&self, level: LogLevel, message: &str, context: &LogContext);
185}
186
187// ---------------------------------------------------------------------------
188// Constraint
189// ---------------------------------------------------------------------------
190
191/// When a constraint runs.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum ConstraintPhase {
194    /// Runs after parsing, before evaluation.
195    Load,
196    /// Runs during evaluation, triggered by events.
197    Eval,
198    /// Runs at both phases.
199    Both,
200}
201
202/// A host-defined validation rule.
203pub trait Constraint: Send + Sync {
204    /// Unique error code (e.g., "ASTRO_001", "TSIG_001").
205    fn code(&self) -> &str;
206
207    /// When this constraint runs.
208    fn phase(&self) -> ConstraintPhase;
209
210    /// Validate at load time against parsed AST and metadata.
211    fn validate_load(
212        &self,
213        _metadata: &ProgramMetadata,
214        _program: &Program,
215        _ctx: &ConstraintContext,
216    ) -> Result<(), ConstraintViolation> {
217        Ok(())
218    }
219
220    /// Validate during evaluation at host-defined trigger points.
221    fn validate_eval(
222        &self,
223        _event: &ConstraintEvent,
224        _ctx: &ConstraintContext,
225    ) -> Result<(), ConstraintViolation> {
226        Ok(())
227    }
228}
229
230/// Parsed metadata from a `rune` block, available to constraints.
231#[derive(Debug, Clone)]
232pub struct ProgramMetadata {
233    pub name: String,
234    pub version: Option<i64>,
235    pub namespace: Option<String>,
236    pub requires: Vec<RequireEntry>,
237    pub custom: BTreeMap<String, Value>,
238}
239
240/// A `requires :module, ">=1.0"` entry.
241#[derive(Debug, Clone)]
242pub struct RequireEntry {
243    pub module: String,
244    pub version_constraint: Option<String>,
245}
246
247/// Context available to constraints during validation.
248pub struct ConstraintContext<'a> {
249    /// The error catalog for rendering messages.
250    pub catalog: &'a dyn ErrorCatalog,
251}
252
253/// An event that triggers eval-phase constraints.
254#[derive(Debug, Clone)]
255pub struct ConstraintEvent {
256    pub kind: String,
257    pub span: Span,
258    pub data: BTreeMap<String, Value>,
259}
260
261/// A constraint violation result.
262#[derive(Debug, Clone)]
263pub struct ConstraintViolation {
264    pub code: String,
265    pub severity: Severity,
266    pub message: String,
267    pub span: Option<Span>,
268    pub suggestion: Option<String>,
269}
270
271// ---------------------------------------------------------------------------
272// Error Catalog
273// ---------------------------------------------------------------------------
274
275/// Registry of error codes with message templates.
276pub trait ErrorCatalog: Send + Sync {
277    /// All registered error entries.
278    fn entries(&self) -> &[ErrorEntry];
279
280    /// Look up an entry by code.
281    fn get(&self, code: &str) -> Option<&ErrorEntry>;
282
283    /// Render an error message from a template with substitutions.
284    fn render(&self, code: &str, params: &[(&str, &str)]) -> String;
285}
286
287/// A single error catalog entry.
288#[derive(Debug, Clone)]
289pub struct ErrorEntry {
290    pub code: String,
291    pub prefix: String,
292    pub title: String,
293    pub template: String,
294    pub severity: Severity,
295    pub reference: Option<String>,
296}
297
298// ---------------------------------------------------------------------------
299// Foundation Class
300// ---------------------------------------------------------------------------
301
302/// A Rust-backed class type that appears as a class in Runes.
303pub trait FoundationClass: Send + Sync {
304    /// The class name (PascalCase).
305    fn name(&self) -> &str;
306
307    /// Field definitions.
308    fn fields(&self) -> &[FoundationField];
309
310    /// Create a new instance from field values.
311    fn instantiate(&self, fields: &BTreeMap<SymbolId, Value>) -> Result<Value, RuneError>;
312
313    /// Methods available on instances.
314    fn methods(&self) -> &[Box<dyn Verb>];
315}
316
317/// A field definition for a foundation class.
318#[derive(Debug, Clone)]
319pub struct FoundationField {
320    pub name: String,
321    pub type_hint: String,
322    pub required: bool,
323    pub default: Option<Value>,
324}
325
326// ---------------------------------------------------------------------------
327// EvalContext (placeholder — full implementation in runes-eval)
328// ---------------------------------------------------------------------------
329
330/// Evaluation context passed to verbs and constructs.
331/// This is a minimal definition — runes-eval provides the full implementation.
332pub struct EvalContext<'a> {
333    pub host: &'a mut dyn Any,
334    pub span: Span,
335    pub symbols: &'a SymbolTable,
336    named_args: Option<BTreeMap<SymbolId, Value>>,
337}
338
339impl<'a> EvalContext<'a> {
340    pub fn new(host: &'a mut dyn Any, span: Span, symbols: &'a SymbolTable) -> Self {
341        Self { host, span, symbols, named_args: None }
342    }
343
344    /// Downcast host state to the expected type.
345    pub fn host_ref<T: 'static>(&self) -> Result<&T, RuneError> {
346        self.host.downcast_ref::<T>().ok_or_else(|| {
347            RuneError::type_error("Host state type mismatch", Some(self.span))
348        })
349    }
350
351    /// Downcast host state mutably.
352    pub fn host_mut<T: 'static>(&mut self) -> Result<&mut T, RuneError> {
353        let span = self.span;
354        self.host.downcast_mut::<T>().ok_or_else(|| {
355            RuneError::type_error("Host state type mismatch", Some(span))
356        })
357    }
358
359    pub fn set_named_args(&mut self, args: BTreeMap<SymbolId, Value>) {
360        self.named_args = Some(args);
361    }
362
363    pub fn named_args(&self) -> Option<&BTreeMap<SymbolId, Value>> {
364        self.named_args.as_ref()
365    }
366}