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;
pub type VerbResult = Result<Value, RuneError>;
pub trait Verb: Send + Sync {
fn name(&self) -> &str;
fn call(&self, args: &[Value], ctx: &mut EvalContext) -> VerbResult;
fn signature(&self) -> Option<VerbSignature> { None }
}
#[derive(Debug, Clone)]
pub struct VerbSignature {
pub positional: Vec<ArgInfo>,
pub named: Vec<ArgInfo>,
pub returns: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ArgInfo {
pub name: String,
pub expected_type: Option<String>,
pub required: bool,
}
pub trait Module: Send + Sync {
fn name(&self) -> &str;
fn version(&self) -> ModuleVersion;
fn verbs(&self) -> &[Box<dyn Verb>];
fn constructs(&self) -> &[Box<dyn Construct>] { &[] }
}
#[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)
}
}
pub trait Construct: Send + Sync {
fn name(&self) -> &str;
fn enter(
&self,
args: &[Value],
ctx: &mut EvalContext,
) -> VerbResult;
fn exit(
&self,
enter_value: Value,
body_value: Value,
ctx: &mut EvalContext,
) -> VerbResult;
}
#[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 {
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,
}
}
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",
}
}
}
pub struct LogContext<'a> {
pub module: &'a str,
pub namespace: &'a str,
pub span: Span,
}
pub trait Logger: Send + Sync {
fn log(&self, level: LogLevel, message: &str, context: &LogContext);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstraintPhase {
Load,
Eval,
Both,
}
pub trait Constraint: Send + Sync {
fn code(&self) -> &str;
fn phase(&self) -> ConstraintPhase;
fn validate_load(
&self,
_metadata: &ProgramMetadata,
_program: &Program,
_ctx: &ConstraintContext,
) -> Result<(), ConstraintViolation> {
Ok(())
}
fn validate_eval(
&self,
_event: &ConstraintEvent,
_ctx: &ConstraintContext,
) -> Result<(), ConstraintViolation> {
Ok(())
}
}
#[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>,
}
#[derive(Debug, Clone)]
pub struct RequireEntry {
pub module: String,
pub version_constraint: Option<String>,
}
pub struct ConstraintContext<'a> {
pub catalog: &'a dyn ErrorCatalog,
}
#[derive(Debug, Clone)]
pub struct ConstraintEvent {
pub kind: String,
pub span: Span,
pub data: BTreeMap<String, Value>,
}
#[derive(Debug, Clone)]
pub struct ConstraintViolation {
pub code: String,
pub severity: Severity,
pub message: String,
pub span: Option<Span>,
pub suggestion: Option<String>,
}
pub trait ErrorCatalog: Send + Sync {
fn entries(&self) -> &[ErrorEntry];
fn get(&self, code: &str) -> Option<&ErrorEntry>;
fn render(&self, code: &str, params: &[(&str, &str)]) -> String;
}
#[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>,
}
pub trait FoundationClass: Send + Sync {
fn name(&self) -> &str;
fn fields(&self) -> &[FoundationField];
fn instantiate(&self, fields: &BTreeMap<SymbolId, Value>) -> Result<Value, RuneError>;
fn methods(&self) -> &[Box<dyn Verb>];
}
#[derive(Debug, Clone)]
pub struct FoundationField {
pub name: String,
pub type_hint: String,
pub required: bool,
pub default: Option<Value>,
}
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 }
}
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))
})
}
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()
}
}