release: v2.2.0 call one function in any .mq.md

The same page is the document, the knowledge and the program. marqdo call runs that function with arguments, so reuse, tools and tests do not need a second skill system.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-30 09:07:23 +08:00
1 parent 4018e9928a
commit 1730f26fc7
42 files changed
+1917 -116

No files matched your search

+21 -3
View File
@@ -33,6 +33,16 @@ struct FlatFun {
}
pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
compile_with(path, module, true)
}
/// Compile every function even when the file has no single program entry.
/// `Program::entry` is then only a placeholder; callers must use [`Vm::call_function`].
pub fn compile_for_call(path: Option<&Path>, module: &Module) -> Result<Program> {
compile_with(path, module, false)
}
fn compile_with(path: Option<&Path>, module: &Module, require_entry: bool) -> Result<Program> {
let mut flat = Vec::new();
let mut next_scope = 1u32;
let _exports = collect_module_tree(module, &mut flat, 0, &mut next_scope);
@@ -40,7 +50,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
bail!("bytecode: no functions to compile");
}
let entry = flat
let chosen = flat
.iter()
.position(|f| f.name == "main" && f.parent.is_none())
.or_else(|| {
@@ -55,8 +65,14 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
} else {
None
}
})
.ok_or_else(|| anyhow::anyhow!("bytecode: no `# main` object"))?;
});
let entry = match chosen {
Some(index) => index,
None if !require_entry => 0,
None => bail!("bytecode: no `# main` object"),
};
// Imports are compiled first, so a missing entry must take paths from the file's own functions.
let path_owner = if chosen.is_some() { entry } else { flat.len() - 1 };
let mut objects = Vec::new();
let mut methods = Vec::new();
@@ -95,6 +111,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
let parents: Vec<Option<usize>> = flat.iter().map(|f| f.parent).collect();
let children: Vec<Vec<usize>> = flat.iter().map(|f| f.children.clone()).collect();
let path_index = flat[path_owner].path_index.clone();
Ok(Program {
functions,
@@ -104,6 +121,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
methods,
parents,
children,
path_index,
})
}
+5 -1
View File
@@ -3,9 +3,11 @@
mod compile;
mod vm;
pub use compile::compile_module;
pub use compile::{compile_for_call, compile_module};
pub use vm::Vm;
use std::collections::HashMap;
use crate::diagnostics::Span;
use crate::value::Value;
@@ -100,6 +102,8 @@ pub struct Program {
pub parents: Vec<Option<usize>>,
/// Parallel to `functions`: child fn indices.
pub children: Vec<Vec<usize>>,
/// Dotted path (`计算器.加法`, `inc.加一`) → function index. Entry module exports plus imports.
pub path_index: HashMap<Vec<String>, usize>,
}
impl Program {
+42 -4
View File
@@ -102,7 +102,6 @@ impl Vm {
}
pub fn run(&mut self, program: &Program) -> Result<Value> {
let mut stack: Vec<Value> = Vec::new();
let entry = program.entry;
let arity = program.functions[entry].params.len();
if arity != 0 {
@@ -113,14 +112,53 @@ impl Vm {
.unwrap_or(Span::new(1, 1));
return Err(self.err_at(span, "bytecode: entry function needs arguments"));
}
self.execute(program, entry, &[])
}
/// Run `fn_idx` with named arguments already bound to local slots.
/// Does not fall back to [`Program::entry`].
pub fn call_function(
&mut self,
program: &Program,
fn_idx: usize,
args: &[(String, Value)],
) -> Result<Value> {
if fn_idx >= program.functions.len() {
return Err(self.err_at(
Span::new(1, 1),
format!("bytecode: function index {fn_idx} is out of range"),
));
}
self.execute(program, fn_idx, args)
}
fn execute(
&mut self,
program: &Program,
fn_idx: usize,
args: &[(String, Value)],
) -> Result<Value> {
let mut stack: Vec<Value> = Vec::new();
let mut slots = vec![Value::None; program.functions[fn_idx].locals.len().max(1)];
for (name, value) in args {
if let Some(i) = program.functions[fn_idx]
.locals
.iter()
.position(|local| local == name)
{
if i < slots.len() {
slots[i] = value.clone();
}
}
}
let mut frames = vec![Frame {
fn_idx: entry,
fn_idx,
ip: 0,
slots: vec![Value::None; program.functions[entry].locals.len().max(1)],
slots,
retag_matrix: None,
}];
self.host
.push_call_frame(&program.functions[entry].name.clone());
.push_call_frame(&program.functions[fn_idx].name.clone());
loop {
let frame = frames.last_mut().unwrap();
+295
View File
@@ -0,0 +1,295 @@
//! `marqdo call`: run one already-bound function in a `.mq.md` file.
//!
//! Location, effects, and execution go through the existing compiler and runtime.
//! The command does not scan headings, and it does not run the program entry when
//! the named function cannot be compiled.
use std::path::Path;
use anyhow::Result;
use crate::ast::Function;
use crate::bytecode::{compile_for_call, Vm};
use crate::diagnostics::{Diagnostic, Span};
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module;
use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject};
use crate::value::Value;
use crate::Backend;
/// Call `function` in `path` with named arguments.
///
/// Non-pure effects are refused before the function runs. Host write, exec, net,
/// and plugin capabilities stay off for the call.
pub fn call_file(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
) -> Result<Value> {
let path = path
.canonicalize()
.map_err(|e| call_diag(None, 1, "call.compile", format!("failed to read {}: {e}", path.display())))?;
let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?;
let artifact = locate_artifact(&compilation.semantics, &path, function)?;
deny_unsafe(&path, artifact)?;
execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
args,
tight_caps(),
backend,
true,
)
.map(|(value, _stdout)| value)
}
/// Run the function declared at `line` in `path`.
///
/// `display_name` is the declaration path (`计算器.加法`). The query the caller
/// typed is not used as a heading search and is not used as the bytecode path,
/// so a unique short name or SymbolId still executes that function.
/// `caps` are the host capabilities for this run. `call` passes them all off.
pub(crate) fn execute_source_function(
path: &Path,
line: u32,
display_name: &str,
args: &[(String, Value)],
caps: HostCaps,
backend: Backend,
strict_args: bool,
) -> Result<(Value, String)> {
let module = load_module(path)?;
let fun = find_function_at_line(&module.functions, line).ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line),
)
})?;
let expected = display_name
.rsplit('.')
.next()
.unwrap_or(display_name);
if fun.name != expected {
return Err(call_diag(
Some(path),
line,
"artifact.unresolved",
format!("源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", fun.name),
));
}
let mut interp = Interpreter::with_capture(Some(path), false)
.with_host(HostContext::for_capture(Some(path), caps));
// `call` checks the signature. `artifact.execute` keeps its previous
// environment injection so an input the body reads is not rejected as unknown.
let bound;
let invoke_args: &[(String, Value)] = if strict_args {
bound = interp.bind_external_args(&module, fun, args)?;
&bound
} else {
args
};
match backend {
Backend::Tree => {
let value = interp.invoke_bound_function(&module, fun, invoke_args)?;
Ok((value, interp.captured_stdout))
}
Backend::Bytecode => {
let program = compile_for_call(Some(path), &module)?;
let key: Vec<String> = display_name
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let idx = program.path_index.get(&key).copied().ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm = Vm::with_capture(Some(path))
.with_host(HostContext::for_capture(Some(path), caps));
let value = vm.call_function(&program, idx, invoke_args)?;
Ok((value, vm.captured_stdout))
}
}
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, or True/False/None.
pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
let mut out = Vec::new();
for token in tokens {
let Some((name, raw)) = token.split_once('=') else {
return Err(call_diag(
None,
0,
"call.bad_arg",
format!("参数 `{token}` 需要写成 名字=值"),
));
};
if name.is_empty() {
return Err(call_diag(
None,
0,
"call.bad_arg",
format!("参数 `{token}` 缺少名字"),
));
}
let value = parse_literal(raw).map_err(|message| {
call_diag(None, 0, "call.bad_value", format!("参数 `{name}`: {message}"))
})?;
out.push((name.to_string(), value));
}
Ok(out)
}
fn tight_caps() -> HostCaps {
HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
}
}
fn locate_artifact<'a>(
project: &'a SemanticProject,
entry: &Path,
query: &str,
) -> Result<&'a SemanticArtifact> {
let in_entry: Vec<&SemanticArtifact> = project
.artifacts
.iter()
.filter(|artifact| same_file(&project.root, &artifact.source.file, entry))
.collect();
let exact: Vec<&SemanticArtifact> = in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.display_name == query
|| artifact
.symbol_id
.as_ref()
.is_some_and(|id| id.as_str() == query)
|| artifact.artifact_id.0 == query
})
.collect();
let hits = if !exact.is_empty() {
exact
} else if !query.contains('.') {
in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.kind == "function"
&& artifact.display_name.rsplit('.').next() == Some(query)
})
.collect()
} else {
Vec::new()
};
match hits.len() {
1 => Ok(hits[0]),
0 => Err(call_diag(
Some(entry),
1,
"artifact.unresolved",
format!("无法唯一绑定 `{query}`"),
)),
_ => Err(call_diag(
Some(entry),
1,
"artifact.ambiguous",
format!("无法唯一绑定 `{query}`"),
)),
}
}
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.not_executable",
"只有非实例函数可由 call 直接执行".to_string(),
));
}
if !artifact.effects.is_pure() {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.effect_denied",
format!(
"call 默认只执行纯函数,拒绝效应 {}",
artifact.effects.values().join(", ")
),
));
}
Ok(())
}
fn same_file(root: &Path, rel: &str, entry: &Path) -> bool {
let abs = root.join(rel);
match (abs.canonicalize(), entry.canonicalize()) {
(Ok(left), Ok(right)) => left == right,
_ => false,
}
}
fn find_function_at_line(functions: &[Function], line: u32) -> Option<&Function> {
for fun in functions {
if fun.span.line == line {
return Some(fun);
}
if let Some(found) = find_function_at_line(&fun.children, line) {
return Some(found);
}
}
None
}
fn parse_literal(raw: &str) -> Result<Value, String> {
match raw {
"True" | "true" => return Ok(Value::Bool(true)),
"False" | "false" => return Ok(Value::Bool(false)),
"None" | "none" => return Ok(Value::None),
_ => {}
}
if raw.len() >= 2 {
let bytes = raw.as_bytes();
if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"')
|| (bytes[0] == b'\'' && bytes[raw.len() - 1] == b'\'')
{
return Ok(Value::Text(raw[1..raw.len() - 1].to_string()));
}
}
if let Ok(n) = raw.parse::<i64>() {
return Ok(Value::Int(n));
}
if raw.contains('.') {
if let Ok(n) = raw.parse::<f64>() {
return Ok(Value::Num(n));
}
}
Err(format!(
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None)"
))
}
fn preserve_diag(path: &Path, err: anyhow::Error) -> anyhow::Error {
if Diagnostic::find(&err).is_some() {
err
} else {
call_diag(Some(path), 1, "call.compile", format!("{err:#}"))
}
}
fn call_diag(path: Option<&Path>, line: u32, code: &str, message: String) -> anyhow::Error {
anyhow::Error::new(Diagnostic::new(path, Span::new(line, 1), message).with_code(code))
}
+1 -1
View File
@@ -67,7 +67,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Host capability flags. Default: all enabled.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
pub struct HostCaps {
pub fs_write: bool,
pub exec: bool,
+108 -29
View File
@@ -151,6 +151,13 @@ impl Interpreter {
bail_at(self.path.as_deref(), self.current_span, message)
}
fn err_code(&self, code: &str, message: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(
crate::diagnostics::Diagnostic::new(self.path.as_deref(), self.current_span, message)
.with_code(code),
)
}
fn emit_line(&mut self, text: &str) {
if self.capture {
self.captured_stdout.push_str(text);
@@ -363,6 +370,68 @@ impl Interpreter {
self.run_function(module, fun, Env::new(), args, false)
}
/// 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)>> {
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(|m| {
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.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)
}
/// 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(
@@ -1450,36 +1519,8 @@ impl Interpreter {
path: &[String],
ev_args: &[EvArg],
) -> Result<Value> {
let (lib, node) = locate_import_function(module, path).map_err(|m| self.err(m))?;
let display = path.join(".");
if path.len() < 2 {
return Err(self.err(format!("library path `{display}`: need at least `lib.member`")));
}
let lib_name = &path[0];
let lib = module.import_modules.get(lib_name).ok_or_else(|| {
self.err(format!("unknown library `{lib_name}` (import it in frontmatter)"))
})?;
let mut parent_is_object = false;
let mut node = lib
.functions
.iter()
.find(|f| f.name == path[1])
.ok_or_else(|| self.err(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(|| self.err(format!("unknown `{display}`")))?;
}
if parent_is_object && !node.is_object() && crate::ast::function_uses_receiver(node) {
return Err(self.err(format!(
"`{display}` is an instance method; call it as `var`.{}",
node.name
)));
}
let bound = {
let mut dummy_env = Env::new();
@@ -1613,6 +1654,44 @@ fn tag_instance(type_name: &str, value: Value) -> Value {
}
}
/// `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,
+43 -1
View File
@@ -12,6 +12,7 @@ pub mod binding;
pub mod browser_session;
pub mod builtin;
pub mod bytecode;
pub mod call;
pub mod capture;
#[cfg(feature = "cli")]
pub mod catalog;
@@ -260,6 +261,23 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
let bound_call = if let Some(lib_path) = &opts.call_lib_path {
let named = named_call_args(opts)?;
let segments: Vec<String> = lib_path
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let (lib, fun) = crate::interp::locate_import_function(&module, &segments)
.map_err(|m| anyhow::anyhow!(m))?;
let mut binder = Interpreter::with_capture(Some(path), false).with_host(
HostContext::for_capture(Some(path), opts.host_caps()),
);
let bound = binder.bind_external_args(lib, fun, &named)?;
Some((lib_path.clone(), bound))
} else {
None
};
let mut vm = Vm::new(Some(path))
.with_stdin(stdin_lines)
.with_trace(opts.trace_eval)
@@ -267,7 +285,21 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
if opts.trace_eval {
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
}
let value = vm.run(&program)?;
let value = if let Some((lib_path, bound)) = bound_call {
let key: Vec<String> = lib_path
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let idx = program.path_index.get(&key).copied().ok_or_else(|| {
anyhow::anyhow!(
"bytecode: `{lib_path}` did not compile to a function; refusing to run the program entry"
)
})?;
vm.call_function(&program, idx, &bound)?
} else {
vm.run(&program)?
};
if opts.trace_eval {
eprintln!("=== marqdo: end trace-eval ===");
}
@@ -301,6 +333,16 @@ fn run_call_lib_path(
Ok(value)
}
fn named_call_args(opts: &RunOptions) -> Result<Vec<(String, crate::value::Value)>> {
let Some(value) = load_args_json(opts)? else {
return Ok(Vec::new());
};
match value {
crate::value::Value::Map(pairs) => Ok(pairs),
_ => bail!("args-json must be a JSON object"),
}
}
fn load_args_json(opts: &RunOptions) -> Result<Option<crate::value::Value>> {
let Some(path) = &opts.args_json else {
return Ok(None);
+61
View File
@@ -137,6 +137,26 @@ enum Commands {
#[arg(long)]
legacy_markup: bool,
},
/// Call one function in a `.mq.md` file: `marqdo call <file> <function> name=value`.
Call {
/// Source file.
file: PathBuf,
/// Function display path, for example `计算器.加法`.
function: String,
/// Named arguments `name=value` (integer, decimal, quoted text, True/False/None).
/// A value may be negative (`a=-2`). `--json` and `--backend` remain flags.
args: Vec<String>,
/// Print one JSON object: `{"ok":true,"result":...}` or `{"ok":false,"error":...}`.
#[arg(long)]
json: bool,
/// Runtime. Both backends execute the named function.
#[arg(long, value_enum, default_value_t = BackendCli::Tree)]
backend: BackendCli,
},
/// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables
Check {
/// Program path (.mq.md)
@@ -784,6 +804,47 @@ fn try_main(cli: Cli) -> Result<i32> {
}
Ok(0)
}
Commands::Call {
file,
function,
args,
json,
backend,
} => {
let outcome = (|| -> Result<marqdo::value::Value> {
let parsed = marqdo::call::parse_call_args(&args)?;
marqdo::call::call_file(&file, &function, &parsed, backend.into())
})();
match outcome {
Ok(value) => {
if json {
let result = marqdo::value_as_json(&value)
.map_err(|e| anyhow::anyhow!(e))?;
println!(
"{}",
serde_json::json!({"ok": true, "result": result})
);
} else {
println!("{}", value.as_display());
}
Ok(0)
}
Err(err) => {
let diag = Diagnostic::find(&err).cloned().unwrap_or_else(|| {
Diagnostic::new(None, Span::new(0, 0), format!("{err:#}")).with_code("call.failed")
});
if json {
println!(
"{}",
serde_json::json!({"ok": false, "error": diag.to_json()})
);
} else {
eprintln!("error: {diag}");
}
Ok(1)
}
}
}
Commands::Check {
file,
json,
+11 -32
View File
@@ -833,28 +833,22 @@ fn artifact_execute(params: &Value) -> Result<Value, Value> {
let denied: Vec<String> = artifact.effects.values().into_iter().filter(|effect| effect != "pure" && !allowed.contains(&effect.as_str())).collect();
if !denied.is_empty() { return Err(json!({"code":"artifact.effect_denied","message":"效果策略拒绝执行","denied":denied,"effects":artifact.effects.values()})); }
let path = compilation.semantics.root.join(&artifact.source.file);
let module = load::load_module(&path).map_err(|e| diagnostic_err("artifact.load", &e))?;
let input = params.get("inputs").cloned().unwrap_or_else(|| json!({}));
let object = input.as_object().ok_or_else(|| err("mlsp.bad_request", "inputs 必须是 JSON 对象"))?;
let mut args = Vec::new();
for (name, value) in object { args.push((name.clone(), crate::host::json::json_to_value(value).map_err(|e| err("mlsp.bad_input", e))?)); }
let caps = crate::host::HostCaps { fs_write: allowed.contains(&"fs.write"), exec: allowed.iter().any(|e| matches!(*e, "process.exec" | "plugin.call" | "llm.call")), net: allowed.iter().any(|e| matches!(*e, "network.read" | "network.write" | "llm.call")), plugin: allowed.contains(&"plugin.call") };
let host = crate::host::HostContext::for_capture(Some(&path), caps);
let mut interpreter = crate::interp::Interpreter::with_capture(Some(&path), false).with_host(host);
// Bind by source line / declaration identity — never by bare display_name suffix (G07).
let fun = find_function_at_line(&module.functions, artifact.source.line).ok_or_else(|| {
err(
"artifact.unresolved",
format!(
"无法在 {}:{} 定位绑定函数 {}",
artifact.source.file, artifact.source.line, artifact.display_name
),
)
})?;
let value = interpreter
.invoke_bound_function(&module, fun, &args)
.map_err(|e| diagnostic_err("artifact.execution_failed", &e))?;
let stdout = std::mem::take(&mut interpreter.captured_stdout);
// Same line identity, argument binding, and runtime as `marqdo call`.
let (value, stdout) = crate::call::execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
&args,
caps,
crate::Backend::Tree,
false,
)
.map_err(|e| diagnostic_err("artifact.execution_failed", &e))?;
Ok(json!({
"schema_version": 1,
"artifact_id": artifact.artifact_id.0,
@@ -866,21 +860,6 @@ fn artifact_execute(params: &Value) -> Result<Value, Value> {
}))
}
fn find_function_at_line<'a>(
functions: &'a [crate::ast::Function],
line: u32,
) -> Option<&'a crate::ast::Function> {
for fun in functions {
if fun.span.line == line {
return Some(fun);
}
if let Some(found) = find_function_at_line(&fun.children, line) {
return Some(found);
}
}
None
}
fn err(code: &str, message: impl Into<String>) -> Value {
json!({"code": code, "message": message.into()})
}
+64 -6
View File
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use sha2::{Digest as _, Sha256};
@@ -240,10 +240,20 @@ pub struct Compilation {
/// side-effect free: it never loads plugins, evaluates expressions or fetches
/// sources.
pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
let t_index = std::time::Instant::now();
let root = ProjectRoot::new(&options.project_root)?;
let index = ProjectIndex::build(root.clone())?;
let index_ms = t_index.elapsed().as_millis();
compile_index(ProjectIndex::build(root)?)
}
/// Compile `entry` and the modules it imports. Sibling files in the directory are not included.
pub fn compile_file_closure(entry: &Path) -> Result<Compilation> {
let files = import_closure(entry)?;
let ancestor = common_ancestor(&files)?;
let root = ProjectRoot::new(&ancestor)?;
compile_index(ProjectIndex::from_files(root, files)?)
}
fn compile_index(index: ProjectIndex) -> Result<Compilation> {
let root = index.root().clone();
// Reuse parsed modules from ProjectIndex — same input snapshot, no second parse (M-R5b).
let mut files = BTreeMap::new();
let mut diagnostics = Vec::new();
@@ -257,8 +267,6 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
),
);
}
let _ = index_ms; // ProjectIndex build duration (M-R5b span)
// Wire import_modules from already-parsed project files so BoundCall path
// resolve shares `resolve_for_exec` (no plugin load / no re-parse).
attach_project_imports(&mut files);
@@ -349,6 +357,56 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
})
}
fn import_closure(entry: &Path) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
fn walk(path: &Path, out: &mut Vec<PathBuf>, seen: &mut std::collections::HashSet<PathBuf>) -> Result<()> {
if !path.is_file() {
return Ok(());
}
let canon = path.canonicalize().with_context(|| format!("resolve {}", path.display()))?;
if !seen.insert(canon.clone()) {
return Ok(());
}
out.push(canon.clone());
let source = fs::read_to_string(&canon).with_context(|| format!("read {}", canon.display()))?;
let module = crate::load::parse_source_auto(&source)
.with_context(|| format!("parse {}", canon.display()))?;
let base = canon.parent().unwrap_or_else(|| Path::new("."));
for imp in &module.imports {
let dep = crate::load::resolve_import(base, &imp.path)
.with_context(|| format!("import `{}` from {}", imp.path, canon.display()))?;
walk(&dep, out, seen)?;
}
Ok(())
}
if !entry.is_file() {
bail!("call target {} is not a file", entry.display());
}
walk(entry, &mut out, &mut seen)?;
out.sort();
Ok(out)
}
fn common_ancestor(files: &[PathBuf]) -> Result<PathBuf> {
let Some(first) = files.first() else {
bail!("call target has no source files");
};
let mut ancestor = first
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
for file in files.iter().skip(1) {
while !file.starts_with(&ancestor) {
ancestor = ancestor
.parent()
.map(|p| p.to_path_buf())
.ok_or_else(|| anyhow::anyhow!("source files have no common directory"))?;
}
}
Ok(ancestor)
}
fn module_artifact(index: &ProjectIndex, module: &ModuleId, path: &Path, text: &str) -> SemanticArtifact {
let implementation = digest(normalize_source(text));
let interface = digest(module.as_str());
+2 -1
View File
@@ -16,7 +16,8 @@ pub use bind::{
};
pub use extract::{plan_pure_extract, ExtractError, ExtractPlan};
pub use ir::{
artifact_json, compile_project, semantic_generation_dir, write_semantic_projections, ArtifactId,
artifact_json, compile_file_closure, compile_project, semantic_generation_dir,
write_semantic_projections, ArtifactId,
BoundCall, CompileOptions, Compilation, Digest, DynamicCall, EffectSet, LockMode,
SemanticArtifact, SemanticProject,
};
+6 -1
View File
@@ -119,8 +119,13 @@ pub struct ProjectIndex {
impl ProjectIndex {
pub fn build(root: ProjectRoot) -> Result<Self> {
let project_id = project_id(root.path());
let files = root.source_files()?;
Self::from_files(root, files)
}
/// Index exactly `files` (already chosen by the caller). Paths must sit under `root`.
pub fn from_files(root: ProjectRoot, files: Vec<PathBuf>) -> Result<Self> {
let project_id = project_id(root.path());
let mut modules = BTreeMap::new();
let mut path_to_module = BTreeMap::new();
let mut symbols = Vec::new();