feat(runtime): tree-walk interpreter for Marqdo IR
Blueprint sections 7.2 and 3: Marqdo executes with its own Rust interpreter. - Frames with isolated scopes, named/positional argument binding, explicit signature rules, compile-time constant defaults evaluated in an empty frame. - Statements: assignment, expression statements, link-form calls, branch (first true arm), loop (condition re-evaluated, return propagates), return. - Expressions: exact Int arithmetic, `/` always Float, mixed arithmetic Float, exact Int/Float comparisons via rationals, Text concatenation, short-circuit and/or, Bool-only conditions, indexes with negative positions, map/Formula/ Code member access, calls (same module, imports, FunctionRef values). - Builtins: print/len/type/str/int/float/table/ref plus capability-host dispatch for math.*, foreign.*, fs.*; `ref` resolves functions or exactly one inert resource and errors on ambiguity instead of picking the first. - Fuel, stack-depth and wall-clock budgets are enforced; call errors carry a structured stack of frames. - End-to-end tests: recursion, loops, explicit positional signatures, builtins, function references, non-Bool conditions, fuel/stack exhaustion, ambiguous references.
This commit is contained in:
1 parent
d54fda9e78
commit
2e49c7b855
6 files changed
+1709
No files matched your search
@@ -14,5 +14,14 @@ marqdo-value = { workspace = true }
|
||||
marqdo-ir = { workspace = true }
|
||||
marqdo-expression = { workspace = true }
|
||||
marqdo-host = { workspace = true }
|
||||
num-bigint = { workspace = true }
|
||||
num-rational = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
marqdo-frontend = { workspace = true }
|
||||
marqdo-sandbox = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Implementations of the v1 builtins.
|
||||
//!
|
||||
//! Pure builtins run in the interpreter; effectful builtins and kernels go
|
||||
//! through the capability host. `ref` resolves inert document resources and
|
||||
//! never evaluates them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_host::HostOp;
|
||||
use marqdo_ir::builtins::Builtin;
|
||||
use marqdo_ir::Resource;
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{
|
||||
float_to_bigint, CodeValue, ErrorCategory, FormulaValue, FunctionRef, RuntimeError, Table,
|
||||
Value,
|
||||
};
|
||||
|
||||
use crate::interpreter::Interpreter;
|
||||
|
||||
pub(crate) fn dispatch(
|
||||
interpreter: &mut Interpreter<'_>,
|
||||
builtin: &'static Builtin,
|
||||
bound: BTreeMap<String, Value>,
|
||||
span: Option<Span>,
|
||||
frame: &FrameView<'_>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let module = frame.module().clone();
|
||||
match builtin.name {
|
||||
"打印" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
interpreter
|
||||
.host_invoke(HostOp::Print, vec![value], span, &module)
|
||||
.map(|_| Value::Unit)
|
||||
}
|
||||
"长度" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
let length = match &value {
|
||||
Value::Text(text) => text.chars().count(),
|
||||
Value::List(items) => items.len(),
|
||||
Value::Map(map) => map.len(),
|
||||
Value::Table(table) => table.rows.len(),
|
||||
other => {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("长度 is not defined for {}", other.type_name()),
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(Value::int(length as i64))
|
||||
}
|
||||
"类型" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
Ok(Value::text(value.type_name()))
|
||||
}
|
||||
"文本" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
match value {
|
||||
Value::Text(text) => Ok(Value::Text(text)),
|
||||
Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::None | Value::Unit => {
|
||||
Ok(Value::Text(value.display()))
|
||||
}
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("cannot convert {} to Text explicitly", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
"整数" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
match value {
|
||||
Value::Int(int) => Ok(Value::Int(int)),
|
||||
Value::Float(float) => float_to_bigint(float).map(Value::Int).ok_or_else(|| {
|
||||
RuntimeError::type_error(span, "Float is not integral and cannot become Int")
|
||||
}),
|
||||
Value::Text(text) => text.trim().parse().map(Value::Int).map_err(|_| {
|
||||
RuntimeError::type_error(span, format!("`{text}` is not a decimal integer"))
|
||||
}),
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("cannot convert {} to Int", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
"小数" => {
|
||||
let value = take(&bound, "值", builtin, span)?;
|
||||
match value {
|
||||
Value::Float(float) => Ok(Value::Float(float)),
|
||||
Value::Int(int) => {
|
||||
use num_traits::ToPrimitive;
|
||||
int.to_f64().map(Value::Float).ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
"integer is too large to convert to a Float",
|
||||
)
|
||||
})
|
||||
}
|
||||
Value::Text(text) => text.trim().parse::<f64>().map(Value::Float).map_err(|_| {
|
||||
RuntimeError::type_error(span, format!("`{text}` is not a decimal number"))
|
||||
}),
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("cannot convert {} to Float", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
"表" => {
|
||||
let header = take(&bound, "表头", builtin, span)?;
|
||||
let rows = take(&bound, "行", builtin, span)?;
|
||||
table(header, rows, span)
|
||||
}
|
||||
"ref" => {
|
||||
let target = take(&bound, "目标", builtin, span)?;
|
||||
let Value::Text(target) = target else {
|
||||
return Err(RuntimeError::type_error(span, "ref target must be Text"));
|
||||
};
|
||||
resolve_ref(interpreter, &module, &target, span)
|
||||
}
|
||||
"math.parse" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let text = formula_text(formula, span)?;
|
||||
interpreter.host_invoke(HostOp::MathParse, vec![Value::Text(text)], span, &module)
|
||||
}
|
||||
"math.eval" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let bindings = take(&bound, "bindings", builtin, span)?;
|
||||
let mut args = vec![formula, bindings];
|
||||
if let Some(target) = bound.get("target") {
|
||||
args.push(target.clone());
|
||||
}
|
||||
interpreter.host_invoke(HostOp::MathEval, args, span, &module)
|
||||
}
|
||||
"math.substitute" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let bindings = take(&bound, "bindings", builtin, span)?;
|
||||
interpreter.host_invoke(
|
||||
HostOp::MathSubstitute,
|
||||
vec![formula, bindings],
|
||||
span,
|
||||
&module,
|
||||
)
|
||||
}
|
||||
"math.simplify" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
interpreter.host_invoke(HostOp::MathSimplify, vec![formula], span, &module)
|
||||
}
|
||||
"math.differentiate" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let variable = take(&bound, "变量", builtin, span)?;
|
||||
interpreter.host_invoke(
|
||||
HostOp::MathDifferentiate,
|
||||
vec![formula, variable],
|
||||
span,
|
||||
&module,
|
||||
)
|
||||
}
|
||||
"foreign.run" => {
|
||||
let code = take(&bound, "ref", builtin, span)?;
|
||||
let mut args = vec![code];
|
||||
if let Some(input) = bound.get("input") {
|
||||
args.push(input.clone());
|
||||
}
|
||||
interpreter.host_invoke(HostOp::ForeignRun, args, span, &module)
|
||||
}
|
||||
"foreign.call" => {
|
||||
let code = take(&bound, "ref", builtin, span)?;
|
||||
let input = take(&bound, "input", builtin, span)?;
|
||||
interpreter.host_invoke(HostOp::ForeignCall, vec![code, input], span, &module)
|
||||
}
|
||||
"fs.read" => {
|
||||
let path = take(&bound, "path", builtin, span)?;
|
||||
interpreter.host_invoke(HostOp::FsRead, vec![path], span, &module)
|
||||
}
|
||||
"fs.write" => {
|
||||
let path = take(&bound, "path", builtin, span)?;
|
||||
let contents = take(&bound, "contents", builtin, span)?;
|
||||
let Value::Text(text) = contents else {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
"fs.write contents must be Text",
|
||||
));
|
||||
};
|
||||
interpreter.host_invoke(
|
||||
HostOp::FsWrite,
|
||||
vec![path, Value::Text(text)],
|
||||
span,
|
||||
&module,
|
||||
)
|
||||
}
|
||||
other => Err(RuntimeError::new(
|
||||
ErrorCategory::KernelUnavailable,
|
||||
span,
|
||||
format!("builtin `{other}` is not implemented in this runtime"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn take(
|
||||
bound: &BTreeMap<String, Value>,
|
||||
name: &str,
|
||||
builtin: &Builtin,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
bound.get(name).cloned().ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
span,
|
||||
format!("`{}` is missing argument `{name}`", builtin.name),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn formula_text(value: Value, span: Option<Span>) -> Result<String, RuntimeError> {
|
||||
match value {
|
||||
Value::Formula(formula) => Ok(formula.latex),
|
||||
Value::Text(text) => Ok(text),
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!(
|
||||
"formula argument must be Formula or Text, got {}",
|
||||
other.type_name()
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn table(header: Value, rows: Value, span: Option<Span>) -> Result<Value, RuntimeError> {
|
||||
let Value::List(header_values) = header else {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
"table header must be a List",
|
||||
));
|
||||
};
|
||||
let mut header_names = Vec::with_capacity(header_values.len());
|
||||
for value in header_values {
|
||||
match value {
|
||||
Value::Text(name) => header_names.push(name),
|
||||
other => {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("table header cells must be Text, got {}", other.type_name()),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
let Value::List(row_values) = rows else {
|
||||
return Err(RuntimeError::type_error(span, "table rows must be a List"));
|
||||
};
|
||||
let mut table_rows = Vec::with_capacity(row_values.len());
|
||||
for row in row_values {
|
||||
let Value::List(cells) = row else {
|
||||
return Err(RuntimeError::type_error(span, "table row must be a List"));
|
||||
};
|
||||
if cells.len() != header_names.len() {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!(
|
||||
"table row has {} cells but header has {}",
|
||||
cells.len(),
|
||||
header_names.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
table_rows.push(cells);
|
||||
}
|
||||
Ok(Value::Table(Table {
|
||||
header: header_names,
|
||||
rows: table_rows,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Resolve `ref("#anchor")` to a function reference or an inert resource.
|
||||
fn resolve_ref(
|
||||
interpreter: &Interpreter<'_>,
|
||||
module_id: &marqdo_ir::ModuleId,
|
||||
target: &str,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let program = interpreter.program();
|
||||
let Some(module) = program.module(module_id) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
span,
|
||||
format!("unknown module `{module_id}`"),
|
||||
));
|
||||
};
|
||||
let Some(fragment) = target.strip_prefix('#') else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
span,
|
||||
format!("ref target `{target}` must be a `#heading` anchor"),
|
||||
));
|
||||
};
|
||||
let Some(unit_id) = module.anchors.get(fragment).cloned() else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
span,
|
||||
format!("no heading matches `{target}`"),
|
||||
));
|
||||
};
|
||||
let resources: Vec<&Resource> = module.resources_of(&unit_id).collect();
|
||||
match resources.len() {
|
||||
1 => Ok(match resources[0] {
|
||||
Resource::Formula {
|
||||
latex,
|
||||
display,
|
||||
span: resource_span,
|
||||
..
|
||||
} => Value::Formula(FormulaValue {
|
||||
latex: latex.clone(),
|
||||
unit: Some(unit_id.to_string()),
|
||||
display: *display,
|
||||
span: Some(*resource_span),
|
||||
}),
|
||||
Resource::Code {
|
||||
language,
|
||||
source,
|
||||
content_hash,
|
||||
span: resource_span,
|
||||
..
|
||||
} => Value::Code(CodeValue {
|
||||
language: language.clone(),
|
||||
source: source.clone(),
|
||||
unit: Some(unit_id.to_string()),
|
||||
content_hash: content_hash.clone(),
|
||||
span: Some(*resource_span),
|
||||
}),
|
||||
}),
|
||||
0 => {
|
||||
if let Some(function) = module.functions.iter().find(|f| f.unit == unit_id) {
|
||||
return Ok(Value::FunctionRef(FunctionRef {
|
||||
module: function.id.module.0.clone(),
|
||||
name: function.id.name.clone(),
|
||||
}));
|
||||
}
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
span,
|
||||
format!("`{target}` contains no formula, code block or function"),
|
||||
))
|
||||
}
|
||||
count => Err(RuntimeError::new(
|
||||
ErrorCategory::RefAmbiguous,
|
||||
span,
|
||||
format!(
|
||||
"`{target}` contains {count} resources; select one explicitly instead of relying on the first"
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Small view used by builtin dispatch to avoid borrowing the whole frame.
|
||||
pub(crate) struct FrameView<'f> {
|
||||
module: &'f marqdo_ir::ModuleId,
|
||||
}
|
||||
|
||||
impl<'f> FrameView<'f> {
|
||||
pub(crate) fn new(module: &'f marqdo_ir::ModuleId) -> Self {
|
||||
Self { module }
|
||||
}
|
||||
|
||||
pub(crate) fn module(&self) -> &'f marqdo_ir::ModuleId {
|
||||
self.module
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
//! The tree-walk interpreter.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
|
||||
use marqdo_host::{ExecutionContext, Host, HostOp};
|
||||
use marqdo_ir::{builtins, CallTarget, Function, FunctionId, ModuleId, Program, Stmt};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
|
||||
use crate::builtins_impl::FrameView;
|
||||
|
||||
use crate::value_ops;
|
||||
|
||||
/// One already-evaluated call argument.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct EvaluatedArg {
|
||||
/// Argument name for named arguments; `None` for positional.
|
||||
pub name: Option<String>,
|
||||
/// Evaluated value.
|
||||
pub value: Value,
|
||||
/// Source span of the argument.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl EvaluatedArg {
|
||||
/// Named argument constructor.
|
||||
pub fn named(name: impl Into<String>, value: Value, span: Span) -> Self {
|
||||
Self {
|
||||
name: Some(name.into()),
|
||||
value,
|
||||
span,
|
||||
}
|
||||
}
|
||||
|
||||
/// Positional argument constructor.
|
||||
pub fn positional(value: Value, span: Span) -> Self {
|
||||
Self {
|
||||
name: None,
|
||||
value,
|
||||
span,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Successful run result.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RunOutcome {
|
||||
/// Value returned by the entry function (`Unit` when it falls through).
|
||||
pub value: Value,
|
||||
}
|
||||
|
||||
/// Execution frame for one function call.
|
||||
struct Frame {
|
||||
function: FunctionId,
|
||||
namespace: Option<String>,
|
||||
locals: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// Flow of one statement list.
|
||||
enum Flow {
|
||||
Next,
|
||||
Return(Value),
|
||||
}
|
||||
|
||||
/// Marqdo tree-walk interpreter.
|
||||
pub struct Interpreter<'a> {
|
||||
program: &'a Program,
|
||||
host: &'a mut dyn Host,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// Run a named function with already-evaluated arguments.
|
||||
pub fn run(
|
||||
program: &Program,
|
||||
host: &mut dyn Host,
|
||||
module: &ModuleId,
|
||||
function: &str,
|
||||
args: Vec<EvaluatedArg>,
|
||||
) -> Result<RunOutcome, RuntimeError> {
|
||||
let mut interpreter = Interpreter {
|
||||
program,
|
||||
host,
|
||||
depth: 0,
|
||||
};
|
||||
let value = interpreter.call_by_name(module, function, args, None)?;
|
||||
Ok(RunOutcome { value })
|
||||
}
|
||||
|
||||
impl<'a> Interpreter<'a> {
|
||||
/// Call a function in a module by canonical or unique local name.
|
||||
pub fn call_by_name(
|
||||
&mut self,
|
||||
module: &ModuleId,
|
||||
name: &str,
|
||||
args: Vec<EvaluatedArg>,
|
||||
call_span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let program = self.program;
|
||||
let Some(target_module) = program.module(module) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
call_span,
|
||||
format!("unknown module `{module}`"),
|
||||
));
|
||||
};
|
||||
let Some(function) = target_module.function(name) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
call_span,
|
||||
format!("unknown function `{name}` in module `{module}`"),
|
||||
));
|
||||
};
|
||||
self.call_function(program, function, args, call_span)
|
||||
}
|
||||
|
||||
fn call_function(
|
||||
&mut self,
|
||||
program: &'a Program,
|
||||
function: &'a Function,
|
||||
args: Vec<EvaluatedArg>,
|
||||
call_span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let display = function.id.name.clone();
|
||||
if self.depth + 1 > 0 {
|
||||
self.host.check_stack(self.depth + 1, call_span)?;
|
||||
}
|
||||
let locals = self.bind_args(function, args, call_span)?;
|
||||
let mut frame = Frame {
|
||||
function: function.id.clone(),
|
||||
namespace: function.namespace.clone(),
|
||||
locals,
|
||||
};
|
||||
self.depth += 1;
|
||||
let result = self.exec_stmts(program, &function.body, &mut frame);
|
||||
self.depth -= 1;
|
||||
match result {
|
||||
Ok(Flow::Next) => Ok(Value::Unit),
|
||||
Ok(Flow::Return(value)) => Ok(value),
|
||||
Err(mut error) => {
|
||||
error.push_frame(display, call_span);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_args(
|
||||
&mut self,
|
||||
function: &Function,
|
||||
args: Vec<EvaluatedArg>,
|
||||
call_span: Option<Span>,
|
||||
) -> Result<BTreeMap<String, Value>, RuntimeError> {
|
||||
let mut provided: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut positional = 0usize;
|
||||
for arg in args {
|
||||
match &arg.name {
|
||||
Some(name) => {
|
||||
if !function.params.iter().any(|param| ¶m.name == name) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!("`{}` has no parameter named `{name}`", function.id.name),
|
||||
));
|
||||
}
|
||||
if provided.insert(name.clone(), arg.value).is_some() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!("duplicate argument `{name}`"),
|
||||
));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if function.signature != marqdo_ir::SignatureKind::Explicit {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!(
|
||||
"`{}` has an inferred signature and only accepts named arguments",
|
||||
function.id.name
|
||||
),
|
||||
));
|
||||
}
|
||||
let Some(param) = function.params.get(positional) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!(
|
||||
"`{}` accepts at most {} positional argument(s)",
|
||||
function.id.name,
|
||||
function.params.len()
|
||||
),
|
||||
));
|
||||
};
|
||||
provided.insert(param.name.clone(), arg.value);
|
||||
positional += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut locals = BTreeMap::new();
|
||||
for param in &function.params {
|
||||
match provided.remove(¶m.name) {
|
||||
Some(value) => {
|
||||
locals.insert(param.name.clone(), value);
|
||||
}
|
||||
None => {
|
||||
if let Some(default) = ¶m.default {
|
||||
// Defaults are compile-time constants; evaluate them in
|
||||
// an empty frame so they cannot reach caller state.
|
||||
let mut empty = Frame {
|
||||
function: function.id.clone(),
|
||||
namespace: function.namespace.clone(),
|
||||
locals: BTreeMap::new(),
|
||||
};
|
||||
let value = self.eval_expr(default, &mut empty)?;
|
||||
locals.insert(param.name.clone(), value);
|
||||
} else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
call_span,
|
||||
format!(
|
||||
"`{}` is missing required argument `{}`",
|
||||
function.id.name, param.name
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(locals)
|
||||
}
|
||||
|
||||
fn exec_stmts(
|
||||
&mut self,
|
||||
program: &'a Program,
|
||||
stmts: &'a [Stmt],
|
||||
frame: &mut Frame,
|
||||
) -> Result<Flow, RuntimeError> {
|
||||
for stmt in stmts {
|
||||
self.host.consume_fuel(1, Some(stmt.span()))?;
|
||||
self.host.check_deadline(Some(stmt.span()))?;
|
||||
match stmt {
|
||||
Stmt::Assign { name, value, .. } => {
|
||||
let value = self.eval_expr(value, frame)?;
|
||||
frame.locals.insert(name.clone(), value);
|
||||
}
|
||||
Stmt::Eval { expr, .. } => {
|
||||
self.eval_expr(expr, frame)?;
|
||||
}
|
||||
Stmt::Call { call, span } => {
|
||||
self.exec_call_site(program, call, *span, frame)?;
|
||||
}
|
||||
Stmt::Return { value, .. } => {
|
||||
let value = self.eval_expr(value, frame)?;
|
||||
return Ok(Flow::Return(value));
|
||||
}
|
||||
Stmt::Branch { arms, .. } => {
|
||||
for arm in arms {
|
||||
self.host.consume_fuel(1, Some(arm.condition_span))?;
|
||||
let condition = self.eval_expr(&arm.condition, frame)?;
|
||||
let Value::Bool(condition) = condition else {
|
||||
return Err(RuntimeError::type_error(
|
||||
Some(arm.condition_span),
|
||||
format!(
|
||||
"branch condition must be Bool, got {}",
|
||||
condition.type_name()
|
||||
),
|
||||
));
|
||||
};
|
||||
if condition {
|
||||
match self.exec_stmts(program, &arm.body, frame)? {
|
||||
Flow::Next => break,
|
||||
Flow::Return(value) => return Ok(Flow::Return(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Stmt::Loop {
|
||||
condition,
|
||||
condition_span,
|
||||
body,
|
||||
span,
|
||||
} => loop {
|
||||
self.host.consume_fuel(1, Some(*span))?;
|
||||
self.host.check_deadline(Some(*condition_span))?;
|
||||
let value = self.eval_expr(condition, frame)?;
|
||||
let Value::Bool(value) = value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
Some(*condition_span),
|
||||
format!("loop condition must be Bool, got {}", value.type_name()),
|
||||
));
|
||||
};
|
||||
if !value {
|
||||
break;
|
||||
}
|
||||
match self.exec_stmts(program, body, frame)? {
|
||||
Flow::Next => {}
|
||||
Flow::Return(value) => return Ok(Flow::Return(value)),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(Flow::Next)
|
||||
}
|
||||
|
||||
fn exec_call_site(
|
||||
&mut self,
|
||||
program: &'a Program,
|
||||
call: &'a marqdo_ir::CallSite,
|
||||
span: Span,
|
||||
frame: &mut Frame,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let args = self.eval_args(&call.args, frame)?;
|
||||
let (module, name) = match &call.target {
|
||||
CallTarget::Function { name } => (frame.function.module.clone(), name.clone()),
|
||||
CallTarget::Qualified {
|
||||
module_alias,
|
||||
function,
|
||||
} => {
|
||||
let Some(target) = program.resolve_import(&frame.function.module, module_alias)
|
||||
else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
Some(span),
|
||||
format!("unknown imported module alias `{module_alias}`"),
|
||||
));
|
||||
};
|
||||
(target.clone(), function.clone())
|
||||
}
|
||||
CallTarget::Resolved { module, function } => (module.clone(), function.clone()),
|
||||
};
|
||||
self.call_by_name(&module, &name, args, Some(span))
|
||||
}
|
||||
|
||||
fn eval_args(
|
||||
&mut self,
|
||||
args: &[marqdo_expression::Arg],
|
||||
frame: &mut Frame,
|
||||
) -> Result<Vec<EvaluatedArg>, RuntimeError> {
|
||||
let mut evaluated = Vec::with_capacity(args.len());
|
||||
for arg in args {
|
||||
let value = self.eval_expr(&arg.value, frame)?;
|
||||
evaluated.push(EvaluatedArg {
|
||||
name: arg.name.clone(),
|
||||
value,
|
||||
span: arg.span,
|
||||
});
|
||||
}
|
||||
Ok(evaluated)
|
||||
}
|
||||
|
||||
fn eval_expr(&mut self, expr: &Expr, frame: &mut Frame) -> Result<Value, RuntimeError> {
|
||||
self.host.consume_fuel(1, Some(expr.span()))?;
|
||||
match expr {
|
||||
Expr::Int(value) => Ok(Value::Int(value.clone())),
|
||||
Expr::Float(value) => Ok(Value::Float(*value)),
|
||||
Expr::Text(value) => Ok(Value::Text(value.clone())),
|
||||
Expr::Bool(value) => Ok(Value::Bool(*value)),
|
||||
Expr::None => Ok(Value::None),
|
||||
Expr::Ident(ident) => frame.locals.get(&ident.name).cloned().ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
Some(ident.span),
|
||||
format!("unknown variable `{}`", ident.name),
|
||||
)
|
||||
}),
|
||||
Expr::List(items) => {
|
||||
let mut values = Vec::with_capacity(items.len());
|
||||
for item in items {
|
||||
values.push(self.eval_expr(item, frame)?);
|
||||
}
|
||||
Ok(Value::List(values))
|
||||
}
|
||||
Expr::Record(entries) => {
|
||||
let mut map = BTreeMap::new();
|
||||
for RecordEntry {
|
||||
key,
|
||||
key_span,
|
||||
value,
|
||||
} in entries
|
||||
{
|
||||
let value = self.eval_expr(value, frame)?;
|
||||
if map.insert(key.clone(), value).is_some() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
Some(*key_span),
|
||||
format!("duplicate record key `{key}`"),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
Expr::Unary { op, operand, span } => {
|
||||
let value = self.eval_expr(operand, frame)?;
|
||||
value_ops::unary(*op, value, Some(*span))
|
||||
}
|
||||
Expr::Binary {
|
||||
op,
|
||||
left,
|
||||
right,
|
||||
span,
|
||||
} => {
|
||||
if matches!(op, BinaryOp::And | BinaryOp::Or) {
|
||||
let left_value = self.eval_expr(left, frame)?;
|
||||
let Value::Bool(left_bool) = left_value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
Some(*span),
|
||||
format!(
|
||||
"`{}` expects Bool, got {}",
|
||||
if *op == BinaryOp::And { "and" } else { "or" },
|
||||
left_value.type_name()
|
||||
),
|
||||
));
|
||||
};
|
||||
if (*op == BinaryOp::And && !left_bool) || (*op == BinaryOp::Or && left_bool) {
|
||||
return Ok(Value::Bool(left_bool));
|
||||
}
|
||||
let right_value = self.eval_expr(right, frame)?;
|
||||
let Value::Bool(right_bool) = right_value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
Some(*span),
|
||||
format!(
|
||||
"`{}` expects Bool, got {}",
|
||||
if *op == BinaryOp::And { "and" } else { "or" },
|
||||
right_value.type_name()
|
||||
),
|
||||
));
|
||||
};
|
||||
return Ok(Value::Bool(right_bool));
|
||||
}
|
||||
let left_value = self.eval_expr(left, frame)?;
|
||||
let right_value = self.eval_expr(right, frame)?;
|
||||
value_ops::binary(*op, left_value, right_value, Some(*span))
|
||||
}
|
||||
Expr::Call { callee, args, span } => {
|
||||
let program = self.program;
|
||||
self.eval_call(program, callee, args, *span, frame)
|
||||
}
|
||||
Expr::Member { base, name, span } => {
|
||||
let value = self.eval_expr(base, frame)?;
|
||||
member_of(value, name, Some(*span))
|
||||
}
|
||||
Expr::Index { base, index, span } => {
|
||||
let base_value = self.eval_expr(base, frame)?;
|
||||
let index_value = self.eval_expr(index, frame)?;
|
||||
index_value_of(base_value, index_value, Some(*span))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_call(
|
||||
&mut self,
|
||||
program: &'a Program,
|
||||
callee: &Expr,
|
||||
args: &[marqdo_expression::Arg],
|
||||
span: Span,
|
||||
frame: &mut Frame,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
match callee {
|
||||
Expr::Ident(ident) => {
|
||||
if let Some(value) = frame.locals.get(&ident.name).cloned() {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
return self.call_value(program, value, args, Some(span));
|
||||
}
|
||||
if let Some(builtin) = builtins::find(&ident.name) {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
return self.call_builtin(builtin, args, Some(span), frame);
|
||||
}
|
||||
let args = self.eval_args(args, frame)?;
|
||||
let (module, namespace) = (frame.function.module.clone(), frame.namespace.clone());
|
||||
let Some(function) =
|
||||
resolve_function(program, &module, namespace.as_deref(), &ident.name)
|
||||
else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
Some(span),
|
||||
format!("unknown function `{}`", ident.name),
|
||||
));
|
||||
};
|
||||
self.call_function(program, function, args, Some(span))
|
||||
}
|
||||
Expr::Member { base, name, .. } => {
|
||||
if let Expr::Ident(alias) = base.as_ref() {
|
||||
if let Some(target_module) =
|
||||
program.resolve_import(&frame.function.module, &alias.name)
|
||||
{
|
||||
let args = self.eval_args(args, frame)?;
|
||||
let Some(function) = resolve_function(program, target_module, None, name)
|
||||
else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
Some(span),
|
||||
format!("unknown function `{name}` in module `{target_module}`"),
|
||||
));
|
||||
};
|
||||
return self.call_function(program, function, args, Some(span));
|
||||
}
|
||||
let qualified = format!("{}.{name}", alias.name);
|
||||
if let Some(builtin) = builtins::find(&qualified) {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
return self.call_builtin(builtin, args, Some(span), frame);
|
||||
}
|
||||
}
|
||||
let callee_value = self.eval_expr(callee, frame)?;
|
||||
let args = self.eval_args(args, frame)?;
|
||||
self.call_value(program, callee_value, args, Some(span))
|
||||
}
|
||||
other => {
|
||||
let callee_value = self.eval_expr(other, frame)?;
|
||||
let args = self.eval_args(args, frame)?;
|
||||
self.call_value(program, callee_value, args, Some(span))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn call_value(
|
||||
&mut self,
|
||||
program: &'a Program,
|
||||
callee: Value,
|
||||
args: Vec<EvaluatedArg>,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
match callee {
|
||||
Value::FunctionRef(reference) => {
|
||||
let id = FunctionId {
|
||||
module: ModuleId(reference.module),
|
||||
name: reference.name,
|
||||
};
|
||||
let Some(function) = program.function(&id) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
span,
|
||||
format!("function reference `{id}` does not exist"),
|
||||
));
|
||||
};
|
||||
self.call_function(program, function, args, span)
|
||||
}
|
||||
other => Err(RuntimeError::new(
|
||||
ErrorCategory::NotCallable,
|
||||
span,
|
||||
format!("{} is not callable", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_builtin(
|
||||
&mut self,
|
||||
builtin: &'static builtins::Builtin,
|
||||
args: Vec<EvaluatedArg>,
|
||||
span: Option<Span>,
|
||||
frame: &Frame,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let bound = bind_builtin_args(builtin, args, span)?;
|
||||
let view = FrameView::new(&frame.function.module);
|
||||
crate::builtins_impl::dispatch(self, builtin, bound, span, &view)
|
||||
}
|
||||
|
||||
/// Access to the program (used by builtin implementations).
|
||||
pub(crate) fn program(&self) -> &'a Program {
|
||||
self.program
|
||||
}
|
||||
|
||||
/// Call a builtin-read host operation on behalf of a frame's module.
|
||||
pub(crate) fn host_invoke(
|
||||
&mut self,
|
||||
op: HostOp,
|
||||
args: Vec<Value>,
|
||||
span: Option<Span>,
|
||||
module: &ModuleId,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let context = ExecutionContext::new(module.0.clone(), span);
|
||||
self.host.invoke(op, args, &context)
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_function<'p>(
|
||||
program: &'p Program,
|
||||
module: &ModuleId,
|
||||
namespace: Option<&str>,
|
||||
name: &str,
|
||||
) -> Option<&'p Function> {
|
||||
let module = program.module(module)?;
|
||||
if let Some(namespace) = namespace {
|
||||
if let Some(found) = module.namespaced_function(namespace, name) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
module.function(name)
|
||||
}
|
||||
|
||||
/// Bind already-evaluated arguments to a builtin parameter list.
|
||||
fn bind_builtin_args(
|
||||
builtin: &'static builtins::Builtin,
|
||||
args: Vec<EvaluatedArg>,
|
||||
span: Option<Span>,
|
||||
) -> Result<BTreeMap<String, Value>, RuntimeError> {
|
||||
let mut provided = BTreeMap::new();
|
||||
let mut positional = 0usize;
|
||||
for arg in args {
|
||||
match &arg.name {
|
||||
Some(name) => {
|
||||
if !builtin.params.iter().any(|param| param.name == name) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!("`{}` has no parameter named `{name}`", builtin.name),
|
||||
));
|
||||
}
|
||||
provided.insert(name.clone(), arg.value);
|
||||
}
|
||||
None => {
|
||||
let Some(param) = builtin.params.get(positional) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
Some(arg.span),
|
||||
format!(
|
||||
"`{}` accepts at most {} argument(s)",
|
||||
builtin.name,
|
||||
builtin.params.len()
|
||||
),
|
||||
));
|
||||
};
|
||||
provided.insert(param.name.to_string(), arg.value);
|
||||
positional += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for param in builtin.params {
|
||||
if param.required && !provided.contains_key(param.name) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
span,
|
||||
format!(
|
||||
"`{}` is missing required argument `{}`",
|
||||
builtin.name, param.name
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(provided)
|
||||
}
|
||||
|
||||
fn member_of(value: Value, name: &str, span: Option<Span>) -> Result<Value, RuntimeError> {
|
||||
match value {
|
||||
Value::Map(map) => map.get(name).cloned().ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::UnknownField,
|
||||
span,
|
||||
format!("map has no field `{name}`"),
|
||||
)
|
||||
}),
|
||||
Value::Formula(formula) => match name {
|
||||
"latex" => Ok(Value::Text(formula.latex)),
|
||||
"display" => Ok(Value::Bool(formula.display)),
|
||||
"unit" => Ok(match formula.unit {
|
||||
Some(unit) => Value::Text(unit),
|
||||
None => Value::None,
|
||||
}),
|
||||
_ => Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownField,
|
||||
span,
|
||||
format!("Formula has no field `{name}`"),
|
||||
)),
|
||||
},
|
||||
Value::Code(code) => match name {
|
||||
"language" => Ok(Value::Text(code.language)),
|
||||
"source" => Ok(Value::Text(code.source)),
|
||||
"content_hash" => Ok(Value::Text(code.content_hash)),
|
||||
"unit" => Ok(match code.unit {
|
||||
Some(unit) => Value::Text(unit),
|
||||
None => Value::None,
|
||||
}),
|
||||
_ => Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownField,
|
||||
span,
|
||||
format!("Code has no field `{name}`"),
|
||||
)),
|
||||
},
|
||||
other => Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownField,
|
||||
span,
|
||||
format!("{} has no fields", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn index_value_of(base: Value, index: Value, span: Option<Span>) -> Result<Value, RuntimeError> {
|
||||
match (base, index) {
|
||||
(Value::List(items), Value::Int(index)) => {
|
||||
let len = items.len() as i64;
|
||||
let Some(position) = resolve_index(&index, len) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::IndexOutOfBounds,
|
||||
span,
|
||||
format!("list index {index} is out of bounds for length {len}"),
|
||||
));
|
||||
};
|
||||
Ok(items[position].clone())
|
||||
}
|
||||
(Value::Text(text), Value::Int(index)) => {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len() as i64;
|
||||
let Some(position) = resolve_index(&index, len) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::IndexOutOfBounds,
|
||||
span,
|
||||
format!("text index {index} is out of bounds for length {len}"),
|
||||
));
|
||||
};
|
||||
Ok(Value::Text(chars[position].to_string()))
|
||||
}
|
||||
(Value::Map(map), Value::Text(key)) => map.get(&key).cloned().ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::UnknownField,
|
||||
span,
|
||||
format!("map has no key `{key}`"),
|
||||
)
|
||||
}),
|
||||
(base, index) => Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
span,
|
||||
format!(
|
||||
"cannot index {} with {}",
|
||||
base.type_name(),
|
||||
index.type_name()
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_index(index: &num_bigint::BigInt, len: i64) -> Option<usize> {
|
||||
use num_traits::ToPrimitive;
|
||||
let index = index.to_i64()?;
|
||||
let position = if index < 0 { len + index } else { index };
|
||||
if position < 0 || position >= len {
|
||||
None
|
||||
} else {
|
||||
Some(position as usize)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Rust tree-walk interpreter for Marqdo IR.
|
||||
//!
|
||||
//! The interpreter is Marqdo's own execution engine: expressions, scoping,
|
||||
//! calls, branches, loops and returns are evaluated here, never by translating
|
||||
//! to Python or another language. Every side effect goes through
|
||||
//! [`marqdo_host::Host`]; prose never reaches this layer because it is absent
|
||||
//! from the IR.
|
||||
|
||||
mod builtins_impl;
|
||||
mod interpreter;
|
||||
mod value_ops;
|
||||
|
||||
pub use interpreter::{run, EvaluatedArg, Interpreter, RunOutcome};
|
||||
|
||||
pub use marqdo_value::{RuntimeError, Value};
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Numeric and structural operations.
|
||||
//!
|
||||
//! Numeric semantics follow spec/evaluation.md §2: Int arithmetic is exact,
|
||||
//! `/` always yields Float, mixed arithmetic yields Float, and Int/Float
|
||||
//! comparisons are exact (the float is treated as the binary rational it is).
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use marqdo_expression::{BinaryOp, UnaryOp};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
use num_bigint::BigInt;
|
||||
use num_rational::BigRational;
|
||||
use num_traits::{Signed, ToPrimitive, Zero};
|
||||
|
||||
/// Maximum exponent accepted by `**` for exact integer powers.
|
||||
pub const MAX_EXACT_EXPONENT: i64 = 100_000;
|
||||
/// Maximum estimated bits of an exact integer power result.
|
||||
pub const MAX_POWER_BITS: u64 = 1_000_000;
|
||||
|
||||
/// Apply a unary operator.
|
||||
pub fn unary(op: UnaryOp, value: Value, span: Option<Span>) -> Result<Value, RuntimeError> {
|
||||
match (op, value) {
|
||||
(UnaryOp::Not, Value::Bool(value)) => Ok(Value::Bool(!value)),
|
||||
(UnaryOp::Not, other) => Err(type_error(
|
||||
span,
|
||||
format!("`not` expects Bool, got {}", other.type_name()),
|
||||
)),
|
||||
(UnaryOp::Neg, Value::Int(value)) => Ok(Value::Int(-value)),
|
||||
(UnaryOp::Neg, Value::Float(value)) => Ok(Value::Float(-value)),
|
||||
(UnaryOp::Neg, other) => Err(type_error(
|
||||
span,
|
||||
format!("unary `-` expects a number, got {}", other.type_name()),
|
||||
)),
|
||||
(UnaryOp::Pos, value @ Value::Int(_)) | (UnaryOp::Pos, value @ Value::Float(_)) => {
|
||||
Ok(value)
|
||||
}
|
||||
(UnaryOp::Pos, other) => Err(type_error(
|
||||
span,
|
||||
format!("unary `+` expects a number, got {}", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a binary operator (short-circuit operators are handled by the caller).
|
||||
pub fn binary(
|
||||
op: BinaryOp,
|
||||
left: Value,
|
||||
right: Value,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
use BinaryOp::*;
|
||||
match op {
|
||||
Eq | Ne | Lt | Le | Gt | Ge => compare(op, left, right, span),
|
||||
Add => {
|
||||
if let (Value::Text(a), Value::Text(b)) = (&left, &right) {
|
||||
return Ok(Value::Text(format!("{a}{b}")));
|
||||
}
|
||||
numeric_binary(op, left, right, span)
|
||||
}
|
||||
Sub | Mul | Div | Pow => numeric_binary(op, left, right, span),
|
||||
FloorDiv | Mod => integer_binary(op, left, right, span),
|
||||
And | Or => Err(RuntimeError::new(
|
||||
ErrorCategory::Internal,
|
||||
span,
|
||||
"logical operators must be short-circuited by the evaluator",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn compare(
|
||||
op: BinaryOp,
|
||||
left: Value,
|
||||
right: Value,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let ordering = match (&left, &right) {
|
||||
(Value::Int(_), Value::Int(_))
|
||||
| (Value::Int(_), Value::Float(_))
|
||||
| (Value::Float(_), Value::Int(_))
|
||||
| (Value::Float(_), Value::Float(_)) => numeric_ordering(&left, &right),
|
||||
(Value::Text(a), Value::Text(b)) => Some(a.cmp(b)),
|
||||
(Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)),
|
||||
(Value::Unit, Value::Unit) | (Value::None, Value::None) => Some(Ordering::Equal),
|
||||
(Value::None, Value::Unit) | (Value::Unit, Value::None) => Some(Ordering::Less),
|
||||
(Value::List(a), Value::List(b)) => {
|
||||
return Ok(Value::Bool(match op {
|
||||
BinaryOp::Eq => a == b,
|
||||
BinaryOp::Ne => a != b,
|
||||
_ => {
|
||||
return Err(type_error(
|
||||
span,
|
||||
"List ordering comparisons are not supported".to_string(),
|
||||
))
|
||||
}
|
||||
}))
|
||||
}
|
||||
(Value::Map(a), Value::Map(b)) => {
|
||||
return Ok(Value::Bool(match op {
|
||||
BinaryOp::Eq => a == b,
|
||||
BinaryOp::Ne => a != b,
|
||||
_ => {
|
||||
return Err(type_error(
|
||||
span,
|
||||
"Map ordering comparisons are not supported".to_string(),
|
||||
))
|
||||
}
|
||||
}))
|
||||
}
|
||||
(a, b) => {
|
||||
if op == BinaryOp::Eq {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
if op == BinaryOp::Ne {
|
||||
return Ok(Value::Bool(true));
|
||||
}
|
||||
return Err(type_error(
|
||||
span,
|
||||
format!("cannot compare {} with {}", a.type_name(), b.type_name()),
|
||||
));
|
||||
}
|
||||
};
|
||||
let Some(ordering) = ordering else {
|
||||
// NaN: equal compares false, everything else also false.
|
||||
return Ok(Value::Bool(false));
|
||||
};
|
||||
Ok(Value::Bool(match op {
|
||||
BinaryOp::Eq => ordering == Ordering::Equal,
|
||||
BinaryOp::Ne => ordering != Ordering::Equal,
|
||||
BinaryOp::Lt => ordering == Ordering::Less,
|
||||
BinaryOp::Le => ordering != Ordering::Greater,
|
||||
BinaryOp::Gt => ordering == Ordering::Greater,
|
||||
BinaryOp::Ge => ordering != Ordering::Less,
|
||||
_ => unreachable!("compare called with non-comparison op"),
|
||||
}))
|
||||
}
|
||||
|
||||
fn numeric_ordering(left: &Value, right: &Value) -> Option<Ordering> {
|
||||
match (to_rational(left), to_rational(right)) {
|
||||
(Some(a), Some(b)) => Some(a.cmp(&b)),
|
||||
_ => match (to_float(left), to_float(right)) {
|
||||
(Some(a), Some(b)) => a.partial_cmp(&b),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn to_rational(value: &Value) -> Option<BigRational> {
|
||||
match value {
|
||||
Value::Int(value) => Some(BigRational::from_integer(value.clone())),
|
||||
Value::Float(value) => BigRational::from_float(*value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_float(value: &Value) -> Option<f64> {
|
||||
match value {
|
||||
Value::Int(value) => value.to_f64(),
|
||||
Value::Float(value) => Some(*value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_binary(
|
||||
op: BinaryOp,
|
||||
left: Value,
|
||||
right: Value,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
// Exact integer arithmetic when both sides are Int.
|
||||
if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
|
||||
return match op {
|
||||
BinaryOp::Add => Ok(Value::Int(a + b)),
|
||||
BinaryOp::Sub => Ok(Value::Int(a - b)),
|
||||
BinaryOp::Mul => Ok(Value::Int(a * b)),
|
||||
BinaryOp::Div => {
|
||||
if b.is_zero() {
|
||||
Err(division_by_zero(span))
|
||||
} else {
|
||||
let quotient = BigRational::new(a.clone(), b.clone());
|
||||
Ok(Value::Float(quotient.to_f64().unwrap_or(f64::NAN)))
|
||||
}
|
||||
}
|
||||
BinaryOp::Pow => integer_power(a, b, span),
|
||||
_ => Err(RuntimeError::new(
|
||||
ErrorCategory::Internal,
|
||||
span,
|
||||
"unsupported numeric operator",
|
||||
)),
|
||||
};
|
||||
}
|
||||
let (Some(a), Some(b)) = (to_float(&left), to_float(&right)) else {
|
||||
return Err(type_error(
|
||||
span,
|
||||
format!(
|
||||
"operator `{}` does not accept {} and {}",
|
||||
op_symbol(op),
|
||||
left.type_name(),
|
||||
right.type_name()
|
||||
),
|
||||
));
|
||||
};
|
||||
Ok(match op {
|
||||
BinaryOp::Add => Value::Float(a + b),
|
||||
BinaryOp::Sub => Value::Float(a - b),
|
||||
BinaryOp::Mul => Value::Float(a * b),
|
||||
BinaryOp::Div => {
|
||||
if b == 0.0 {
|
||||
return Err(division_by_zero(span));
|
||||
}
|
||||
Value::Float(a / b)
|
||||
}
|
||||
BinaryOp::Pow => Value::Float(a.powf(b)),
|
||||
_ => {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Internal,
|
||||
span,
|
||||
"unsupported numeric operator",
|
||||
))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn integer_binary(
|
||||
op: BinaryOp,
|
||||
left: Value,
|
||||
right: Value,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let (Value::Int(a), Value::Int(b)) = (&left, &right) else {
|
||||
return Err(type_error(
|
||||
span,
|
||||
format!(
|
||||
"operator `{}` requires Int operands, got {} and {}",
|
||||
op_symbol(op),
|
||||
left.type_name(),
|
||||
right.type_name()
|
||||
),
|
||||
));
|
||||
};
|
||||
if b.is_zero() {
|
||||
return Err(division_by_zero(span));
|
||||
}
|
||||
let quotient = a / b;
|
||||
let remainder = a % b;
|
||||
// Floor division: adjust when the truncated quotient is not the floor.
|
||||
let floored = if !remainder.is_zero() && (remainder.is_negative() != b.is_negative()) {
|
||||
quotient - BigInt::from(1)
|
||||
} else {
|
||||
quotient
|
||||
};
|
||||
Ok(match op {
|
||||
BinaryOp::FloorDiv => Value::Int(floored),
|
||||
BinaryOp::Mod => Value::Int(a - &floored * b),
|
||||
_ => {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Internal,
|
||||
span,
|
||||
"unsupported integer operator",
|
||||
))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn integer_power(
|
||||
base: &BigInt,
|
||||
exponent: &BigInt,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let Some(exponent) = exponent.to_i64() else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
"integer exponent is too large",
|
||||
));
|
||||
};
|
||||
if exponent < 0 {
|
||||
return Err(type_error(
|
||||
span,
|
||||
"negative integer exponents are not exact; use Float operands or `/`".to_string(),
|
||||
));
|
||||
}
|
||||
if exponent > MAX_EXACT_EXPONENT {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
format!("integer exponent exceeds the limit of {MAX_EXACT_EXPONENT}"),
|
||||
));
|
||||
}
|
||||
let estimated_bits = base.bits().max(1).saturating_mul(exponent as u64);
|
||||
if estimated_bits > MAX_POWER_BITS {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
"integer power result would be too large",
|
||||
));
|
||||
}
|
||||
Ok(Value::Int(base.pow(exponent as u32)))
|
||||
}
|
||||
|
||||
fn op_symbol(op: BinaryOp) -> &'static str {
|
||||
match op {
|
||||
BinaryOp::Add => "+",
|
||||
BinaryOp::Sub => "-",
|
||||
BinaryOp::Mul => "*",
|
||||
BinaryOp::Div => "/",
|
||||
BinaryOp::FloorDiv => "//",
|
||||
BinaryOp::Mod => "%",
|
||||
BinaryOp::Pow => "**",
|
||||
BinaryOp::And => "and",
|
||||
BinaryOp::Or => "or",
|
||||
BinaryOp::Eq => "==",
|
||||
BinaryOp::Ne => "!=",
|
||||
BinaryOp::Lt => "<",
|
||||
BinaryOp::Le => "<=",
|
||||
BinaryOp::Gt => ">",
|
||||
BinaryOp::Ge => ">=",
|
||||
}
|
||||
}
|
||||
|
||||
fn type_error(span: Option<Span>, message: String) -> RuntimeError {
|
||||
RuntimeError::type_error(span, message)
|
||||
}
|
||||
|
||||
fn division_by_zero(span: Option<Span>) -> RuntimeError {
|
||||
RuntimeError::new(ErrorCategory::DivisionByZero, span, "division by zero")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn int(value: i64) -> Value {
|
||||
Value::int(value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_arithmetic_is_exact() {
|
||||
let big = Value::Int("12345678901234567890".parse().unwrap());
|
||||
let result = binary(BinaryOp::Mul, big, int(2), None).unwrap();
|
||||
assert_eq!(result.display(), "24691357802469135780");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn division_always_yields_float() {
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Div, int(1), int(2), None).unwrap(),
|
||||
Value::Float(0.5)
|
||||
);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Div, int(4), int(2), None).unwrap(),
|
||||
Value::Float(2.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floor_division_and_modulo_signs() {
|
||||
assert_eq!(
|
||||
binary(BinaryOp::FloorDiv, int(-7), int(2), None).unwrap(),
|
||||
int(-4)
|
||||
);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Mod, int(-7), int(2), None).unwrap(),
|
||||
int(1)
|
||||
);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::FloorDiv, int(7), int(-2), None).unwrap(),
|
||||
int(-4)
|
||||
);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Mod, int(7), int(-2), None).unwrap(),
|
||||
int(-1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_comparisons_are_exact() {
|
||||
let huge = Value::Int("9007199254740993".parse().unwrap());
|
||||
let float = Value::Float(9007199254740992.0);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Gt, huge, float, None).unwrap(),
|
||||
Value::Bool(true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_concatenation_and_power() {
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Add, Value::text("a"), Value::text("b"), None).unwrap(),
|
||||
Value::text("ab")
|
||||
);
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Pow, int(2), int(10), None).unwrap(),
|
||||
int(1024)
|
||||
);
|
||||
assert!(binary(BinaryOp::Pow, int(2), int(-1), None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn division_by_zero_is_an_error() {
|
||||
assert_eq!(
|
||||
binary(BinaryOp::Div, int(1), int(0), None)
|
||||
.unwrap_err()
|
||||
.category,
|
||||
ErrorCategory::DivisionByZero
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! End-to-end interpreter tests: Markdown source → frontend IR → execution.
|
||||
|
||||
use marqdo_host::{Capabilities, Host, StdHost};
|
||||
use marqdo_ir::{ModuleId, Program};
|
||||
use marqdo_runtime::{run, EvaluatedArg, RuntimeError, Value};
|
||||
use marqdo_sandbox::SandboxMode;
|
||||
use marqdo_span::Span;
|
||||
|
||||
fn build(source: &str) -> Program {
|
||||
let result = marqdo_frontend::analyze_source("index.mq.md", source);
|
||||
assert!(
|
||||
!result.has_errors(),
|
||||
"unexpected compile diagnostics: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
let module_id = ModuleId::from("index.mq.md");
|
||||
let mut program = Program {
|
||||
main_module: Some(module_id.clone()),
|
||||
..Program::default()
|
||||
};
|
||||
program.insert(result.module);
|
||||
program
|
||||
}
|
||||
|
||||
fn host() -> StdHost {
|
||||
StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
}
|
||||
|
||||
fn run_named(source: &str, function: &str, args: &[(&str, Value)]) -> Result<Value, RuntimeError> {
|
||||
let program = build(source);
|
||||
let mut host = host();
|
||||
let args = args
|
||||
.iter()
|
||||
.map(|(name, value)| EvaluatedArg::named(*name, value.clone(), Span::default()))
|
||||
.collect();
|
||||
run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
function,
|
||||
args,
|
||||
)
|
||||
.map(|outcome| outcome.value)
|
||||
}
|
||||
|
||||
fn run_and_output(source: &str, function: &str) -> (Result<Value, RuntimeError>, String) {
|
||||
let program = build(source);
|
||||
let mut host = host();
|
||||
let result = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
function,
|
||||
Vec::new(),
|
||||
)
|
||||
.map(|outcome| outcome.value);
|
||||
let output = String::from_utf8(host.take_output()).unwrap();
|
||||
(result, output)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursion_branch_and_return() {
|
||||
let source = "## 阶乘\n\n1. `n <= 1`\n\n *1*\n\n2. `n > 1`\n\n **结果 = n * 阶乘(n=n-1)**\n\n *结果*\n";
|
||||
let value = run_named(source, "阶乘", &[("n", Value::int(5))]).unwrap();
|
||||
assert_eq!(value, Value::int(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_prints_and_returns_unit_for_fallthrough() {
|
||||
let source = "## 倒计时\n\n**n = 3**\n\n- `n > 0`\n\n > 打印(n)\n\n **n = n - 1**\n";
|
||||
let (result, output) = run_and_output(source, "倒计时");
|
||||
assert_eq!(result.unwrap(), Value::Unit);
|
||||
assert_eq!(output, "3\n2\n1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_inside_loop_propagates() {
|
||||
let source = "## 找\n\n**i = 0**\n\n- `true`\n\n **i = i + 1**\n\n - `i >= 3`\n\n *i*\n";
|
||||
let (result, _) = run_and_output(source, "找");
|
||||
assert_eq!(result.unwrap(), Value::int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_signature_supports_positional_arguments() {
|
||||
let source = "## 加\n\n`(a: Int, b: Int = 10)`\n\n*a + b*\n";
|
||||
let program = build(source);
|
||||
let mut host = host();
|
||||
let result = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
"加",
|
||||
vec![EvaluatedArg::positional(Value::int(2), Span::default())],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.value, Value::int(12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins_for_conversions_and_length() {
|
||||
let source = "## f\n\n*长度(\"你好\") + 整数(\"40\") + 整数(2.0)*\n";
|
||||
let value = run_named(source, "f", &[]).unwrap();
|
||||
assert_eq!(value, Value::int(44));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_reference_can_be_called() {
|
||||
let source =
|
||||
"## 平方\n\n`(n: Int)`\n\n*n * n*\n\n## 主\n\n**f = ref(\"#平方\")**\n\n*f(n=4)*\n";
|
||||
let value = run_named(source, "主", &[]).unwrap();
|
||||
assert_eq!(value, Value::int(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_bool_condition_is_a_runtime_error() {
|
||||
let source = "## f\n\n**x = 1**\n\n- `x`\n\n > 打印(1)\n\n*x*\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "runtime.type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fuel_budget_is_enforced() {
|
||||
let program = build("## f\n\n- `true`\n\n > 打印(1)\n\n*0*\n");
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
);
|
||||
host.budget.fuel = 200;
|
||||
let error = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
"f",
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), "resource.exhausted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursion_depth_is_bounded() {
|
||||
let source = "## f\n\n*f(n=n + 1)*\n";
|
||||
let program = build(source);
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
);
|
||||
host.budget.stack_limit = 8;
|
||||
let error = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
"f",
|
||||
vec![EvaluatedArg::named("n", Value::int(0), Span::default())],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), "resource.exhausted");
|
||||
assert!(error.frames.len() >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_ref_resource_is_an_error() {
|
||||
let source = "## f\n\n### 公式\n\n$$a = 1$$\n\n$$b = 2$$\n\n**x = ref(\"#公式\")**\n\n*x*\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "ref.ambiguous");
|
||||
}
|
||||
Reference in new issue
Block a user