2041 lines
74 KiB
Rust
2041 lines
74 KiB
Rust
//! Tree-walk interpreter (Phase I).
|
|
|
|
use anyhow::{bail, Result};
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use crate::ast::{
|
|
Arg, BinaryOp, CallExpr, Expr, Function, IndexKey, InterpPart, Literal, Module, Param, Stmt,
|
|
};
|
|
use crate::builtin::{
|
|
builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join,
|
|
builtin_len, builtin_split, builtin_str, builtin_trim,
|
|
builtin_type,
|
|
};
|
|
use crate::debug::{emit_trace, DebugController};
|
|
use crate::diagnostics::{Diagnostic, DiagnosticFrame, SourceIdentity, Span};
|
|
use crate::host::{call_host, HostContext};
|
|
use crate::input_feed::InputFeed;
|
|
use crate::capture::{
|
|
BranchHit, CallFrame, LoopFrame, LoopHit, LoopIter, StmtEvent, StmtEventKind, ViewTrace,
|
|
};
|
|
use crate::value::Value;
|
|
use std::sync::Arc;
|
|
|
|
pub struct Interpreter {
|
|
pub path: Option<PathBuf>,
|
|
pub trace: bool,
|
|
capture: bool,
|
|
pub captured_stdout: String,
|
|
/// Bindings in the entry (`# main` / sole object) env after it finishes.
|
|
pub entry_bindings: HashMap<String, Value>,
|
|
/// Silent branch/loop hits for `marqdo view` annotations.
|
|
pub view_trace: ViewTrace,
|
|
next_call_id: u32,
|
|
call_stack: Vec<u32>,
|
|
fn_ordinals: HashMap<String, u32>,
|
|
next_loop_id: u32,
|
|
/// Active loops: `(loop_id, iter_index_0based)`.
|
|
loop_stack: Vec<(u32, u32)>,
|
|
current_span: Span,
|
|
current_source: SourceIdentity,
|
|
current_module: Option<*const Module>,
|
|
diagnostic_frames: Vec<DiagnosticFrame>,
|
|
input: InputFeed,
|
|
host: HostContext,
|
|
debug: Option<Arc<DebugController>>,
|
|
/// Entry module pointer for `host_query("call_lib_path")` while plugins run.
|
|
site_module: Option<*const Module>,
|
|
}
|
|
|
|
struct Env {
|
|
vars: HashMap<String, Value>,
|
|
}
|
|
|
|
impl Env {
|
|
fn new() -> Self {
|
|
Self {
|
|
vars: HashMap::new(),
|
|
}
|
|
}
|
|
|
|
/// Phase 2: lift resolved Artifact Metadata into the entry environment.
|
|
/// Existing keys are left unchanged (`or_insert` semantics).
|
|
fn with_metadata(module: &Module) -> Self {
|
|
let mut env = Self::new();
|
|
for (k, v) in &module.metadata {
|
|
env.vars.entry(k.clone()).or_insert_with(|| v.clone());
|
|
}
|
|
env
|
|
}
|
|
|
|
fn get(&self, name: &str) -> Option<&Value> {
|
|
self.vars.get(name)
|
|
}
|
|
|
|
fn set(&mut self, name: String, value: Value) {
|
|
self.vars.insert(name, value);
|
|
}
|
|
|
|
fn vars_clone(&self) -> HashMap<String, Value> {
|
|
self.vars.clone()
|
|
}
|
|
}
|
|
|
|
pub(crate) enum EvArg {
|
|
Positional(Value),
|
|
Named(String, Value),
|
|
}
|
|
|
|
impl Interpreter {
|
|
pub fn new(path: Option<&Path>, trace: bool) -> Self {
|
|
Self {
|
|
path: path.map(|p| p.to_path_buf()),
|
|
trace,
|
|
capture: false,
|
|
captured_stdout: String::new(),
|
|
entry_bindings: HashMap::new(),
|
|
view_trace: ViewTrace::default(),
|
|
next_call_id: 1,
|
|
call_stack: Vec::new(),
|
|
fn_ordinals: HashMap::new(),
|
|
next_loop_id: 1,
|
|
loop_stack: Vec::new(),
|
|
current_span: Span::new(1, 1),
|
|
current_source: SourceIdentity { path: path.map(Path::to_path_buf), sha256: None },
|
|
current_module: None,
|
|
diagnostic_frames: Vec::new(),
|
|
input: InputFeed::new(false, Vec::new()),
|
|
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
|
debug: None,
|
|
site_module: None,
|
|
}
|
|
}
|
|
|
|
pub fn with_capture(path: Option<&Path>, trace: bool) -> Self {
|
|
Self {
|
|
path: path.map(|p| p.to_path_buf()),
|
|
trace,
|
|
capture: true,
|
|
captured_stdout: String::new(),
|
|
entry_bindings: HashMap::new(),
|
|
view_trace: ViewTrace::default(),
|
|
next_call_id: 1,
|
|
call_stack: Vec::new(),
|
|
fn_ordinals: HashMap::new(),
|
|
next_loop_id: 1,
|
|
loop_stack: Vec::new(),
|
|
current_span: Span::new(1, 1),
|
|
current_source: SourceIdentity { path: path.map(Path::to_path_buf), sha256: None },
|
|
current_module: None,
|
|
diagnostic_frames: Vec::new(),
|
|
input: InputFeed::new(true, Vec::new()),
|
|
host: HostContext::for_capture(path, Default::default()),
|
|
debug: None,
|
|
site_module: None,
|
|
}
|
|
}
|
|
|
|
pub fn with_stdin(mut self, lines: Vec<String>) -> Self {
|
|
self.input = InputFeed::new(self.capture, lines);
|
|
self
|
|
}
|
|
|
|
pub fn with_host(mut self, host: HostContext) -> Self {
|
|
self.host = host;
|
|
self
|
|
}
|
|
|
|
pub fn with_debug(mut self, debug: Arc<DebugController>) -> Self {
|
|
self.debug = Some(debug);
|
|
self
|
|
}
|
|
|
|
pub fn take_plots(&mut self) -> Vec<crate::host::PlotArtifact> {
|
|
std::mem::take(&mut self.host.plots)
|
|
}
|
|
|
|
#[cfg(all(test, feature = "exec-host"))]
|
|
pub(crate) fn foreign_source_evidence(&mut self) -> (Vec<Value>, Vec<Value>, Vec<crate::host::foreign_session::ProtocolStep>) {
|
|
crate::source_refinement_tests::boundary_evidence(&mut self.host)
|
|
}
|
|
|
|
#[cfg(all(test, feature = "exec-host"))]
|
|
pub(crate) fn application_evidence(&self) -> (Vec<Value>, Vec<crate::host::foreign_session::ProtocolStep>, usize) {
|
|
(self.host.oracle_observations.clone(), self.host.foreign_protocol_steps.clone(), self.host.foreign_sessions.len())
|
|
}
|
|
|
|
#[cfg(all(test, feature = "exec-host"))]
|
|
pub(crate) fn causal_replay_evidence(&mut self) -> serde_json::Value {
|
|
crate::causal_replay_tests::evidence(&mut self.host)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn diagnostic_scope_state(&self) -> (SourceIdentity, usize, Vec<String>, Vec<u32>, bool) {
|
|
(self.current_source.clone(), self.diagnostic_frames.len(), self.host.call_stack.clone(),
|
|
self.host.call_site_lines.clone(), self.current_module.is_some())
|
|
}
|
|
|
|
fn err(&self, message: impl Into<String>) -> anyhow::Error {
|
|
Diagnostic::new(self.current_source.path.as_deref(), self.current_span, message)
|
|
.with_source(&self.current_source).with_frames(&self.diagnostic_frames).into()
|
|
}
|
|
|
|
fn err_code(&self, code: &str, message: impl Into<String>) -> anyhow::Error {
|
|
anyhow::Error::new(
|
|
Diagnostic::new(self.current_source.path.as_deref(), self.current_span, message)
|
|
.with_source(&self.current_source).with_frames(&self.diagnostic_frames).with_code(code),
|
|
)
|
|
}
|
|
|
|
fn emit_line(&mut self, text: &str) {
|
|
if self.capture {
|
|
self.captured_stdout.push_str(text);
|
|
self.captured_stdout.push('\n');
|
|
} else {
|
|
println!("{text}");
|
|
}
|
|
}
|
|
|
|
fn emit_prompt(&mut self, prompt: &str) {
|
|
if prompt.is_empty() {
|
|
return;
|
|
}
|
|
if self.capture {
|
|
self.captured_stdout.push_str(prompt);
|
|
} else {
|
|
print!("{prompt}");
|
|
use std::io::Write;
|
|
let _ = std::io::stdout().flush();
|
|
}
|
|
}
|
|
|
|
fn current_call_id(&self) -> u32 {
|
|
self.call_stack.last().copied().unwrap_or(0)
|
|
}
|
|
|
|
fn loop_ctx(&self) -> (Option<u32>, Option<u32>) {
|
|
self.loop_stack
|
|
.last()
|
|
.map(|(id, iter)| (Some(*id), Some(*iter)))
|
|
.unwrap_or((None, None))
|
|
}
|
|
|
|
fn push_view_call(&mut self, fun: &Function, env: &Env) {
|
|
if !self.capture {
|
|
return;
|
|
}
|
|
let call_id = self.next_call_id;
|
|
self.next_call_id += 1;
|
|
let ordinal = {
|
|
let e = self.fn_ordinals.entry(fun.name.clone()).or_insert(0);
|
|
*e += 1;
|
|
*e
|
|
};
|
|
let args_brief = fun
|
|
.params
|
|
.iter()
|
|
.filter_map(|p| {
|
|
env.get(&p.name)
|
|
.map(|v| format!("{}={}", p.name, brief_trace_val(v)))
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(", ");
|
|
self.view_trace.calls.push(CallFrame {
|
|
call_id,
|
|
fn_name: fun.name.clone(),
|
|
fn_line: fun.span.line,
|
|
call_line: self.current_span.line,
|
|
ordinal,
|
|
args_brief,
|
|
});
|
|
self.call_stack.push(call_id);
|
|
}
|
|
|
|
fn pop_view_call(&mut self) {
|
|
if self.capture {
|
|
self.call_stack.pop();
|
|
}
|
|
}
|
|
|
|
fn begin_view_loop(
|
|
&mut self,
|
|
line: u32,
|
|
item: Option<&str>,
|
|
collection: Option<&str>,
|
|
) -> u32 {
|
|
let loop_id = self.next_loop_id;
|
|
self.next_loop_id += 1;
|
|
self.view_trace.loop_frames.push(LoopFrame {
|
|
loop_id,
|
|
line,
|
|
item_name: item.map(|s| s.to_string()),
|
|
collection: collection.map(|s| s.to_string()),
|
|
iterations: Vec::new(),
|
|
});
|
|
self.loop_stack.push((loop_id, 0));
|
|
loop_id
|
|
}
|
|
|
|
fn enter_loop_iter(&mut self, loop_id: u32, index: u32, item_value: &str) {
|
|
if let Some((_, cur)) = self.loop_stack.iter_mut().rev().find(|(id, _)| *id == loop_id)
|
|
{
|
|
*cur = index;
|
|
}
|
|
let call_id = self.current_call_id();
|
|
if let Some(fr) = self
|
|
.view_trace
|
|
.loop_frames
|
|
.iter_mut()
|
|
.find(|f| f.loop_id == loop_id)
|
|
{
|
|
fr.iterations.push(LoopIter {
|
|
index,
|
|
item_value: item_value.to_string(),
|
|
call_id,
|
|
});
|
|
}
|
|
}
|
|
|
|
fn end_view_loop(&mut self, loop_id: u32) {
|
|
if self
|
|
.loop_stack
|
|
.last()
|
|
.map(|(id, _)| *id == loop_id)
|
|
.unwrap_or(false)
|
|
{
|
|
self.loop_stack.pop();
|
|
}
|
|
}
|
|
|
|
fn record_stmt_event(&mut self, mut ev: StmtEvent) {
|
|
if self.capture {
|
|
if ev.loop_id.is_none() || ev.iter.is_none() {
|
|
let (lid, iter) = self.loop_ctx();
|
|
if ev.loop_id.is_none() {
|
|
ev.loop_id = lid;
|
|
}
|
|
if ev.iter.is_none() {
|
|
ev.iter = iter;
|
|
}
|
|
}
|
|
self.view_trace.events.push(ev);
|
|
}
|
|
}
|
|
|
|
fn record_branch_hit(&mut self, line: u32, arm_index: usize) {
|
|
let call_id = self.current_call_id();
|
|
if let Some(existing) = self.view_trace.branches.iter_mut().find(|h| {
|
|
h.line == line && h.arm_index == arm_index && h.call_id == call_id
|
|
}) {
|
|
existing.count += 1;
|
|
} else {
|
|
self.view_trace.branches.push(BranchHit {
|
|
line,
|
|
arm_index,
|
|
count: 1,
|
|
call_id,
|
|
});
|
|
}
|
|
let (loop_id, iter) = self.loop_ctx();
|
|
self.record_stmt_event(StmtEvent {
|
|
line,
|
|
kind: StmtEventKind::Branch,
|
|
name: None,
|
|
value_after: Some(format!("arm {}", arm_index + 1)),
|
|
arm_index: Some(arm_index),
|
|
iter,
|
|
call_id,
|
|
loop_id,
|
|
});
|
|
}
|
|
|
|
fn record_loop_hit(&mut self, line: u32, iterations: u32, last_item: Option<String>) {
|
|
if let Some(existing) = self.view_trace.loops.iter_mut().find(|h| h.line == line) {
|
|
existing.iterations = iterations;
|
|
if last_item.is_some() {
|
|
existing.last_item = last_item.clone();
|
|
}
|
|
} else {
|
|
self.view_trace.loops.push(LoopHit {
|
|
line,
|
|
iterations,
|
|
last_item: last_item.clone(),
|
|
});
|
|
}
|
|
let (loop_id, _) = self.loop_ctx();
|
|
self.record_stmt_event(StmtEvent {
|
|
line,
|
|
kind: StmtEventKind::Loop,
|
|
name: None,
|
|
value_after: Some(format!("{iterations} iters")),
|
|
arm_index: None,
|
|
// Summary event: total count (not 0-based index).
|
|
iter: Some(iterations),
|
|
call_id: self.current_call_id(),
|
|
loop_id,
|
|
});
|
|
}
|
|
|
|
/// Run a function by name anywhere in the module (for `lib/subtask` workers).
|
|
pub fn invoke_function(
|
|
&mut self,
|
|
module: &Module,
|
|
name: &str,
|
|
args: &[(String, Value)],
|
|
) -> Result<Value> {
|
|
let fun = find_function_anywhere(module, name)
|
|
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
|
|
self.invoke_bound_function(module, fun, args)
|
|
}
|
|
|
|
/// Run an already-bound function node (SymbolId / source-line identity).
|
|
/// Prefer this over name lookup so nested same-named functions cannot drift (G07).
|
|
pub fn invoke_bound_function(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
args: &[(String, Value)],
|
|
) -> Result<Value> {
|
|
let previous=self.site_module;
|
|
self.site_module=Some(module as *const Module);
|
|
let result=self.run_function(module, fun, Env::new(), args, false);
|
|
self.site_module=previous;
|
|
result
|
|
}
|
|
|
|
/// Bind named arguments for an external call. Unknown names, missing
|
|
/// required parameters, and contract mismatches are errors. Defaults run.
|
|
pub fn bind_external_args(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
args: &[(String, Value)],
|
|
) -> Result<Vec<(String, Value)>> {
|
|
let previous=self.site_module;
|
|
self.site_module=Some(module as *const Module);
|
|
let result=self.in_function_source(module, fun, |this| this.bind_external_args_inner(module, fun, args));
|
|
self.site_module=previous;
|
|
result
|
|
}
|
|
|
|
fn bind_external_args_inner(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
args: &[(String, Value)],
|
|
) -> Result<Vec<(String, Value)>> {
|
|
self.current_span = fun.span;
|
|
self.host.current_line = fun.span.line;
|
|
let mut named: HashMap<String, Value> = HashMap::new();
|
|
for (k, v) in args {
|
|
if named.insert(k.clone(), v.clone()).is_some() {
|
|
return Err(self.err_code(
|
|
"call.duplicate_arg",
|
|
format!("duplicate named argument `{k}`"),
|
|
));
|
|
}
|
|
}
|
|
for k in named.keys() {
|
|
if !fun.params.iter().any(|p| &p.name == k) {
|
|
return Err(self.err_code(
|
|
"call.unknown_arg",
|
|
format!("unknown argument `{k}`"),
|
|
));
|
|
}
|
|
}
|
|
let ev: Vec<EvArg> = named
|
|
.into_iter()
|
|
.map(|(k, v)| EvArg::Named(k, v))
|
|
.collect();
|
|
let mut env = Env::new();
|
|
let bound = bind_function_args(self, module, fun, &mut env, &fun.params, &ev, false)
|
|
.map_err(|error| {
|
|
if Diagnostic::find(&error).is_some() { return error; }
|
|
let m = error.to_string();
|
|
if m.starts_with("missing argument") {
|
|
self.err_code("call.missing_arg", m)
|
|
} else if m.starts_with("duplicate named argument") {
|
|
self.err_code("call.duplicate_arg", m)
|
|
} else {
|
|
self.err(m)
|
|
}
|
|
})?;
|
|
if let Some(c) = &fun.contract {
|
|
if let Some(d) = crate::contract::call_arg_diag(
|
|
c,
|
|
&fun.name,
|
|
&bound,
|
|
self.current_source.path.as_deref(),
|
|
fun.span,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
let mut out = Vec::new();
|
|
for p in &fun.params {
|
|
if let Some(v) = bound.get(&p.name) {
|
|
out.push((p.name.clone(), v.clone()));
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
fn argument_error(&self, error: anyhow::Error) -> anyhow::Error {
|
|
if Diagnostic::find(&error).is_some() { error } else { self.err(error.to_string()) }
|
|
}
|
|
|
|
/// Call a function using (and updating) [`Self::entry_bindings`] from `# main`.
|
|
/// Used by browser WASM sessions so handlers share state with the entry object.
|
|
pub fn invoke_in_entry(
|
|
&mut self,
|
|
module: &Module,
|
|
name: &str,
|
|
args: &[(String, Value)],
|
|
) -> Result<Value> {
|
|
let fun = find_function_anywhere(module, name)
|
|
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
|
|
let mut env = Env::with_metadata(module);
|
|
for (k, v) in &self.entry_bindings {
|
|
env.set(k.clone(), v.clone());
|
|
}
|
|
let prev = self.site_module;
|
|
self.site_module = Some(module as *const Module);
|
|
let result = self.run_function(module, fun, env, args, true);
|
|
self.site_module = prev;
|
|
result
|
|
}
|
|
|
|
/// Evaluate only the entry object's top-level assignments, without running
|
|
/// calls/returns/control flow. This is the view plan's language-native
|
|
/// projection: cell tables are ordinary Marqdo values, not source scans.
|
|
/// Evaluate selected entry bindings plus their assignment dependencies.
|
|
/// This is the view plan's language-native projection: cell tables are
|
|
/// ordinary Marqdo values, not source scans.
|
|
pub fn capture_declarations(
|
|
&mut self,
|
|
module: &Module,
|
|
names: &[&str],
|
|
) -> Result<std::collections::HashMap<String, Value>> {
|
|
let prev = self.site_module;
|
|
self.site_module = Some(module as *const Module);
|
|
let result = (|| {
|
|
let entry = find_top(module, "main").or_else(|| {
|
|
let entries: Vec<&Function> = module
|
|
.functions
|
|
.iter()
|
|
.filter(|f| f.is_object() && f.params.is_empty())
|
|
.collect();
|
|
if entries.len() == 1 {
|
|
Some(entries[0])
|
|
} else {
|
|
None
|
|
}
|
|
});
|
|
let entry = entry.ok_or_else(|| self.err("no `# main` object to inspect"))?;
|
|
let assignments: std::collections::HashMap<&str, &Expr> = entry
|
|
.body
|
|
.iter()
|
|
.filter_map(|stmt| match stmt {
|
|
Stmt::Assign { name, value, .. } => Some((name.as_str(), value)),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
let mut env = Env::with_metadata(module);
|
|
let mut done = std::collections::HashSet::new();
|
|
let mut visiting = std::collections::HashSet::new();
|
|
|
|
fn resolve(
|
|
this: &mut Interpreter,
|
|
module: &Module,
|
|
fun: &Function,
|
|
assignments: &std::collections::HashMap<&str, &Expr>,
|
|
name: &str,
|
|
env: &mut Env,
|
|
done: &mut std::collections::HashSet<String>,
|
|
visiting: &mut std::collections::HashSet<String>,
|
|
) -> Result<()> {
|
|
if done.contains(name) {
|
|
return Ok(());
|
|
}
|
|
if !visiting.insert(name.to_string()) {
|
|
return Err(this.err(format!("cyclic view-plan binding `{name}`")));
|
|
}
|
|
let Some(expr) = assignments.get(name) else {
|
|
visiting.remove(name);
|
|
return Ok(());
|
|
};
|
|
let mut deps = std::collections::HashSet::new();
|
|
collect_decl_reads(expr, &mut deps);
|
|
for dep in deps {
|
|
if assignments.contains_key(dep.as_str()) && env.get(&dep).is_none() {
|
|
resolve(this, module, fun, assignments, &dep, env, done, visiting)?;
|
|
}
|
|
}
|
|
let value = this.eval_expr(module, fun, env, expr)?;
|
|
env.set(name.to_string(), value);
|
|
done.insert(name.to_string());
|
|
visiting.remove(name);
|
|
Ok(())
|
|
}
|
|
|
|
for name in names {
|
|
resolve(
|
|
self,
|
|
module,
|
|
entry,
|
|
&assignments,
|
|
name,
|
|
&mut env,
|
|
&mut done,
|
|
&mut visiting,
|
|
)?;
|
|
}
|
|
self.entry_bindings = env.vars_clone();
|
|
Ok(self.entry_bindings.clone())
|
|
})();
|
|
self.site_module = prev;
|
|
result
|
|
}
|
|
|
|
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
|
|
let prev = self.site_module;
|
|
self.site_module = Some(module as *const Module);
|
|
let result = (|| {
|
|
if let Some(main) = find_top(module, "main") {
|
|
return self.run_function(module, main, Env::with_metadata(module), &[], true);
|
|
}
|
|
// Document-as-entry: sole top-level `#` object with no params (e.g. `# Hello World`).
|
|
let entries: Vec<&Function> = module
|
|
.functions
|
|
.iter()
|
|
.filter(|f| f.is_object() && f.params.is_empty())
|
|
.collect();
|
|
if entries.len() == 1 {
|
|
return self.run_function(
|
|
module,
|
|
entries[0],
|
|
Env::with_metadata(module),
|
|
&[],
|
|
true,
|
|
);
|
|
}
|
|
// Web Artifact entry (ADR 0007): `type: web|endpoint` may be pure document —
|
|
// no `# main`. Return a Result-shaped summary for run/check gold paths.
|
|
if let Some(value) = crate::artifact::declaration_summary(module) {
|
|
return Ok(value);
|
|
}
|
|
bail!("no `# main` object to run");
|
|
})();
|
|
self.site_module = prev;
|
|
result
|
|
}
|
|
|
|
|
|
/// Pin `module` as site and call `lib.member` (isolated worker / CLI `--call-lib-path`).
|
|
pub fn run_site_lib_path(
|
|
&mut self,
|
|
module: &Module,
|
|
path: &str,
|
|
args: Option<&Value>,
|
|
) -> std::result::Result<Value, String> {
|
|
let prev = self.site_module;
|
|
self.site_module = Some(module as *const Module);
|
|
let out = self.call_site_lib_path(path, args);
|
|
self.site_module = prev;
|
|
out
|
|
}
|
|
|
|
/// Resolve `lib.member` on the site (entry) module — used by ABI `call_lib_path`.
|
|
pub(crate) fn call_site_lib_path(
|
|
&mut self,
|
|
path: &str,
|
|
args: Option<&Value>,
|
|
) -> std::result::Result<Value, String> {
|
|
let site = self
|
|
.site_module
|
|
.ok_or_else(|| "call_lib_path: no site module".to_string())?;
|
|
let site = unsafe { &*site };
|
|
let parts: Vec<String> = path
|
|
.split('.')
|
|
.map(|s| s.trim().to_string())
|
|
.filter(|s| !s.is_empty())
|
|
.collect();
|
|
if parts.len() < 2 {
|
|
return Err(format!(
|
|
"call_lib_path: need `lib.member`, got `{path}`"
|
|
));
|
|
}
|
|
let mut ev_args: Vec<EvArg> = Vec::new();
|
|
if let Some(Value::Map(pairs)) = args {
|
|
for (k, v) in pairs {
|
|
ev_args.push(EvArg::Named(k.clone(), v.clone()));
|
|
}
|
|
}
|
|
self.eval_path_call(site, &parts, &ev_args)
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
|
|
fn call_plugin_registered(
|
|
&mut self,
|
|
name: &str,
|
|
bound: &HashMap<String, Value>,
|
|
) -> std::result::Result<Value, String> {
|
|
struct HookData {
|
|
interp: *mut Interpreter,
|
|
}
|
|
fn trampoline(
|
|
data: *mut (),
|
|
path: &str,
|
|
args: Option<&Value>,
|
|
) -> std::result::Result<Value, String> {
|
|
let data = unsafe { &mut *(data as *mut HookData) };
|
|
let interp = unsafe { &mut *data.interp };
|
|
interp.call_site_lib_path(path, args)
|
|
}
|
|
let mut data = HookData {
|
|
interp: self as *mut Interpreter,
|
|
};
|
|
let hook = crate::host::plugin::LibPathCall {
|
|
call: trampoline,
|
|
data: &mut data as *mut HookData as *mut (),
|
|
};
|
|
crate::host::plugin::with_lib_path_call(hook, || {
|
|
crate::host::plugin::call_registered(&mut self.host, name, bound)
|
|
})
|
|
}
|
|
|
|
fn run_function(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
env: Env,
|
|
args: &[(String, Value)],
|
|
capture_entry_env: bool,
|
|
) -> Result<Value> {
|
|
self.in_function_source(module, fun, |this| {
|
|
this.run_function_inner(module, fun, env, args, capture_entry_env)
|
|
})
|
|
}
|
|
|
|
fn in_function_source<T>(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
run: impl FnOnce(&mut Self) -> Result<T>,
|
|
) -> Result<T> {
|
|
let mut source = module.source.clone();
|
|
if source.path.is_none() {
|
|
if self.diagnostic_frames.is_empty() {
|
|
source.path = self.path.clone();
|
|
} else if self.current_module == Some(module as *const Module) {
|
|
source.path = self.current_source.path.clone();
|
|
}
|
|
}
|
|
let caller = (!self.diagnostic_frames.is_empty()).then(|| self.current_source.at(self.current_span));
|
|
let previous_source = std::mem::replace(&mut self.current_source, source);
|
|
let previous_module = self.current_module.replace(module as *const Module);
|
|
let previous_span = std::mem::replace(&mut self.current_span, fun.span);
|
|
let previous_line = self.host.current_line;
|
|
self.diagnostic_frames.push(DiagnosticFrame {
|
|
function: fun.name.clone(), declaration: self.current_source.at(fun.span), call_site: caller,
|
|
});
|
|
let result = run(self)
|
|
.map_err(|error| {
|
|
if let Some(mut diagnostic) = Diagnostic::find(&error).cloned() {
|
|
if diagnostic.source_sha256.is_none() && diagnostic.path == self.current_source.path {
|
|
diagnostic.source_sha256 = self.current_source.sha256.clone();
|
|
}
|
|
if diagnostic.frames.is_empty() { diagnostic.frames = self.diagnostic_frames.clone(); }
|
|
diagnostic.into()
|
|
} else { self.err(error.to_string()) }
|
|
});
|
|
self.diagnostic_frames.pop();
|
|
self.current_source = previous_source;
|
|
self.current_module = previous_module;
|
|
self.current_span = previous_span;
|
|
self.host.current_line = previous_line;
|
|
result
|
|
}
|
|
|
|
fn run_function_inner(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
mut env: Env,
|
|
args: &[(String, Value)],
|
|
capture_entry_env: bool,
|
|
) -> Result<Value> {
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(fun.span),
|
|
"enter_fn",
|
|
&[("fn", fun.name.as_str())],
|
|
);
|
|
}
|
|
for (k, v) in args {
|
|
env.set(k.clone(), v.clone());
|
|
}
|
|
// Raw/named entry APIs and document metadata must use the same default
|
|
// semantics as ordinary calls. Already bound defaults are supplied
|
|
// values here and therefore never execute a second time.
|
|
let supplied=env.vars.iter().map(|(name,value)|EvArg::Named(name.clone(),value.clone())).collect::<Vec<_>>();
|
|
let completed=bind_function_args(self,module,fun,&mut env,&fun.params,&supplied,true)?;
|
|
for (name,value) in completed { env.set(name,value); }
|
|
for p in &fun.params {
|
|
if env.get(&p.name).is_none() {
|
|
env.set(p.name.clone(), Value::None);
|
|
}
|
|
}
|
|
|
|
if let Some(contract)=&fun.contract {
|
|
if let Some(diag)=crate::contract::call_arg_diag(contract,&fun.name,&env.vars,self.current_source.path.as_deref(),fun.span) {
|
|
return Err(diag.into());
|
|
}
|
|
}
|
|
let ret = Value::None;
|
|
self.push_view_call(fun, &env);
|
|
self.host.push_call_frame(&fun.name);
|
|
let body_result = (|| -> Result<Value> {
|
|
for stmt in &fun.body {
|
|
if let Some(v) = self.exec_stmt(module, fun, &mut env, stmt)? {
|
|
return Ok(v);
|
|
}
|
|
}
|
|
Ok(ret)
|
|
})();
|
|
self.host.pop_call_frame();
|
|
self.pop_view_call();
|
|
let ret = body_result?;
|
|
if capture_entry_env {
|
|
self.entry_bindings = env.vars_clone();
|
|
}
|
|
if self.trace {
|
|
let display = ret.as_display();
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(fun.span),
|
|
"leave_fn",
|
|
&[("fn", fun.name.as_str()), ("value", display.as_str())],
|
|
);
|
|
}
|
|
Ok(ret)
|
|
}
|
|
|
|
fn exec_stmt(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
env: &mut Env,
|
|
stmt: &Stmt,
|
|
) -> Result<Option<Value>> {
|
|
let span = stmt_span(stmt);
|
|
self.current_span = span;
|
|
self.host.current_line = span.line;
|
|
if let Some(dbg) = &self.debug {
|
|
dbg.on_stmt(span.line, &fun.name, &env.vars, &self.captured_stdout)
|
|
.map_err(|m| self.err(m))?;
|
|
}
|
|
match stmt {
|
|
Stmt::Assign { name, value, span, .. } => {
|
|
self.current_span = *span;
|
|
let v = self.eval_expr(module, fun, env, value)?;
|
|
// 契约边界 3(T2.2):表绑定 vs 字段契约。
|
|
if let Some(c) = fun.var_contracts.get(name) {
|
|
if let Some(d) =
|
|
crate::contract::fields_diag(c, name, &v, self.current_source.path.as_deref(), *span)
|
|
{
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
if self.trace {
|
|
let display = v.as_display();
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[
|
|
("kind", "assign"),
|
|
("name", name.as_str()),
|
|
("value", display.as_str()),
|
|
],
|
|
);
|
|
}
|
|
if self.capture {
|
|
self.record_stmt_event(StmtEvent {
|
|
line: span.line,
|
|
kind: StmtEventKind::Assign,
|
|
name: Some(name.clone()),
|
|
value_after: Some(v.as_display()),
|
|
arm_index: None,
|
|
iter: None,
|
|
call_id: self.current_call_id(),
|
|
loop_id: None,
|
|
});
|
|
}
|
|
env.set(name.clone(), v);
|
|
Ok(None)
|
|
}
|
|
Stmt::Return { value, span } => {
|
|
self.current_span = *span;
|
|
let v = self.eval_expr(module, fun, env, value)?;
|
|
// 契约边界 2(T2.2):返回值 vs 返回契约。
|
|
if let Some(c) = &fun.contract {
|
|
if let Some(d) =
|
|
crate::contract::return_diag(c, &fun.name, &v, self.current_source.path.as_deref(), *span)
|
|
{
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
if self.trace {
|
|
let display = v.as_display();
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[("kind", "return"), ("value", display.as_str())],
|
|
);
|
|
}
|
|
if self.capture {
|
|
self.record_stmt_event(StmtEvent {
|
|
line: span.line,
|
|
kind: StmtEventKind::Return,
|
|
name: None,
|
|
value_after: Some(v.as_display()),
|
|
arm_index: None,
|
|
iter: None,
|
|
call_id: self.current_call_id(),
|
|
loop_id: None,
|
|
});
|
|
}
|
|
Ok(Some(v))
|
|
}
|
|
Stmt::Call { call, span } => {
|
|
self.current_span = *span;
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[("kind", "call"), ("callee", call.callee.as_str())],
|
|
);
|
|
}
|
|
let stdout_before = self.captured_stdout.len();
|
|
let v = self.eval_call(module, fun, env, call)?;
|
|
if self.capture {
|
|
let (loop_id, iter) = self.loop_ctx();
|
|
self.record_stmt_event(StmtEvent {
|
|
line: span.line,
|
|
kind: StmtEventKind::Call,
|
|
name: Some(call.callee.clone()),
|
|
value_after: Some(call_event_brief(
|
|
&v,
|
|
&self.captured_stdout,
|
|
stdout_before,
|
|
&call.callee,
|
|
)),
|
|
arm_index: None,
|
|
iter,
|
|
call_id: self.current_call_id(),
|
|
loop_id,
|
|
});
|
|
}
|
|
Ok(None)
|
|
}
|
|
Stmt::Expr { value, span } => {
|
|
self.current_span = *span;
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[("kind", "expr")],
|
|
);
|
|
}
|
|
let stdout_before = self.captured_stdout.len();
|
|
let v = self.eval_expr(module, fun, env, value)?;
|
|
if self.capture {
|
|
let (loop_id, iter) = self.loop_ctx();
|
|
let name = match value {
|
|
Expr::Call(c) => Some(c.callee.clone()),
|
|
_ => None,
|
|
};
|
|
self.record_stmt_event(StmtEvent {
|
|
line: span.line,
|
|
kind: StmtEventKind::Call,
|
|
name: name.clone(),
|
|
value_after: Some(call_event_brief(
|
|
&v,
|
|
&self.captured_stdout,
|
|
stdout_before,
|
|
name.as_deref().unwrap_or("expr"),
|
|
)),
|
|
arm_index: None,
|
|
iter,
|
|
call_id: self.current_call_id(),
|
|
loop_id,
|
|
});
|
|
}
|
|
Ok(None)
|
|
}
|
|
Stmt::Branch { arms, span } => {
|
|
self.current_span = *span;
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[("kind", "branch")],
|
|
);
|
|
}
|
|
for (arm_index, arm) in arms.iter().enumerate() {
|
|
let take = match &arm.condition {
|
|
None => true,
|
|
Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(),
|
|
};
|
|
if take {
|
|
if self.capture {
|
|
self.record_branch_hit(span.line, arm_index);
|
|
}
|
|
for s in &arm.body {
|
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
|
return Ok(Some(v));
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
Stmt::While {
|
|
condition,
|
|
body,
|
|
span,
|
|
} => {
|
|
self.current_span = *span;
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[("kind", "while")],
|
|
);
|
|
}
|
|
let loop_id = if self.capture {
|
|
Some(self.begin_view_loop(span.line, None, None))
|
|
} else {
|
|
None
|
|
};
|
|
let mut guard = 0u32;
|
|
loop {
|
|
self.current_span=*span;
|
|
self.host.current_line=span.line;
|
|
if !self.eval_expr(module,fun,env,condition)?.truthy(){break;}
|
|
guard += 1;
|
|
if guard > 1_000_000 {
|
|
return Err(self.err("while loop exceeded iteration limit"));
|
|
}
|
|
if let Some(lid) = loop_id {
|
|
self.enter_loop_iter(lid, guard - 1, &format!("iter {guard}"));
|
|
}
|
|
for s in body {
|
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
|
if self.capture {
|
|
if let Some(lid) = loop_id {
|
|
self.end_view_loop(lid);
|
|
}
|
|
self.record_loop_hit(span.line, guard, None);
|
|
}
|
|
return Ok(Some(v));
|
|
}
|
|
}
|
|
}
|
|
if self.capture {
|
|
if let Some(lid) = loop_id {
|
|
self.end_view_loop(lid);
|
|
}
|
|
self.record_loop_hit(span.line, guard, None);
|
|
}
|
|
Ok(None)
|
|
}
|
|
Stmt::ForEach {
|
|
item,
|
|
collection,
|
|
label: _,
|
|
body,
|
|
span,
|
|
} => {
|
|
self.current_span = *span;
|
|
if self.trace {
|
|
emit_trace(
|
|
self.current_source.path.as_deref(),
|
|
Some(*span),
|
|
"stmt",
|
|
&[
|
|
("kind", "foreach"),
|
|
("item", item.as_str()),
|
|
("collection", collection.as_str()),
|
|
],
|
|
);
|
|
}
|
|
let coll = env.get(collection).cloned().ok_or_else(|| {
|
|
self.err(format!("undefined collection `{collection}`"))
|
|
})?;
|
|
let items = match builtin_iter_items(&coll) {
|
|
Ok(Value::List(xs)) => xs,
|
|
Ok(_) => unreachable!(),
|
|
Err(m) => return Err(self.err(m)),
|
|
};
|
|
let loop_id = if self.capture {
|
|
Some(self.begin_view_loop(
|
|
span.line,
|
|
Some(item.as_str()),
|
|
Some(collection.as_str()),
|
|
))
|
|
} else {
|
|
None
|
|
};
|
|
let mut iterations = 0u32;
|
|
let mut last_item: Option<String> = None;
|
|
for val in items {
|
|
let index = iterations;
|
|
iterations += 1;
|
|
let display = val.as_display();
|
|
last_item = Some(display.clone());
|
|
if let Some(lid) = loop_id {
|
|
self.enter_loop_iter(lid, index, &display);
|
|
self.record_stmt_event(StmtEvent {
|
|
line: span.line,
|
|
kind: StmtEventKind::BindRef,
|
|
name: Some(item.clone()),
|
|
value_after: Some(format!(
|
|
"{collection}[{index}]={display}"
|
|
)),
|
|
arm_index: None,
|
|
iter: Some(index),
|
|
call_id: self.current_call_id(),
|
|
loop_id: Some(lid),
|
|
});
|
|
}
|
|
env.set(item.clone(), val);
|
|
for s in body {
|
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
|
if self.capture {
|
|
if let Some(lid) = loop_id {
|
|
self.end_view_loop(lid);
|
|
}
|
|
self.record_loop_hit(span.line, iterations, last_item.clone());
|
|
}
|
|
return Ok(Some(v));
|
|
}
|
|
}
|
|
}
|
|
if self.capture {
|
|
if let Some(lid) = loop_id {
|
|
self.end_view_loop(lid);
|
|
}
|
|
self.record_loop_hit(span.line, iterations, last_item);
|
|
}
|
|
Ok(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn resolve_index_key(
|
|
&mut self,
|
|
_module: &Module,
|
|
_fun: &Function,
|
|
env: &mut Env,
|
|
label: &IndexKey,
|
|
) -> Result<String> {
|
|
match label {
|
|
IndexKey::Lit(s) => Ok(s.clone()),
|
|
IndexKey::Var(name) => {
|
|
let v = env.get(name).cloned().ok_or_else(|| {
|
|
self.err(format!("undefined variable `{name}` in footnote key"))
|
|
})?;
|
|
Ok(v.as_display())
|
|
}
|
|
}
|
|
}
|
|
|
|
fn eval_expr(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
env: &mut Env,
|
|
expr: &Expr,
|
|
) -> Result<Value> {
|
|
match expr {
|
|
Expr::Literal(lit) => Ok(lit_to_value(lit)),
|
|
Expr::Var(name) => env
|
|
.get(name)
|
|
.cloned()
|
|
.ok_or_else(|| self.err(format!("undefined variable `{name}`"))),
|
|
Expr::Interp(parts) => {
|
|
let mut s = String::new();
|
|
for part in parts {
|
|
match part {
|
|
InterpPart::Lit(t) => s.push_str(t),
|
|
InterpPart::Var(n) => {
|
|
let v = env
|
|
.get(n)
|
|
.ok_or_else(|| self.err(format!("undefined variable `{n}`")))?;
|
|
s.push_str(&v.as_display());
|
|
}
|
|
InterpPart::Index { base, labels } => {
|
|
let mut v = env.get(base).cloned().ok_or_else(|| {
|
|
self.err(format!("undefined variable `{base}`"))
|
|
})?;
|
|
for label in labels {
|
|
v = builtin_footnote_get(&v, label).map_err(|m| self.err(m))?;
|
|
}
|
|
s.push_str(&v.as_display());
|
|
}
|
|
}
|
|
}
|
|
Ok(Value::Text(s))
|
|
}
|
|
Expr::Unary { op, expr } => {
|
|
let value=self.eval_expr(module,fun,env,expr)?;
|
|
crate::builtin::eval_unary(*op,&value).map_err(|message|self.err(message))
|
|
}
|
|
Expr::Binary { op, left, right } => {
|
|
let l = self.eval_expr(module, fun, env, left)?;
|
|
match op {
|
|
BinaryOp::And => {
|
|
if !l.truthy() {
|
|
return Ok(Value::Bool(false));
|
|
}
|
|
let r = self.eval_expr(module, fun, env, right)?;
|
|
return Ok(Value::Bool(r.truthy()));
|
|
}
|
|
BinaryOp::Or => {
|
|
if l.truthy() {
|
|
return Ok(Value::Bool(true));
|
|
}
|
|
let r = self.eval_expr(module, fun, env, right)?;
|
|
return Ok(Value::Bool(r.truthy()));
|
|
}
|
|
_ => {}
|
|
}
|
|
let r = self.eval_expr(module, fun, env, right)?;
|
|
if let Some(v) = crate::linalg_ops::try_matrix_binary(
|
|
&mut self.host,
|
|
*op,
|
|
&l,
|
|
&r,
|
|
)
|
|
.map_err(|e| self.err(e))?
|
|
{
|
|
return Ok(v);
|
|
}
|
|
crate::builtin::eval_binary(*op, &l, &r).map_err(|e| self.err(e.to_string()))
|
|
}
|
|
Expr::Call(call) => self.eval_call(module, fun, env, call),
|
|
Expr::List(items) => {
|
|
let mut out = Vec::new();
|
|
for it in items {
|
|
out.push(self.eval_expr(module, fun, env, it)?);
|
|
}
|
|
Ok(Value::List(out))
|
|
}
|
|
Expr::Map(pairs) => {
|
|
let mut out = Vec::new();
|
|
for (k, e) in pairs {
|
|
out.push((k.clone(), self.eval_expr(module, fun, env, e)?));
|
|
}
|
|
Ok(Value::Map(out))
|
|
}
|
|
Expr::Index { base, label } => {
|
|
let v = self.eval_expr(module, fun, env, base)?;
|
|
let key = self.resolve_index_key(module, fun, env, label)?;
|
|
// 契约边界 4(T2.2):字段访问 vs 字段契约——键存在性**先于**取值
|
|
// (契约诊断优先于运行时 `missing map key`)。
|
|
if let Expr::Var(name) = base.as_ref() {
|
|
if let Some(c) = fun.var_contracts.get(name) {
|
|
if let Some(d) = crate::contract::index_diag(
|
|
c,
|
|
name,
|
|
&key,
|
|
&Value::None,
|
|
self.current_source.path.as_deref(),
|
|
self.current_span,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
}
|
|
let out = builtin_footnote_get(&v, &key).map_err(|m| self.err(m))?;
|
|
if let Expr::Var(name) = base.as_ref() {
|
|
if let Some(c) = fun.var_contracts.get(name) {
|
|
if let Some(d) = crate::contract::index_diag(
|
|
c,
|
|
name,
|
|
&key,
|
|
&out,
|
|
self.current_source.path.as_deref(),
|
|
self.current_span,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
Expr::Formula(e) => Ok(Value::Formula(e.clone())),
|
|
Expr::Code(c) => Ok(Value::Code(c.clone())),
|
|
// `<TAB>` M2: the label is inert prose; only the payload evaluates.
|
|
Expr::Occluded { payload, .. } => match payload {
|
|
Some(inner) => self.eval_expr(module, fun, env, inner),
|
|
None => Ok(Value::None),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn eval_call(
|
|
&mut self,
|
|
module: &Module,
|
|
fun: &Function,
|
|
env: &mut Env,
|
|
call: &CallExpr,
|
|
) -> Result<Value> {
|
|
let mut call = call.clone();
|
|
// Method callees keep author names (`绘图` on quantum ≠ math `host_plot`).
|
|
if call.path.is_none() && call.receiver.is_none() {
|
|
let callee = crate::aliases::normalize_call_callee_and_args(
|
|
&call.callee,
|
|
&mut call.args,
|
|
);
|
|
call.callee = callee;
|
|
}
|
|
|
|
for m in &call.pre_modifiers {
|
|
if call.args.iter().any(|a| matches!(a, Arg::Named { name, .. } if name == m)) {
|
|
return Err(self.err(format!(
|
|
"pre-bracket modifier `{m}` conflicts with named argument `{m}`"
|
|
)));
|
|
}
|
|
}
|
|
|
|
let mut ev_args = Vec::new();
|
|
for m in &call.pre_modifiers {
|
|
ev_args.push(EvArg::Named(m.clone(), Value::Bool(true)));
|
|
}
|
|
for arg in &call.args {
|
|
match arg {
|
|
Arg::Positional(e) => {
|
|
ev_args.push(EvArg::Positional(self.eval_expr(module, fun, env, e)?));
|
|
}
|
|
Arg::Named { name, value } => {
|
|
ev_args.push(EvArg::Named(
|
|
name.clone(),
|
|
self.eval_expr(module, fun, env, value)?,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
if let Some(recv_name) = &call.receiver {
|
|
return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args);
|
|
}
|
|
|
|
// Local-var method sugar (`a.b` when `a` is in env) before BoundCall path resolve.
|
|
if let Some(path) = &call.path {
|
|
if path.len() == 2
|
|
&& env.get(&path[0]).is_some()
|
|
&& !module.import_modules.contains_key(&path[0])
|
|
{
|
|
let recv = path[0].clone();
|
|
let method = path[1].clone();
|
|
return self.eval_method_call(module, fun, env, &recv, &method, &ev_args);
|
|
}
|
|
}
|
|
|
|
use crate::sema::bind::{resolve_for_exec, DynamicReason, ExecTarget};
|
|
match resolve_for_exec(module, fun, &call) {
|
|
ExecTarget::Local(target) => {
|
|
self.eval_bound_function_call(module, fun, env, target, &ev_args)
|
|
}
|
|
ExecTarget::Import {
|
|
lib: lib_mod,
|
|
fun: target,
|
|
..
|
|
} => self.eval_bound_function_call(lib_mod, fun, env, target, &ev_args),
|
|
ExecTarget::Builtin(name) => self.eval_builtin_call(name, &ev_args),
|
|
ExecTarget::Host(hf) => {
|
|
let mut params: Vec<String> =
|
|
hf.required_params().iter().map(|s| (*s).to_string()).collect();
|
|
for p in hf.optional_params() {
|
|
params.push((*p).to_string());
|
|
}
|
|
let bound = bind_args(¶ms, &ev_args, true).map_err(|m| self.err(m))?;
|
|
for req in hf.required_params() {
|
|
if !bound.contains_key(*req) {
|
|
return Err(self.err(format!("{} requires `{req}`", hf.name())));
|
|
}
|
|
}
|
|
call_host(&mut self.host, hf, &bound).map_err(|m| self.err(m))
|
|
}
|
|
ExecTarget::Dynamic {
|
|
reason: DynamicReason::CallFn,
|
|
..
|
|
} => {
|
|
let bound = bind_args(&["name".into()], &ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let name = match bound.get("name") {
|
|
Some(Value::Text(s)) => s.as_str(),
|
|
_ => return Err(self.err("call_fn requires text name")),
|
|
};
|
|
let target = lookup_function(module, fun, name).ok_or_else(|| {
|
|
self.err(format!("call_fn: unknown function `{name}`"))
|
|
})?;
|
|
if !target.params.is_empty() {
|
|
return Err(self.err(format!(
|
|
"call_fn: `{name}` must have no parameters"
|
|
)));
|
|
}
|
|
self.run_function(module, target, Env::new(), &[], false)
|
|
}
|
|
ExecTarget::Dynamic {
|
|
reason: DynamicReason::Plugin,
|
|
name,
|
|
} => {
|
|
if let Some(reg) = self.host.plugins.get(&name).cloned() {
|
|
let bound =
|
|
bind_args(®.params, &ev_args, false).map_err(|m| self.err(m))?;
|
|
return self
|
|
.call_plugin_registered(&name, &bound)
|
|
.map_err(|m| self.err(m));
|
|
}
|
|
Err(self.err(format!("unknown function `{name}`")))
|
|
}
|
|
ExecTarget::Dynamic {
|
|
reason: DynamicReason::MethodReceiver,
|
|
name,
|
|
} => {
|
|
if let Some(path) = &call.path {
|
|
if path.len() == 2 && env.get(&path[0]).is_some() {
|
|
return self.eval_method_call(
|
|
module,
|
|
fun,
|
|
env,
|
|
&path[0],
|
|
&path[1],
|
|
&ev_args,
|
|
);
|
|
}
|
|
}
|
|
Err(self.err(format!("unresolved dynamic call `{name}`")))
|
|
}
|
|
ExecTarget::Unresolved { message, .. } => Err(self.err(message)),
|
|
}
|
|
}
|
|
|
|
/// Invoke a function already resolved via [`crate::sema::bind::resolve_for_exec`].
|
|
fn eval_bound_function_call(
|
|
&mut self,
|
|
module: &Module,
|
|
_caller: &Function,
|
|
_env: &mut Env,
|
|
target: &Function,
|
|
ev_args: &[EvArg],
|
|
) -> Result<Value> {
|
|
let bound =
|
|
bind_function_args(self, module, target, &mut Env::new(), &target.params, ev_args, false)
|
|
.map_err(|e| self.argument_error(e))?;
|
|
if let Some(c) = &target.contract {
|
|
if let Some(d) = crate::contract::call_arg_diag_in(
|
|
c,
|
|
&target.name,
|
|
&bound,
|
|
&self.current_source.at(self.current_span),
|
|
&module.source,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
let mut call_env = Env::new();
|
|
for (k, v) in bound {
|
|
call_env.set(k, v);
|
|
}
|
|
self.host.push_call_site_line(self.host.current_line);
|
|
let result = self.run_function(module, target, call_env, &[], false);
|
|
self.host.pop_call_site_line();
|
|
let result = result?;
|
|
if target.is_object() {
|
|
Ok(crate::value::tag_instance(&target.name, &self.object_module_path(module), result))
|
|
} else {
|
|
Ok(result)
|
|
}
|
|
}
|
|
|
|
fn eval_builtin_call(&mut self, name: &str, ev_args: &[EvArg]) -> Result<Value> {
|
|
match name {
|
|
"print" => {
|
|
let bound = bind_args(&["text".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let text = bound
|
|
.get("text")
|
|
.map(|v| v.as_display())
|
|
.ok_or_else(|| self.err("print requires text (named or positional)"))?;
|
|
self.emit_line(&text);
|
|
Ok(Value::None)
|
|
}
|
|
"input" => {
|
|
let bound = bind_args(&["prompt".into()], ev_args, true)
|
|
.map_err(|m| self.err(m))?;
|
|
let prompt = bound
|
|
.get("prompt")
|
|
.map(|v| v.as_display())
|
|
.unwrap_or_default();
|
|
let line = if self.capture {
|
|
self.emit_prompt(&prompt);
|
|
self.input.read_line()
|
|
} else if crate::input_feed::stdin_is_tty() {
|
|
self.input
|
|
.read_line_with_prompt(&prompt)
|
|
.map(|(line, _)| line)
|
|
} else {
|
|
self.emit_prompt(&prompt);
|
|
self.input.read_line()
|
|
}
|
|
.map_err(|e| {
|
|
let msg = e.to_string();
|
|
if msg.contains("input needs a line") {
|
|
self.err(msg)
|
|
} else {
|
|
e
|
|
}
|
|
})?;
|
|
Ok(Value::Text(line))
|
|
}
|
|
"len" => {
|
|
let bound = bind_args(&["value".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let v = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("len requires value"))?;
|
|
let n = builtin_len(v).map_err(|m| self.err(m))?;
|
|
Ok(Value::Int(n))
|
|
}
|
|
"str" => {
|
|
let bound = bind_args(&["value".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let v = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("str requires value"))?;
|
|
Ok(builtin_str(v))
|
|
}
|
|
"int" => {
|
|
let bound = bind_args(&["value".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let v = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("int requires value"))?;
|
|
let n = builtin_int(v).map_err(|m| self.err(m))?;
|
|
Ok(Value::Int(n))
|
|
}
|
|
"type" => {
|
|
let bound = bind_args(&["value".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let v = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("type requires value"))?;
|
|
Ok(builtin_type(v))
|
|
}
|
|
"trim" => {
|
|
let bound = bind_args(&["value".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let v = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("trim requires value"))?;
|
|
builtin_trim(v).map_err(|m| self.err(m))
|
|
}
|
|
"split" => {
|
|
let bound = bind_args(&["value".into(), "sep".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let value = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("split requires value"))?;
|
|
let sep = bound
|
|
.get("sep")
|
|
.ok_or_else(|| self.err("split requires sep"))?;
|
|
builtin_split(value, sep).map_err(|m| self.err(m))
|
|
}
|
|
"join" => {
|
|
let bound = bind_args(&["value".into(), "sep".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let value = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("join requires value"))?;
|
|
let sep = bound
|
|
.get("sep")
|
|
.ok_or_else(|| self.err("join requires sep"))?;
|
|
builtin_join(value, sep).map_err(|m| self.err(m))
|
|
}
|
|
"at" => {
|
|
let bound = bind_args(&["value".into(), "index".into()], ev_args, false)
|
|
.map_err(|m| self.err(m))?;
|
|
let value = bound
|
|
.get("value")
|
|
.ok_or_else(|| self.err("at requires value"))?;
|
|
let index = bound
|
|
.get("index")
|
|
.ok_or_else(|| self.err("at requires index"))?;
|
|
builtin_at(value, index).map_err(|m| self.err(m))
|
|
}
|
|
other => Err(self.err(format!("unknown builtin `{other}`"))),
|
|
}
|
|
}
|
|
|
|
/// Resolve bare path `lib.member` / `lib.Type.member` (definition-tree addressing).
|
|
pub(crate) fn eval_path_call(
|
|
&mut self,
|
|
module: &Module,
|
|
path: &[String],
|
|
ev_args: &[EvArg],
|
|
) -> Result<Value> {
|
|
let (lib, node) = locate_import_function(module, path).map_err(|m| self.err(m))?;
|
|
|
|
let bound = {
|
|
let mut dummy_env = Env::new();
|
|
bind_function_args(
|
|
self,
|
|
lib,
|
|
node,
|
|
&mut dummy_env,
|
|
&node.params,
|
|
ev_args,
|
|
false,
|
|
)
|
|
.map_err(|e| self.argument_error(e))?
|
|
};
|
|
// 契约边界 1(T2.2):库路径调用的实参 vs 形参契约。
|
|
if let Some(c) = &node.contract {
|
|
if let Some(d) = crate::contract::call_arg_diag_in(
|
|
c,
|
|
&node.name,
|
|
&bound,
|
|
&self.current_source.at(self.current_span),
|
|
&lib.source,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
let mut call_env = Env::new();
|
|
for (k, v) in bound {
|
|
call_env.set(k, v);
|
|
}
|
|
|
|
self.host.push_call_site_line(self.host.current_line);
|
|
let result = self.run_function(lib, node, call_env, &[], false);
|
|
self.host.pop_call_site_line();
|
|
let result = result?;
|
|
if node.is_object() {
|
|
Ok(crate::value::tag_instance(&node.name, &self.object_module_path(lib), result))
|
|
} else {
|
|
Ok(result)
|
|
}
|
|
}
|
|
|
|
fn eval_method_call(
|
|
&mut self,
|
|
module: &Module,
|
|
_fun: &Function,
|
|
env: &mut Env,
|
|
recv_name: &str,
|
|
method: &str,
|
|
ev_args: &[EvArg],
|
|
) -> Result<Value> {
|
|
let recv = env
|
|
.get(recv_name)
|
|
.cloned()
|
|
.ok_or_else(|| self.err(format!("undefined variable `{recv_name}`")))?;
|
|
let type_name = instance_type_name(&recv).map_err(|m| self.err(m))?;
|
|
// The active root is immutable for this invocation; site_module is
|
|
// installed/restored by the public run/call entry points.
|
|
let root=unsafe { self.site_module.map(|root| &*root) }.unwrap_or(module);
|
|
let namespace=crate::value::instance_module(&recv).map_err(|m|self.err(m))?;
|
|
let (class_owner,class)=if let Some(namespace)=namespace {
|
|
crate::inherit::object_at_namespace(root,&namespace,&type_name)
|
|
.ok_or_else(||self.err(format!("unknown object type `{type_name}` in module `{}`",namespace.join("."))))?
|
|
} else {
|
|
crate::inherit::resolve_object(module,&type_name).map_err(|m|self.err(m))?
|
|
};
|
|
let (owner, _obj, target) = find_method_along_bases(class_owner, class, method)
|
|
.ok_or_else(|| {
|
|
let chain = crate::inherit::inheritance_chain(class_owner, &type_name)
|
|
.into_iter()
|
|
.map(|o| o.name.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join(" → ");
|
|
self.err(format!(
|
|
"unknown method `{type_name}.{method}` (searched {chain})"
|
|
))
|
|
})?;
|
|
let mut receiver_env = Env::new();
|
|
receiver_env.set("self".into(), recv.clone());
|
|
receiver_env.set("自".into(), recv.clone());
|
|
let bound = bind_function_args(self, owner, target, &mut receiver_env, &target.params, ev_args, false)
|
|
.map_err(|e| self.argument_error(e))?;
|
|
// 契约边界 1(T2.2):方法调用的实参 vs 形参契约。
|
|
if let Some(c) = &target.contract {
|
|
if let Some(d) = crate::contract::call_arg_diag_in(
|
|
c,
|
|
&target.name,
|
|
&bound,
|
|
&self.current_source.at(self.current_span),
|
|
&owner.source,
|
|
) {
|
|
return Err(d.into());
|
|
}
|
|
}
|
|
let mut call_env = Env::new();
|
|
for (k, v) in bound {
|
|
call_env.set(k, v);
|
|
}
|
|
call_env.set("自".into(), recv.clone());
|
|
call_env.set("self".into(), recv.clone());
|
|
self.host.push_call_site_line(self.host.current_line);
|
|
let result = self.run_function(owner, target, call_env, &[], false);
|
|
self.host.pop_call_site_line();
|
|
let result = result?;
|
|
if crate::linalg_ops::is_matrix_value(&recv) {
|
|
Ok(crate::value::preserve_instance_module(&recv,crate::linalg_ops::retag_matrix_like(&type_name, result)))
|
|
} else {
|
|
Ok(result)
|
|
}
|
|
}
|
|
|
|
fn object_module_path(&self, module:&Module) -> Vec<String> {
|
|
let root=unsafe { self.site_module.map(|root| &*root) }.unwrap_or(module);
|
|
crate::inherit::module_namespace(root,module).unwrap_or_default()
|
|
}
|
|
}
|
|
|
|
fn instance_type_name(v: &Value) -> std::result::Result<String, String> {
|
|
match v {
|
|
Value::Map(entries) => entries
|
|
.iter()
|
|
.find(|(k, _)| k == "_type")
|
|
.and_then(|(_, v)| match v {
|
|
Value::Text(s) => Some(s.clone()),
|
|
_ => None,
|
|
})
|
|
.ok_or_else(|| "method receiver needs a map with `_type`".into()),
|
|
_ => Err("method receiver must be an object map".into()),
|
|
}
|
|
}
|
|
|
|
/// `lib.member` / `lib.Type.member` against frontmatter imports. Does not execute.
|
|
pub(crate) fn locate_import_function<'a>(
|
|
module: &'a Module,
|
|
path: &[String],
|
|
) -> Result<(&'a Module, &'a Function), String> {
|
|
let display = path.join(".");
|
|
if path.len() < 2 {
|
|
return Err(format!(
|
|
"library path `{display}`: need at least `lib.member`"
|
|
));
|
|
}
|
|
let lib = module
|
|
.import_modules
|
|
.get(&path[0])
|
|
.ok_or_else(|| format!("unknown library `{}` (import it in frontmatter)", path[0]))?;
|
|
let mut parent_is_object = false;
|
|
let mut node = lib
|
|
.functions
|
|
.iter()
|
|
.find(|f| f.name == path[1])
|
|
.ok_or_else(|| format!("unknown `{display}`"))?;
|
|
for seg in &path[2..] {
|
|
parent_is_object = node.is_object();
|
|
node = node
|
|
.children
|
|
.iter()
|
|
.find(|c| c.name == *seg)
|
|
.ok_or_else(|| format!("unknown `{display}`"))?;
|
|
}
|
|
if parent_is_object && !node.is_object() && crate::ast::function_uses_receiver(node) {
|
|
return Err(format!(
|
|
"`{display}` is an instance method; call it as `var`.{}",
|
|
node.name
|
|
));
|
|
}
|
|
Ok((lib, node))
|
|
}
|
|
|
|
/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path).
|
|
fn bind_function_args(
|
|
interp: &mut Interpreter,
|
|
module: &Module,
|
|
target: &Function,
|
|
initial_env: &mut Env,
|
|
params: &[Param],
|
|
args: &[EvArg],
|
|
allow_missing: bool,
|
|
) -> Result<HashMap<String, Value>> {
|
|
let mut named: HashMap<String, Value> = HashMap::new();
|
|
let mut positionals = Vec::new();
|
|
for a in args {
|
|
match a {
|
|
EvArg::Positional(v) => positionals.push(v.clone()),
|
|
EvArg::Named(k, v) => {
|
|
if named.contains_key(k) {
|
|
return Err(anyhow::anyhow!("duplicate named argument `{k}`"));
|
|
}
|
|
named.insert(k.clone(), v.clone());
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut out: HashMap<String, Value> = HashMap::new();
|
|
let mut used_named = HashSet::new();
|
|
let mut pos_i = 0usize;
|
|
let mut defaults_env = Env::new();
|
|
// Only an explicit receiver crosses into a method's default environment.
|
|
for name in ["self", "自"] {
|
|
if let Some(value) = initial_env.get(name) {
|
|
defaults_env.set(name.into(), value.clone());
|
|
}
|
|
}
|
|
|
|
for p in params {
|
|
if let Some(v) = named.get(&p.name) {
|
|
out.insert(p.name.clone(), v.clone());
|
|
used_named.insert(p.name.clone());
|
|
} else if pos_i < positionals.len() {
|
|
out.insert(p.name.clone(), positionals[pos_i].clone());
|
|
pos_i += 1;
|
|
} else if p.default.is_none() && !allow_missing {
|
|
return Err(anyhow::anyhow!("missing argument for parameter `{}`", p.name));
|
|
}
|
|
}
|
|
if pos_i < positionals.len() {
|
|
return Err(anyhow::anyhow!("too many positional arguments ({} extra)", positionals.len() - pos_i));
|
|
}
|
|
for (k, v) in named {
|
|
if !used_named.contains(&k) && !out.contains_key(&k) { out.insert(k, v); }
|
|
}
|
|
for (name, value) in &out { defaults_env.set(name.clone(), value.clone()); }
|
|
for name in ["self", "自"] {
|
|
if let Some(value)=initial_env.get(name) { defaults_env.set(name.into(),value.clone()); }
|
|
}
|
|
for p in params {
|
|
if out.contains_key(&p.name) { continue; }
|
|
if let Some(def) = &p.default {
|
|
let mut evaluate=|this:&mut Interpreter| {
|
|
let previous_span=this.current_span;
|
|
let previous_line=this.host.current_line;
|
|
this.current_span=p.span;
|
|
this.host.current_line=p.span.line;
|
|
let result=this.eval_expr(module,target,&mut defaults_env,def);
|
|
this.current_span=previous_span;
|
|
this.host.current_line=previous_line;
|
|
result
|
|
};
|
|
let v = if interp.current_module == Some(module as *const Module)
|
|
&& interp.diagnostic_frames.last().is_some_and(|frame| frame.declaration.span == target.span)
|
|
{
|
|
evaluate(interp)?
|
|
} else {
|
|
interp.in_function_source(module, target, evaluate)?
|
|
};
|
|
out.insert(p.name.clone(), v);
|
|
}
|
|
if let Some(value) = out.get(&p.name) {
|
|
defaults_env.set(p.name.clone(), value.clone());
|
|
}
|
|
}
|
|
|
|
Ok(out)
|
|
}
|
|
|
|
/// Bind evaluated args onto parameter names (host / plugin functions).
|
|
fn bind_args(
|
|
params: &[String],
|
|
args: &[EvArg],
|
|
allow_missing: bool,
|
|
) -> std::result::Result<HashMap<String, Value>, String> {
|
|
let names=args.iter().map(|a|match a{EvArg::Positional(_)=>None,EvArg::Named(name,_)=>Some(name.clone())}).collect::<Vec<_>>();
|
|
let values=args.iter().map(|a|match a{EvArg::Positional(value)|EvArg::Named(_,value)=>value.clone()}).collect::<Vec<_>>();
|
|
crate::arguments::bind(params,&names,&values,allow_missing)
|
|
}
|
|
|
|
fn collect_decl_reads(expr: &Expr, out: &mut std::collections::HashSet<String>) {
|
|
match expr {
|
|
Expr::Occluded { payload, .. } => {
|
|
if let Some(inner) = payload {
|
|
collect_decl_reads(inner, out);
|
|
}
|
|
}
|
|
Expr::Var(name) => {
|
|
out.insert(name.clone());
|
|
}
|
|
Expr::Interp(parts) => {
|
|
for part in parts {
|
|
match part {
|
|
InterpPart::Var(name) => {
|
|
out.insert(name.clone());
|
|
}
|
|
InterpPart::Index { base, .. } => {
|
|
out.insert(base.clone());
|
|
}
|
|
InterpPart::Lit(_) => {}
|
|
}
|
|
}
|
|
}
|
|
Expr::Index { base, label } => {
|
|
collect_decl_reads(base, out);
|
|
if let IndexKey::Var(name) = label {
|
|
out.insert(name.clone());
|
|
}
|
|
}
|
|
Expr::Binary { left, right, .. } => {
|
|
collect_decl_reads(left, out);
|
|
collect_decl_reads(right, out);
|
|
}
|
|
Expr::Unary { expr, .. } => collect_decl_reads(expr, out),
|
|
Expr::List(xs) => {
|
|
for x in xs {
|
|
collect_decl_reads(x, out);
|
|
}
|
|
}
|
|
Expr::Map(entries) => {
|
|
for (_, v) in entries {
|
|
collect_decl_reads(v, out);
|
|
}
|
|
}
|
|
Expr::Call(call) => {
|
|
if let Some(receiver) = &call.receiver {
|
|
out.insert(receiver.clone());
|
|
}
|
|
for arg in &call.args {
|
|
match arg {
|
|
Arg::Positional(e) | Arg::Named { value: e, .. } => {
|
|
collect_decl_reads(e, out);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {}
|
|
}
|
|
}
|
|
|
|
fn find_top<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
|
module.functions.iter().find(|f| f.name == name)
|
|
}
|
|
|
|
/// Resolve `#` object type by name in the entry module or any imported library.
|
|
/// Resolve `` `obj`.method `` along the inheritance chain (`_type` first, then bases).
|
|
fn find_method_along_bases<'a>(
|
|
module: &'a Module,
|
|
object: &'a Function,
|
|
method: &str,
|
|
) -> Option<(&'a Module, &'a Function, &'a Function)> {
|
|
let mut owner=module;
|
|
let mut obj=object;
|
|
let mut seen = std::collections::HashSet::new();
|
|
while seen.insert((owner as *const Module,obj as *const Function)) {
|
|
if let Some(target) = obj.children.iter().find(|c| c.name == method) {
|
|
return Some((owner, obj, target));
|
|
}
|
|
match &obj.base {
|
|
Some(base) => { (owner,obj)=crate::inherit::resolve_object(owner,base).ok()?; },
|
|
None => break,
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn find_function_anywhere<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
|
for f in &module.functions {
|
|
if f.name == name {
|
|
return Some(f);
|
|
}
|
|
if let Some(child) = find_in_tree(f, name) {
|
|
return Some(child);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn lookup_function<'a>(
|
|
module: &'a Module,
|
|
current: &'a Function,
|
|
name: &str,
|
|
) -> Option<&'a Function> {
|
|
if let Some(f) = find_in_tree(current, name) {
|
|
return Some(f);
|
|
}
|
|
module.functions.iter().find(|f| f.name == name)
|
|
}
|
|
|
|
fn find_in_tree<'a>(fun: &'a Function, name: &str) -> Option<&'a Function> {
|
|
for child in &fun.children {
|
|
if child.name == name {
|
|
return Some(child);
|
|
}
|
|
if let Some(f) = find_in_tree(child, name) {
|
|
return Some(f);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn lit_to_value(lit: &Literal) -> Value {
|
|
match lit {
|
|
Literal::None => Value::None,
|
|
Literal::Bool(b) => Value::Bool(*b),
|
|
Literal::Int(n) => Value::Int(*n),
|
|
Literal::Num(n) => Value::Num(*n),
|
|
Literal::Text(s) => Value::Text(s.clone()),
|
|
}
|
|
}
|
|
|
|
fn brief_trace_val(v: &Value) -> String {
|
|
let s = v.as_display();
|
|
if s.chars().count() > 24 {
|
|
format!("{}…", s.chars().take(24).collect::<String>())
|
|
} else {
|
|
s
|
|
}
|
|
}
|
|
|
|
/// Prefer real result; else last stdout line emitted by the call; else callee name.
|
|
fn call_event_brief(v: &Value, stdout: &str, stdout_before: usize, callee: &str) -> String {
|
|
if !matches!(v, Value::None) {
|
|
return brief_trace_val(v);
|
|
}
|
|
if stdout.len() > stdout_before {
|
|
let delta = &stdout[stdout_before..];
|
|
let line = delta
|
|
.trim_end()
|
|
.lines()
|
|
.last()
|
|
.unwrap_or(delta.trim_end());
|
|
if !line.is_empty() {
|
|
return if line.chars().count() > 48 {
|
|
format!("{}…", line.chars().take(48).collect::<String>())
|
|
} else {
|
|
line.to_string()
|
|
};
|
|
}
|
|
}
|
|
callee.to_string()
|
|
}
|
|
|
|
fn stmt_span(stmt: &Stmt) -> Span {
|
|
match stmt {
|
|
Stmt::Assign { span, .. }
|
|
| Stmt::Return { span, .. }
|
|
| Stmt::Call { span, .. }
|
|
| Stmt::Expr { span, .. }
|
|
| Stmt::Branch { span, .. }
|
|
| Stmt::While { span, .. }
|
|
| Stmt::ForEach { span, .. } => *span,
|
|
}
|
|
}
|