Add module namespaces and harden L1/agent after the import redesign.

Bind imports to library names with bare path calls (and use), forward optional host args through mq wrappers, stabilize writeback replacement newlines, and document the M1/M2 decisions.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-07 13:28:32 +08:00
1 parent 99132ac8fc
commit 1f23e2ed93
108 files changed
+3228 -1023

No files matched your search

+43
View File
@@ -53,6 +53,30 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
("at", "value" | "值") => "value".into(),
("at", "index" | "下标") => "index".into(),
("call_fn", "name" | "名") => "name".into(),
(
"host_writeback_record" | "host_writeback_get" | "host_writeback_clear",
"key" | "键",
) => "key".into(),
("host_writeback_ensure", "key" | "键") => "key".into(),
(
"host_writeback_ensure",
"placeholder" | "占位",
) => "placeholder".into(),
(
"host_writeback_record" | "host_writeback_get" | "host_writeback_clear",
"at_end" | "末尾",
) => "at_end".into(),
(
"host_writeback_record"
| "host_writeback_get"
| "host_writeback_clear"
| "host_writeback_ensure",
"line" | "行",
) => "line".into(),
(
"host_writeback_record",
"value" | "值",
) => "value".into(),
(
"host_plot" | "host_plot_points" | "host_plot_conic",
"grid" | "网格",
@@ -60,6 +84,24 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
("host_plot" | "host_plot_points" | "host_plot_conic", "path" | "路径") => {
"path".into()
}
("host_dotenv_load" | "load_dotenv", "path" | "路径") => "path".into(),
("host_exec" | "exec", "cmd" | "命令") => "cmd".into(),
("host_exec" | "exec", "args" | "参数") => "args".into(),
(
"host_http_get" | "http_get" | "host_http_post" | "http_post" | "host_http_request"
| "http_request",
"headers" | "头",
) => "headers".into(),
(
"host_http_post" | "http_post" | "host_http_request" | "http_request",
"content_type" | "类型",
) => "content_type".into(),
("host_http_get" | "http_get" | "host_http_post" | "http_post" | "host_http_request"
| "http_request", "url" | "地址") => "url".into(),
("host_http_post" | "http_post" | "host_http_request" | "http_request", "body" | "内容") => {
"body".into()
}
("host_json_stringify" | "stringify", "indent" | "缩进") => "indent".into(),
("host_plot", "steps" | "步数") => "steps".into(),
("host_plot", "derivative" | "导数") => "derivative".into(),
("host_foreign_run", "code" | "代码") => "code".into(),
@@ -67,6 +109,7 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
("host_foreign_set_cmd" | "host_foreign_run_lang", "lang" | "语言") => "lang".into(),
("host_foreign_set_cmd", "cmd" | "命令") => "cmd".into(),
("host_foreign_run_lang", "source" | "源码") => "source".into(),
("host_ext_native_path", "name" | "名") => "name".into(),
_ => param.to_string(),
}
}
+40 -2
View File
@@ -1,13 +1,43 @@
//! Marqdo AST (Phase I).
use std::collections::HashMap;
use crate::diagnostics::Span;
use crate::formula::Expr as FormulaExpr;
use crate::value::CodeBlock;
/// Frontmatter import: path + library bind name (see `doc/design/module-namespace.md`).
#[derive(Debug, Clone)]
pub struct Import {
pub path: String,
pub bind: String,
}
/// Frontmatter `use` / `使用`: bind a short name to a library path (`time.format`).
#[derive(Debug, Clone)]
pub struct Use {
pub path: Vec<String>,
pub bind: String,
}
#[derive(Debug, Clone)]
pub struct Module {
pub imports: Vec<String>,
pub imports: Vec<Import>,
pub uses: Vec<Use>,
pub functions: Vec<Function>,
/// Populated by the loader: bind name → imported module (not flattened).
pub import_modules: HashMap<String, Module>,
}
impl Default for Module {
fn default() -> Self {
Self {
imports: Vec::new(),
uses: Vec::new(),
functions: Vec::new(),
import_modules: HashMap::new(),
}
}
}
#[derive(Debug, Clone)]
@@ -78,6 +108,9 @@ pub struct BranchArm {
#[derive(Debug, Clone)]
pub struct CallExpr {
pub callee: String,
/// Bare library path segments, e.g. `["time","parse"]` for `time.parse`.
/// Mutually exclusive with `receiver` (instance method).
pub path: Option<Vec<String>>,
/// When set, `` `recv`.callee `` method call; receiver is a variable name.
pub receiver: Option<String>,
pub args: Vec<Arg>,
@@ -155,7 +188,12 @@ pub fn format_ast_dump(path: &str, module: &Module) -> String {
let mut out = String::new();
out.push_str(&format!("=== marqdo: ast ({path}) ===\n"));
if !module.imports.is_empty() {
out.push_str(&format!("(imports {:?})\n", module.imports));
let specs: Vec<String> = module
.imports
.iter()
.map(|i| format!("{} as {}", i.path, i.bind))
.collect();
out.push_str(&format!("(imports {:?})\n", specs));
}
for fun in &module.functions {
dump_fun(&mut out, fun, 0);
+129 -46
View File
@@ -19,13 +19,15 @@ struct FlatFun {
body: Vec<Stmt>,
children: Vec<usize>,
span: Span,
/// Full path segments (`lib.member` / `lib.Type.method`) → flat index.
path_index: HashMap<Vec<String>, usize>,
/// Short name from frontmatter `use` → path segments.
uses: HashMap<String, Vec<String>>,
}
pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
let mut flat = Vec::new();
for fun in &module.functions {
collect_fun(fun, None, &mut flat);
}
let _exports = collect_module_tree(module, &mut flat);
if flat.is_empty() {
bail!("bytecode: no functions to compile");
}
@@ -78,7 +80,55 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
})
}
fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -> usize {
/// Collect `module` and its imports into `flat`.
/// Returns relative export paths within this module (e.g. `["parse"]`, `["agent","step"]`).
fn collect_module_tree(module: &Module, flat: &mut Vec<FlatFun>) -> HashMap<Vec<String>, usize> {
let mut path_index = HashMap::new();
for (bind, dep) in &module.import_modules {
let dep_exports = collect_module_tree(dep, flat);
for (rel, idx) in dep_exports {
let mut full = Vec::with_capacity(rel.len() + 1);
full.push(bind.clone());
full.extend(rel);
path_index.insert(full, idx);
}
}
let uses: HashMap<String, Vec<String>> = module
.uses
.iter()
.map(|u| (u.bind.clone(), u.path.clone()))
.collect();
let mut exports = HashMap::new();
for fun in &module.functions {
let id = collect_fun(fun, None, flat, &path_index, &uses);
export_tree(&mut exports, &[], id, flat);
}
exports
}
fn export_tree(
out: &mut HashMap<Vec<String>, usize>,
prefix: &[String],
id: usize,
flat: &[FlatFun],
) {
let mut p = prefix.to_vec();
p.push(flat[id].name.clone());
out.insert(p.clone(), id);
for &cid in &flat[id].children {
export_tree(out, &p, cid, flat);
}
}
fn collect_fun(
fun: &Function,
parent: Option<usize>,
flat: &mut Vec<FlatFun>,
path_index: &HashMap<Vec<String>, usize>,
uses: &HashMap<String, Vec<String>>,
) -> usize {
let id = flat.len();
flat.push(FlatFun {
name: fun.name.clone(),
@@ -88,10 +138,12 @@ fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -
body: fun.body.clone(),
children: Vec::new(),
span: fun.span,
path_index: path_index.clone(),
uses: uses.clone(),
});
let mut child_ids = Vec::new();
for child in &fun.children {
child_ids.push(collect_fun(child, Some(id), flat));
child_ids.push(collect_fun(child, Some(id), flat, path_index, uses));
}
flat[id].children = child_ids;
id
@@ -365,6 +417,12 @@ impl<'a> FnCompiler<'a> {
fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> {
let mut call = call.clone();
if let Some(path) = &call.path {
return self.compile_path_call(path, &call, as_stmt);
}
if let Some(path) = self.flat[self.fn_id].uses.get(&call.callee).cloned() {
return self.compile_path_call(&path, &call, as_stmt);
}
call.callee =
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
@@ -529,51 +587,76 @@ impl<'a> FnCompiler<'a> {
}
match self.resolve_call(&call.callee) {
Ok(fid) => {
let params = &self.flat[fid].params;
let mut named: HashMap<String, &Expr> = HashMap::new();
let mut positionals = Vec::new();
for a in &call.args {
match a {
Arg::Positional(e) => positionals.push(e),
Arg::Named { name, value } => {
named.insert(name.clone(), value);
}
}
}
let mut pos_i = 0;
for p in params {
if let Some(e) = named.get(&p.name) {
self.compile_expr(e)?;
} else if pos_i < positionals.len() {
self.compile_expr(positionals[pos_i])?;
pos_i += 1;
} else if let Some(def) = &p.default {
self.compile_expr(def)?;
} else {
return Err(self.err(format!("missing argument for parameter `{}`", p.name)));
}
}
if pos_i < positionals.len() {
return Err(self.err(format!(
"too many positional arguments ({} extra)",
positionals.len() - pos_i
)));
}
self.emit(Op::Call(fid as u16, params.len() as u8));
if self.flat[fid].parent.is_none() && self.flat[fid].level == 1 {
let ti = self.add_const(Value::Text(self.flat[fid].name.clone()));
self.emit(Op::TagInstance(ti));
}
if as_stmt {
self.emit(Op::Pop);
}
Ok(())
}
Ok(fid) => self.compile_user_call(fid, &call, as_stmt),
Err(_) => self.compile_plugin_call(&call, as_stmt),
}
}
fn compile_path_call(&mut self, path: &[String], call: &CallExpr, as_stmt: bool) -> Result<()> {
let display = path.join(".");
if path.len() < 2 {
return Err(self.err(format!(
"library path `{display}`: need at least `lib.member`"
)));
}
let fid = *self.flat[self.fn_id]
.path_index
.get(path)
.ok_or_else(|| self.err(format!("unknown `{display}`")))?;
if let Some(pid) = self.flat[fid].parent {
let parent = &self.flat[pid];
if parent.level == 1 && parent.parent.is_none() && !(self.flat[fid].level == 1) {
return Err(self.err(format!(
"`{display}` is an instance method; call it as `var`.{}",
self.flat[fid].name
)));
}
}
self.compile_user_call(fid, call, as_stmt)
}
fn compile_user_call(&mut self, fid: usize, call: &CallExpr, as_stmt: bool) -> Result<()> {
let params = &self.flat[fid].params;
let mut named: HashMap<String, &Expr> = HashMap::new();
let mut positionals = Vec::new();
for a in &call.args {
match a {
Arg::Positional(e) => positionals.push(e),
Arg::Named { name, value } => {
named.insert(name.clone(), value);
}
}
}
let mut pos_i = 0;
for p in params {
if let Some(e) = named.get(&p.name) {
self.compile_expr(e)?;
} else if pos_i < positionals.len() {
self.compile_expr(positionals[pos_i])?;
pos_i += 1;
} else if let Some(def) = &p.default {
self.compile_expr(def)?;
} else {
return Err(self.err(format!("missing argument for parameter `{}`", p.name)));
}
}
if pos_i < positionals.len() {
return Err(self.err(format!(
"too many positional arguments ({} extra)",
positionals.len() - pos_i
)));
}
self.emit(Op::Call(fid as u16, params.len() as u8));
if self.flat[fid].parent.is_none() && self.flat[fid].level == 1 {
let ti = self.add_const(Value::Text(self.flat[fid].name.clone()));
self.emit(Op::TagInstance(ti));
}
if as_stmt {
self.emit(Op::Pop);
}
Ok(())
}
/// Unresolved callee → runtime plugin registry (or unknown-fn error).
/// Named args: stack pairs (name, value)×N, argc = 2N, name const prefixed with `@`.
/// Positional: stack values, argc = N, name const as-is.
+2 -3
View File
@@ -156,9 +156,8 @@ fn extract_frontmatter_imports(source: &str) -> Vec<String> {
break;
}
if let Some(rest) = t.strip_prefix('>') {
let path = rest.trim();
if path.ends_with(".mq.md") {
imports.push(path.to_string());
if let Some(imp) = crate::parse::parse_import_spec(rest.trim()) {
imports.push(format!("{} as {}", imp.path, imp.bind));
}
}
}
+39 -6
View File
@@ -28,7 +28,7 @@ pub const CATALOG: &[ExtPackage] = &[
id: "agent",
description: "Agent development framework (ext/ai/agent)",
mq_files: &["ai/agent.mq.md", "ai/智能体.mq.md"],
native_crate: None,
native_crate: Some("marqdo_plugin_agent"),
},
];
@@ -151,11 +151,24 @@ fn find_source_file(name: &str) -> Result<PathBuf> {
fn find_native_plugin() -> Result<PathBuf> {
let name = native_lib_filename();
let mut candidates = Vec::new();
if let Ok(p) = env::var("MARQDO_AGENT_PLUGIN") {
let p = PathBuf::from(p);
if p.is_file() {
return Ok(p);
}
candidates.push(p);
}
if let Ok(h) = env::var("MARQDO_EXT_SOURCE") {
let base = PathBuf::from(h);
candidates.push(base.join("native").join(name));
candidates.push(base.join(name));
}
// Honor CARGO_TARGET_DIR (sandbox / custom target roots) before cwd/target.
if let Ok(td) = env::var("CARGO_TARGET_DIR") {
let td = PathBuf::from(td);
candidates.push(td.join("debug").join(name));
candidates.push(td.join("release").join(name));
}
if let Ok(cwd) = env::current_dir() {
candidates.push(cwd.join("target").join("debug").join(name));
candidates.push(cwd.join("target").join("release").join(name));
@@ -164,19 +177,19 @@ fn find_native_plugin() -> Result<PathBuf> {
if let Ok(exe) = env::current_exe() {
if let Some(dir) = exe.parent() {
candidates.push(dir.join("ext").join("native").join(name));
// Same directory as the marqdo binary (typical: target/debug/).
candidates.push(dir.join(name));
// target/debug/deps → target/debug
candidates.push(dir.join(name));
candidates.push(dir.join("..").join(name));
}
}
for p in candidates {
for p in &candidates {
if p.is_file() {
return Ok(p);
return Ok(p.clone());
}
}
bail!(
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_agent`, or place it under MARQDO_EXT_SOURCE/native/)"
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_agent`, or `marqdo ext add agent`, or set MARQDO_AGENT_PLUGIN)"
);
}
@@ -270,6 +283,7 @@ pub fn remove_ext(id: &str) -> Result<()> {
}
/// Resolve installed native plugin path for `name` (currently only `agent`).
/// Also falls back to cargo `target/{debug,release}` artifacts for local runs.
pub fn installed_native_path(name: &str) -> Option<PathBuf> {
if name != "agent" {
return None;
@@ -287,7 +301,13 @@ pub fn installed_native_path(name: &str) -> Option<PathBuf> {
return Some(p);
}
}
None
if let Ok(p) = env::var("MARQDO_AGENT_PLUGIN") {
let p = PathBuf::from(p);
if p.is_file() {
return Some(p);
}
}
find_native_plugin().ok()
}
pub fn path_is_trusted_plugin(path: &Path) -> bool {
@@ -303,5 +323,18 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool {
return true;
}
}
if let Ok(p) = env::var("MARQDO_AGENT_PLUGIN") {
let p = PathBuf::from(p);
let p = p.canonicalize().unwrap_or(p);
if p == path {
return true;
}
}
if let Ok(found) = find_native_plugin() {
let found = found.canonicalize().unwrap_or(found);
if found == path {
return true;
}
}
false
}
+5 -113
View File
@@ -1,4 +1,4 @@
//! Runtime support for `ext/agent`: module source, call site, skill text, history store.
//! Runtime helpers for ABI `host_query` and shared map/list ops.
use std::path::{Path, PathBuf};
@@ -18,13 +18,6 @@ impl HostContext {
pub fn pop_call_frame(&mut self) {
self.call_stack.pop();
}
pub fn alloc_agent_id(&mut self) -> String {
self.agent_seq = self.agent_seq.wrapping_add(1);
let id = format!("agent-{}", self.agent_seq);
self.agent_histories.insert(id.clone(), Vec::new());
id
}
}
pub fn module_source(ctx: &HostContext) -> Result<Value, String> {
@@ -110,7 +103,6 @@ fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
roots.push(dir.to_path_buf());
if let Some(parent) = dir.parent() {
roots.push(parent.to_path_buf());
// target/debug → repo root
if let Some(repo) = parent.parent() {
roots.push(repo.to_path_buf());
}
@@ -121,7 +113,6 @@ fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
if let Some(p) = &ctx.entry_path {
if let Some(parent) = p.parent() {
roots.push(parent.to_path_buf());
// tests/ext → repo
if let Some(repo) = parent.parent().and_then(|p| p.parent()) {
roots.push(repo.to_path_buf());
}
@@ -133,44 +124,6 @@ fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
roots
}
pub fn agent_alloc(ctx: &mut HostContext) -> Result<Value, String> {
Ok(Value::Text(ctx.alloc_agent_id()))
}
pub fn agent_history_get(ctx: &HostContext, id: &Value) -> Result<Value, String> {
let id = text_id(id)?;
Ok(Value::List(
ctx.agent_histories
.get(&id)
.cloned()
.unwrap_or_default(),
))
}
pub fn agent_history_clear(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = text_id(id)?;
ctx.agent_histories.insert(id, Vec::new());
Ok(Value::None)
}
pub fn agent_history_append(
ctx: &mut HostContext,
id: &Value,
item: &Value,
) -> Result<Value, String> {
let id = text_id(id)?;
let list = ctx.agent_histories.entry(id).or_default();
list.push(item.clone());
Ok(Value::List(list.clone()))
}
fn text_id(id: &Value) -> Result<String, String> {
match id {
Value::Text(s) if !s.is_empty() => Ok(s.clone()),
_ => Err("agent history id must be non-empty text".into()),
}
}
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.clone(),
@@ -203,75 +156,14 @@ pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
}
}
fn tool_name_from_row(row: &Value) -> Option<String> {
match row {
Value::Text(s) if !s.is_empty() => Some(s.clone()),
Value::Map(entries) => ["工具", "tools", "name"]
.iter()
.find_map(|key| {
entries.iter().find(|(k, _)| k == *key).and_then(|(_, v)| {
if let Value::Text(s) = v {
(!s.is_empty()).then(|| s.clone())
} else {
None
}
})
}),
_ => None,
}
}
pub fn tool_names(tools: &Value) -> Vec<String> {
match tools {
Value::List(rows) => rows.iter().filter_map(tool_name_from_row).collect(),
_ => Vec::new(),
}
}
pub fn format_tools_for_llm(tools: &Value) -> Result<Value, String> {
let mut out = String::from("Available tools (invoke via TOOL:<name>):\n");
for name in tool_names(tools) {
out.push_str("- ");
out.push_str(&name);
out.push('\n');
}
Ok(Value::Text(out))
}
pub fn tool_allowed(tools: &Value, name: &Value) -> Result<Value, String> {
let name = match name {
Value::Text(s) if !s.is_empty() => s.as_str(),
_ => return Ok(Value::Bool(false)),
};
Ok(Value::Bool(
tool_names(tools).iter().any(|n| n == name),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tool_catalog_from_table() {
let tools = Value::List(vec![Value::Text("获取时间".into())]);
let text = format_tools_for_llm(&tools).unwrap();
assert!(matches!(text, Value::Text(s) if s.contains("获取时间")));
assert!(tool_allowed(&tools, &Value::Text("获取时间".into())).unwrap().truthy());
assert!(!tool_allowed(&tools, &Value::Text("nope".into())).unwrap().truthy());
}
#[test]
fn map_set_and_history() {
let mut ctx = HostContext::default();
let id = ctx.alloc_agent_id();
assert!(id.starts_with("agent-"));
agent_history_append(&mut ctx, &Value::Text(id.clone()), &Value::Text("a".into()))
.unwrap();
let h = agent_history_get(&ctx, &Value::Text(id.clone())).unwrap();
assert_eq!(h, Value::List(vec![Value::Text("a".into())]));
agent_history_clear(&mut ctx, &Value::Text(id)).unwrap();
let h2 = agent_history_get(&ctx, &Value::Text("agent-1".into())).unwrap();
assert_eq!(h2, Value::List(vec![]));
fn map_set_updates() {
let m = Value::Map(vec![("a".into(), Value::Int(1))]);
let m2 = map_set(&m, &Value::Text("a".into()), &Value::Int(2)).unwrap();
assert_eq!(m2, Value::Map(vec![("a".into(), Value::Int(2))]));
}
}
+48 -66
View File
@@ -81,17 +81,8 @@ pub enum HostFn {
PluginUnload = 70,
PluginList = 71,
ExtNativePath = 72,
ModuleSource = 73,
CallSite = 74,
MarqdoSkill = 75,
MapSet = 76,
ListAppend = 77,
AgentAlloc = 78,
AgentHistoryGet = 79,
AgentHistoryClear = 80,
AgentHistoryAppend = 81,
FormatToolsForLlm = 82,
ToolAllowed = 83,
WritebackRecord = 84,
WritebackGet = 85,
WritebackClear = 86,
@@ -101,6 +92,8 @@ pub enum HostFn {
SubtaskJoin = 90,
SubtaskKill = 91,
SubtaskWaitAll = 92,
WritebackEnsure = 93,
OuterCallLine = 94,
}
impl HostFn {
@@ -178,17 +171,8 @@ impl HostFn {
70 => Self::PluginUnload,
71 => Self::PluginList,
72 => Self::ExtNativePath,
73 => Self::ModuleSource,
74 => Self::CallSite,
75 => Self::MarqdoSkill,
76 => Self::MapSet,
77 => Self::ListAppend,
78 => Self::AgentAlloc,
79 => Self::AgentHistoryGet,
80 => Self::AgentHistoryClear,
81 => Self::AgentHistoryAppend,
82 => Self::FormatToolsForLlm,
83 => Self::ToolAllowed,
84 => Self::WritebackRecord,
85 => Self::WritebackGet,
86 => Self::WritebackClear,
@@ -198,6 +182,8 @@ impl HostFn {
90 => Self::SubtaskJoin,
91 => Self::SubtaskKill,
92 => Self::SubtaskWaitAll,
93 => Self::WritebackEnsure,
94 => Self::OuterCallLine,
_ => return None,
})
}
@@ -279,21 +265,14 @@ impl HostFn {
"host_plugin_unload" | "plugin_unload" => Self::PluginUnload,
"host_plugin_list" | "plugin_list" => Self::PluginList,
"host_ext_native_path" | "ext_native_path" => Self::ExtNativePath,
"host_module_source" | "module_source" => Self::ModuleSource,
"host_call_site" | "call_site" => Self::CallSite,
"host_marqdo_skill" | "marqdo_skill" => Self::MarqdoSkill,
"host_map_set" | "map_set" => Self::MapSet,
"host_map_set" | "map_set" => Self::MapSet,
"host_list_append" | "list_append" => Self::ListAppend,
"host_agent_alloc" | "agent_alloc" => Self::AgentAlloc,
"host_agent_history_get" | "agent_history_get" => Self::AgentHistoryGet,
"host_agent_history_clear" | "agent_history_clear" => Self::AgentHistoryClear,
"host_agent_history_append" | "agent_history_append" => Self::AgentHistoryAppend,
"host_format_tools_for_llm" | "format_tools_for_llm" => Self::FormatToolsForLlm,
"host_tool_allowed" | "tool_allowed" => Self::ToolAllowed,
"host_writeback_record" | "writeback_record" => Self::WritebackRecord,
"host_writeback_record" | "writeback_record" => Self::WritebackRecord,
"host_writeback_get" | "writeback_get" => Self::WritebackGet,
"host_writeback_clear" | "writeback_clear" => Self::WritebackClear,
"host_writeback_list" | "writeback_list" => Self::WritebackList,
"host_writeback_ensure" | "writeback_ensure" => Self::WritebackEnsure,
"host_outer_call_line" | "outer_call_line" => Self::OuterCallLine,
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
@@ -381,21 +360,14 @@ impl HostFn {
Self::PluginUnload => "host_plugin_unload",
Self::PluginList => "host_plugin_list",
Self::ExtNativePath => "host_ext_native_path",
Self::ModuleSource => "host_module_source",
Self::CallSite => "host_call_site",
Self::MarqdoSkill => "host_marqdo_skill",
Self::MapSet => "host_map_set",
Self::ListAppend => "host_list_append",
Self::AgentAlloc => "host_agent_alloc",
Self::AgentHistoryGet => "host_agent_history_get",
Self::AgentHistoryClear => "host_agent_history_clear",
Self::AgentHistoryAppend => "host_agent_history_append",
Self::FormatToolsForLlm => "host_format_tools_for_llm",
Self::ToolAllowed => "host_tool_allowed",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
Self::WritebackList => "host_writeback_list",
Self::WritebackEnsure => "host_writeback_ensure",
Self::OuterCallLine => "host_outer_call_line",
Self::SubtaskSpawn => "host_subtask_spawn",
Self::SubtaskPoll => "host_subtask_poll",
Self::SubtaskJoin => "host_subtask_join",
@@ -446,16 +418,13 @@ impl HostFn {
Self::PluginLoad => &["path"],
Self::PluginUnload | Self::PluginList => &[],
Self::ExtNativePath => &["name"],
Self::ModuleSource | Self::CallSite | Self::MarqdoSkill | Self::AgentAlloc => &[],
Self::OuterCallLine => &[],
Self::MapSet => &["map", "key", "value"],
Self::ListAppend => &["list", "item"],
Self::AgentHistoryGet | Self::AgentHistoryClear => &["id"],
Self::AgentHistoryAppend => &["id", "item"],
Self::FormatToolsForLlm => &["tools"],
Self::ToolAllowed => &["tools", "name"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
Self::WritebackEnsure => &["key"],
Self::SubtaskSpawn => &[],
Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"],
Self::SubtaskWaitAll => &[],
@@ -476,7 +445,10 @@ impl HostFn {
Self::PlotConic => &["b", "h", "k", "path", "grid"],
Self::ForeignSetCmd => &["args"],
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => &["at_end"],
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => {
&["at_end", "key", "line"]
}
Self::WritebackEnsure => &["placeholder", "line"],
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin"],
_ => &[],
}
@@ -650,40 +622,50 @@ pub fn call_host(
None => Value::None,
})
}
HostFn::ModuleSource => agent_rt::module_source(ctx),
HostFn::CallSite => {
agent_rt::call_site(ctx, Some(ctx.current_line))
}
HostFn::MarqdoSkill => agent_rt::marqdo_skill(ctx),
HostFn::MapSet => {
agent_rt::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
}
HostFn::ListAppend => {
agent_rt::list_append(require(bound, "list")?, require(bound, "item")?)
}
HostFn::AgentAlloc => agent_rt::agent_alloc(ctx),
HostFn::AgentHistoryGet => agent_rt::agent_history_get(ctx, require(bound, "id")?),
HostFn::AgentHistoryClear => {
agent_rt::agent_history_clear(ctx, require(bound, "id")?)
}
HostFn::AgentHistoryAppend => {
agent_rt::agent_history_append(ctx, require(bound, "id")?, require(bound, "item")?)
}
HostFn::FormatToolsForLlm => {
agent_rt::format_tools_for_llm(require(bound, "tools")?)
}
HostFn::ToolAllowed => agent_rt::tool_allowed(
require(bound, "tools")?,
require(bound, "name")?,
),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
.copied()
.unwrap_or(ctx.current_line) as i64,
)),
HostFn::WritebackRecord => writeback::record(
ctx,
require(bound, "value")?,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackGet => writeback::get(
ctx,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackClear => writeback::clear(
ctx,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackGet => writeback::get(ctx, bound.get("at_end")),
HostFn::WritebackClear => writeback::clear(ctx, bound.get("at_end")),
HostFn::WritebackList => writeback::list(ctx),
HostFn::WritebackEnsure => {
let placeholder = bound
.get("placeholder")
.cloned()
.unwrap_or_else(|| Value::Text("pending".into()));
writeback::ensure_slot(
ctx,
require(bound, "key")?,
&placeholder,
bound.get("line"),
)
}
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
+3 -10
View File
@@ -24,8 +24,6 @@ pub use plugin::PluginState;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::value::Value;
/// Host capability flags. Default: all enabled.
#[derive(Debug, Clone)]
pub struct HostCaps {
@@ -68,17 +66,14 @@ pub struct HostContext {
pub plots: Vec<PlotArtifact>,
/// lang → interpreter argv (from `set_cmd`).
pub foreign_cmds: HashMap<String, Vec<String>>,
/// Loaded native plugins (ABI v1).
/// Loaded native plugins (ABI v1/v2).
pub plugins: PluginState,
/// Entry `.mq.md` source text (for agent context injection).
/// Entry `.mq.md` source text (for ABI host_query / context injection).
pub entry_source: Option<String>,
pub entry_path: Option<PathBuf>,
/// Active function names (outer → inner) for call-site injection.
pub call_stack: Vec<String>,
/// Per-agent conversation history (id → turns).
pub agent_histories: HashMap<String, Vec<Value>>,
pub agent_seq: u64,
/// Last statement line (updated by interpreters for `host_call_site`).
/// Last statement line (updated by interpreters for call-site queries).
pub current_line: u32,
/// Entry-file line of each active user call (for writeback anchoring).
pub call_site_lines: Vec<u32>,
@@ -103,8 +98,6 @@ impl Default for HostContext {
entry_source: None,
entry_path: None,
call_stack: Vec::new(),
agent_histories: HashMap::new(),
agent_seq: 0,
current_line: 1,
call_site_lines: Vec::new(),
subtasks: HashMap::new(),
+1 -1
View File
@@ -117,8 +117,8 @@ pub fn http_post(
let url = as_text(url, "url")?;
let body = as_text(body, "body")?;
let ct = match content_type {
None | Some(Value::None) => "application/json; charset=utf-8",
Some(v) => as_text(v, "content_type")?,
None => "application/json; charset=utf-8",
};
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange("POST", url, Some(body), Some(ct), &hdrs)?;
+105 -5
View File
@@ -1,16 +1,21 @@
//! Native plugin loader (C ABI v1). Shared libs are not linked into marqdo.
//! Native plugin loader (C ABI v1/v2). Shared libs are not linked into marqdo.
use std::cell::Cell;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use libloading::{Library, Symbol};
use crate::host::agent_rt;
use crate::host::json::{json_to_value, value_to_json};
use crate::host::HostContext;
use crate::value::Value;
pub const ABI_VERSION: u32 = 1;
/// Highest ABI version this host speaks.
pub const ABI_VERSION: u32 = 2;
/// Oldest plugin ABI still accepted.
pub const ABI_VERSION_MIN: u32 = 1;
type PluginFn = unsafe extern "C" fn(
args_json: *const c_char,
@@ -18,6 +23,14 @@ type PluginFn = unsafe extern "C" fn(
err_msg: *mut *mut c_char,
) -> c_int;
type HostQueryFn = unsafe extern "C" fn(
userdata: *mut c_void,
name: *const c_char,
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> c_int;
type AbiVersionFn = unsafe extern "C" fn() -> u32;
type InitFn = unsafe extern "C" fn(host: *const MarqdoHostApi) -> c_int;
type ShutdownFn = unsafe extern "C" fn();
@@ -35,6 +48,12 @@ struct MarqdoHostApi {
>,
alloc: Option<unsafe extern "C" fn(n: usize) -> *mut c_void>,
free: Option<unsafe extern "C" fn(p: *mut c_void)>,
host_query: Option<HostQueryFn>,
}
thread_local! {
/// Set around plugin calls so `host_query` can read entry source / call site.
static CURRENT_HOST: Cell<*const HostContext> = const { Cell::new(std::ptr::null()) };
}
struct RegisterBuf {
@@ -88,6 +107,10 @@ impl PluginState {
names.sort();
names
}
pub fn has_fn(&self, name: &str) -> bool {
self.fns.contains_key(name)
}
}
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
@@ -112,6 +135,17 @@ unsafe extern "C" fn host_free(p: *mut c_void) {
}
}
unsafe fn host_strdup(s: &str) -> *mut c_char {
let bytes = s.as_bytes();
let p = host_alloc(bytes.len() + 1) as *mut u8;
if p.is_null() {
return std::ptr::null_mut();
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
*p.add(bytes.len()) = 0;
p as *mut c_char
}
unsafe extern "C" fn host_register(
userdata: *mut c_void,
name: *const c_char,
@@ -167,6 +201,63 @@ unsafe extern "C" fn host_register(
0
}
/// Allowlisted host introspection for ABI v2 plugins (`host_query`).
unsafe extern "C" fn host_query(
_userdata: *mut c_void,
name: *const c_char,
_args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> c_int {
let set_err = |msg: &str| {
if !err_msg.is_null() {
*err_msg = host_strdup(msg);
}
};
let set_out = |msg: &str| {
if !out_json.is_null() {
*out_json = host_strdup(msg);
}
};
if name.is_null() {
set_err("host_query: null name");
return 1;
}
let name = match CStr::from_ptr(name).to_str() {
Ok(s) => s,
Err(_) => {
set_err("host_query: name not utf-8");
return 1;
}
};
let ctx_ptr = CURRENT_HOST.with(|c| c.get());
if ctx_ptr.is_null() {
set_err("host_query: no active host context (call during plugin fn)");
return 1;
}
let ctx = &*ctx_ptr;
let result = match name {
"module_source" => agent_rt::module_source(ctx).and_then(|v| value_to_json(&v)),
"call_site" => agent_rt::call_site(ctx, Some(ctx.current_line)).and_then(|v| value_to_json(&v)),
"marqdo_skill" => agent_rt::marqdo_skill(ctx).and_then(|v| value_to_json(&v)),
other => Err(format!("host_query: unknown `{other}`")),
};
match result {
Ok(j) => {
set_out(&j.to_string());
0
}
Err(e) => {
set_err(&e);
1
}
}
}
pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_plugin() {
return Err("plugin_load denied by host policy".into());
@@ -200,9 +291,9 @@ pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
.map_err(|e| format!("plugin missing marqdo_plugin_abi_version: {e}"))?
};
let ver = unsafe { version_fn() };
if ver != ABI_VERSION {
if ver < ABI_VERSION_MIN || ver > ABI_VERSION {
return Err(format!(
"plugin ABI version {ver} != host {ABI_VERSION} ({})",
"plugin ABI version {ver} not in host range {ABI_VERSION_MIN}..={ABI_VERSION} ({})",
file.display()
));
}
@@ -221,6 +312,7 @@ pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
register_fn: Some(host_register),
alloc: Some(host_alloc),
free: Some(host_free),
host_query: Some(host_query),
};
let rc = unsafe { init_fn(&api) };
@@ -235,6 +327,10 @@ pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
for k in buf.fns.keys() {
if ctx.plugins.fns.contains_key(k) {
// Idempotent re-load of the same plugin surface (e.g. multiple `agent` ctors).
if buf.fns.keys().all(|name| ctx.plugins.fns.contains_key(name)) {
return Ok(Value::Int(0));
}
return Err(format!("plugin function `{k}` already registered"));
}
}
@@ -282,7 +378,8 @@ pub fn call_registered(
let reg = ctx
.plugins
.get(name)
.ok_or_else(|| format!("unknown function `{name}`"))?;
.ok_or_else(|| format!("unknown function `{name}`"))?
.clone();
let mut map = serde_json::Map::new();
for p in &reg.params {
@@ -299,7 +396,10 @@ pub fn call_registered(
let mut out_ptr: *mut c_char = std::ptr::null_mut();
let mut err_ptr: *mut c_char = std::ptr::null_mut();
CURRENT_HOST.with(|c| c.set(ctx as *const HostContext));
let rc = unsafe { (reg.fn_ptr)(c_args.as_ptr(), &mut out_ptr, &mut err_ptr) };
CURRENT_HOST.with(|c| c.set(std::ptr::null()));
let err_s = take_c_string(err_ptr);
let out_s = take_c_string(out_ptr);
+3 -5
View File
@@ -133,12 +133,10 @@ pub fn kill_all(ctx: &mut HostContext) {
let _ = task.stderr.join();
}
Handle::Function(mut task) => {
if let Ok(mut st) = task.state.lock() {
if matches!(*st, FnState::Running) {
*st = FnState::Killed;
}
// Join so fire-and-forget writers (e.g. agent writeback) finish before exit.
if let Some(h) = task.handle.take() {
let _ = h.join();
}
drop(task.handle.take());
}
}
}
+9 -10
View File
@@ -107,18 +107,17 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
let cmd = as_text(cmd, "cmd")?;
let mut command = Command::new(cmd);
command.current_dir(&ctx.cwd);
if let Some(a) = args {
match a {
Value::List(xs) => {
for x in xs {
command.arg(x.as_display());
}
match args {
None | Some(Value::None) => {}
Some(Value::List(xs)) => {
for x in xs {
command.arg(x.as_display());
}
Value::Text(s) => {
command.arg(s);
}
_ => return Err("exec args must be list or text".into()),
}
Some(Value::Text(s)) => {
command.arg(s);
}
Some(_) => return Err("exec args must be list or text".into()),
}
let status = command
.status()
+386 -61
View File
@@ -1,18 +1,27 @@
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
//!
//! Optional **named slots**: `<!-- marqdo-out ok -->` / `<!-- marqdo-out error -->`
//! so success and failure results do not overwrite each other.
use std::collections::HashMap;
use std::sync::Mutex;
use crate::host::HostContext;
use crate::value::Value;
const MAGIC: &str = "marqdo-out";
/// Serialize all writeback file mutations (sync + subtask writers).
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Clone, PartialEq, Eq)]
struct BlockSpan {
start: usize,
end: usize,
body: String,
start_line: u32,
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
key: Option<String>,
}
fn display_value(v: &Value) -> String {
@@ -31,6 +40,48 @@ fn is_truthy(v: Option<&Value>) -> bool {
}
}
fn opt_key(v: Option<&Value>) -> Result<Option<String>, String> {
match v {
None | Some(Value::None) => Ok(None),
Some(Value::Text(s)) => {
let t = s.trim();
if t.is_empty() {
Ok(None)
} else {
Ok(Some(normalize_slot_key(t)))
}
}
_ => Err("writeback key must be text".into()),
}
}
fn opt_line(v: Option<&Value>) -> Result<Option<u32>, String> {
match v {
None | Some(Value::None) => Ok(None),
Some(Value::Int(n)) if *n > 0 => Ok(Some(*n as u32)),
Some(Value::Text(s)) => {
let t = s.trim();
if t.is_empty() {
Ok(None)
} else {
t.parse::<u32>()
.map(|n| if n > 0 { Some(n) } else { None })
.map_err(|_| "writeback line must be a positive int".into())
}
}
_ => Err("writeback line must be a positive int".into()),
}
}
/// Canonical slot ids used by the agent framework.
fn normalize_slot_key(raw: &str) -> String {
match raw {
"ok" | "success" | "成功" => "ok".into(),
"error" | "failure" | "失败" => "error".into(),
other => other.to_string(),
}
}
fn call_line(ctx: &HostContext) -> Result<u32, String> {
ctx.call_site_lines
.last()
@@ -38,6 +89,28 @@ fn call_line(ctx: &HostContext) -> Result<u32, String> {
.ok_or_else(|| "writeback: no call site line".into())
}
/// Line that should own adjacent output cards.
/// Prefer explicit `line=`, else for keyed slots the outermost call site (`step`),
/// else the parent/current call site.
fn resolve_anchor(
ctx: &HostContext,
keyed: bool,
line: Option<&Value>,
) -> Result<u32, String> {
if let Some(n) = opt_line(line)? {
return Ok(n);
}
if keyed {
if let Some(n) = ctx.call_site_lines.first().copied() {
return Ok(n);
}
if ctx.call_site_lines.len() >= 2 {
return Ok(ctx.call_site_lines[ctx.call_site_lines.len() - 2]);
}
}
call_line(ctx)
}
fn line_number_at(source: &str, byte: usize) -> u32 {
source[..byte.min(source.len())]
.bytes()
@@ -46,8 +119,20 @@ fn line_number_at(source: &str, byte: usize) -> u32 {
+ 1
}
fn format_block(body: &str) -> String {
format!("<!-- {MAGIC}\n{body}\n-->")
fn format_block(body: &str, key: Option<&str>) -> String {
match key {
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
None => format!("<!-- {MAGIC}\n{body}\n-->"),
}
}
fn parse_header_key(header: &str) -> Option<String> {
let mut parts = header.split_whitespace();
let first = parts.next()?;
if first != MAGIC {
return None;
}
parts.next().map(normalize_slot_key)
}
fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<BlockSpan> {
@@ -66,6 +151,7 @@ fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<Block
if !header.split_whitespace().any(|t| t == MAGIC) {
return None;
}
let key = parse_header_key(header);
let body = lines.join("\n");
let end = start_byte + block.len();
Some(BlockSpan {
@@ -73,6 +159,7 @@ fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<Block
end,
body,
start_line: line_number_at(source, start_byte),
key,
})
}
@@ -109,6 +196,28 @@ fn strip_span(source: &str, start: usize, end: usize) -> String {
out
}
/// Byte end of a `<!-- … -->` span, including the single newline that terminates the `-->` line.
fn span_end_including_nl(source: &str, end: usize) -> usize {
if source.as_bytes().get(end) == Some(&b'\n') {
end + 1
} else {
end
}
}
/// Write `block` (plus a terminating newline) over `[start, end)`, preserving blank lines after.
fn splice_block(source: &str, start: usize, end: usize, block: &str) -> String {
let end = span_end_including_nl(source, end);
let mut out = String::with_capacity(source.len() + block.len() + 1);
out.push_str(&source[..start]);
out.push_str(block);
if !block.ends_with('\n') {
out.push('\n');
}
out.push_str(&source[end..]);
out
}
fn line_start_byte(source: &str, line_no: u32) -> Option<usize> {
if line_no == 0 {
return None;
@@ -154,7 +263,7 @@ fn find_adjacent_block(source: &str, after_line: u32) -> Option<BlockSpan> {
line += 1;
}
for b in scan_blocks(source) {
if b.start_line == line {
if b.start_line == line && b.key.is_none() {
return Some(b);
}
}
@@ -169,7 +278,73 @@ fn find_eof_block(source: &str) -> Option<BlockSpan> {
scan_blocks(source)
.into_iter()
.rev()
.find(|b| is_eof_block(source, b))
.find(|b| b.key.is_none() && is_eof_block(source, b))
}
fn find_keyed_block(source: &str, key: &str) -> Option<BlockSpan> {
let key = normalize_slot_key(key);
scan_blocks(source)
.into_iter()
.rev()
.find(|b| b.key.as_deref() == Some(key.as_str()))
}
/// Consecutive `marqdo-out` blocks immediately below `after_line` (blank lines allowed).
fn cluster_after_line(source: &str, after_line: u32) -> Vec<BlockSpan> {
let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let mut line = after_line.saturating_add(1);
while line <= total && is_blank_line(source, line) {
line += 1;
}
let blocks = scan_blocks(source);
let mut cluster = Vec::new();
while line <= total {
if let Some(b) = blocks.iter().find(|b| b.start_line == line) {
cluster.push(b.clone());
let end_line = line_number_at(source, b.end.saturating_sub(1).max(b.start));
line = end_line.saturating_add(1);
while line <= total && is_blank_line(source, line) {
line += 1;
}
} else {
break;
}
}
cluster
}
fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option<BlockSpan> {
let key = normalize_slot_key(key);
cluster_after_line(source, after_line)
.into_iter()
.find(|b| b.key.as_deref() == Some(key.as_str()))
}
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
let key = normalize_slot_key(key);
let block = format_block(body, Some(&key));
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
return Ok(splice_block(source, existing.start, existing.end, &block));
}
let cluster = cluster_after_line(source, anchor);
if let Some(last) = cluster.last() {
// Insert after the last block's terminating newline (or after `-->` if none).
let insert_at = span_end_including_nl(source, last.end);
let mut out = String::with_capacity(source.len() + block.len() + 1);
out.push_str(&source[..insert_at]);
if !out.ends_with('\n') {
out.push('\n');
}
out.push_str(&block);
if !block.ends_with('\n') {
out.push('\n');
}
out.push_str(&source[insert_at..]);
Ok(out)
} else {
insert_after_line(source, anchor, &block)
}
}
fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result<String, String> {
@@ -213,6 +388,24 @@ fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> {
Ok(())
}
fn load_entry_source(ctx: &HostContext) -> Result<String, String> {
if let Some(path) = &ctx.entry_path {
if let Ok(text) = std::fs::read_to_string(path) {
return Ok(text);
}
}
ctx.entry_source
.clone()
.ok_or_else(|| "writeback: no entry source".to_string())
}
fn with_writeback_lock<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
let _guard = WRITEBACK_LOCK
.lock()
.map_err(|_| "writeback lock poisoned".to_string())?;
f()
}
fn anchor_line_above(source: &str, block_start_line: u32) -> u32 {
let mut line = block_start_line.saturating_sub(1);
while line > 0 && is_blank_line(source, line) {
@@ -225,64 +418,109 @@ pub fn record(
ctx: &mut HostContext,
value: &Value,
at_end: Option<&Value>,
key: Option<&Value>,
line: Option<&Value>,
) -> Result<Value, String> {
let body = display_value(value);
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let next = if is_truthy(at_end) {
let stripped = find_eof_block(source)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string());
append_eof(&stripped, &format_block(&body))
let key = opt_key(key)?;
let at_end = is_truthy(at_end);
let anchor = if key.is_some() || !at_end {
Some(resolve_anchor(ctx, key.is_some(), line)?)
} else {
let line = call_line(ctx)?;
let stripped = find_adjacent_block(source, line)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string());
insert_after_line(&stripped, line, &format_block(&body))?
None
};
persist(ctx, &next)?;
Ok(Value::Text(body))
}
pub fn get(ctx: &HostContext, at_end: Option<&Value>) -> Result<Value, String> {
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let body = if is_truthy(at_end) {
find_eof_block(source).map(|b| b.body)
} else {
let line = call_line(ctx)?;
find_adjacent_block(source, line).map(|b| b.body)
};
Ok(match body {
Some(s) => Value::Text(s),
None => Value::None,
with_writeback_lock(|| {
let source = load_entry_source(ctx)?;
let next = if let Some(ref k) = key {
let anchor = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
replace_or_insert_keyed_at(&source, anchor, k, &body)?
} else if at_end {
let stripped = find_eof_block(&source)
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
.unwrap_or_else(|| source.clone());
append_eof(&stripped, &format_block(&body, None))
} else {
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
let stripped = find_adjacent_block(&source, line)
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
.unwrap_or_else(|| source.clone());
insert_after_line(&stripped, line, &format_block(&body, None))?
};
persist(ctx, &next)?;
Ok(Value::Text(body.clone()))
})
}
pub fn clear(ctx: &mut HostContext, at_end: Option<&Value>) -> Result<Value, String> {
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let next = if is_truthy(at_end) {
find_eof_block(source)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string())
pub fn get(
ctx: &HostContext,
at_end: Option<&Value>,
key: Option<&Value>,
line: Option<&Value>,
) -> Result<Value, String> {
let key = opt_key(key)?;
let at_end = is_truthy(at_end);
let anchor = if key.is_some() || !at_end {
resolve_anchor(ctx, key.is_some(), line).ok()
} else {
let line = call_line(ctx)?;
find_adjacent_block(source, line)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string())
None
};
if next != source {
persist(ctx, &next)?;
}
Ok(Value::None)
with_writeback_lock(|| {
let source = load_entry_source(ctx)?;
let body = if let Some(ref k) = key {
let found = anchor
.and_then(|a| find_keyed_in_cluster(&source, a, k))
.or_else(|| find_keyed_block(&source, k));
found.map(|b| b.body)
} else if at_end {
find_eof_block(&source).map(|b| b.body)
} else {
let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?;
find_adjacent_block(&source, line).map(|b| b.body)
};
Ok(match body {
Some(s) => Value::Text(s),
None => Value::None,
})
})
}
pub fn clear(
ctx: &mut HostContext,
at_end: Option<&Value>,
key: Option<&Value>,
line: Option<&Value>,
) -> Result<Value, String> {
let key = opt_key(key)?;
let at_end = is_truthy(at_end);
let anchor = if key.is_some() || !at_end {
resolve_anchor(ctx, key.is_some(), line).ok()
} else {
None
};
with_writeback_lock(|| {
let source = load_entry_source(ctx)?;
let next = if let Some(ref k) = key {
let block = anchor
.and_then(|a| find_keyed_in_cluster(&source, a, k))
.or_else(|| find_keyed_block(&source, k));
block
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
.unwrap_or_else(|| source.clone())
} else if at_end {
find_eof_block(&source)
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
.unwrap_or_else(|| source.clone())
} else {
let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?;
find_adjacent_block(&source, line)
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
.unwrap_or_else(|| source.clone())
};
if next != source {
persist(ctx, &next)?;
}
Ok(Value::None)
})
}
pub fn list(ctx: &HostContext) -> Result<Value, String> {
@@ -294,25 +532,60 @@ pub fn list(ctx: &HostContext) -> Result<Value, String> {
.into_iter()
.map(|b| {
let anchor = anchor_line_above(source, b.start_line);
let at_eof = is_eof_block(source, &b);
Value::Map(vec![
let at_eof = b.key.is_none() && is_eof_block(source, &b);
let mut entries = vec![
("line".into(), Value::Int(anchor as i64)),
("body".into(), Value::Text(b.body)),
("at_end".into(), Value::Bool(at_eof)),
])
];
if let Some(k) = b.key {
entries.push(("key".into(), Value::Text(k)));
}
Value::Map(entries)
})
.collect();
Ok(Value::List(items))
}
/// Map statement line → body for adjacent blocks; EOF blocks use key `0`.
/// Ensure named slots exist with a placeholder body; **does not** overwrite non-empty bodies.
pub fn ensure_slot(
ctx: &mut HostContext,
key: &Value,
placeholder: &Value,
line: Option<&Value>,
) -> Result<Value, String> {
let k = opt_key(Some(key))?.ok_or_else(|| "writeback ensure needs key".to_string())?;
let body = display_value(placeholder);
let anchor = resolve_anchor(ctx, true, line)?;
with_writeback_lock(|| {
let source = load_entry_source(ctx)?;
if find_keyed_in_cluster(&source, anchor, &k).is_some() {
return Ok(Value::Bool(false));
}
let next = replace_or_insert_keyed_at(&source, anchor, &k, &body)?;
persist(ctx, &next)?;
Ok(Value::Bool(true))
})
}
/// Map statement line → body for adjacent blocks (keyed slots included under their anchor).
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
let mut map = HashMap::new();
for b in scan_blocks(source) {
if is_eof_block(source, &b) {
map.insert(0, b.body);
let anchor = anchor_line_above(source, b.start_line);
let piece = match &b.key {
Some(k) => format!("[{k}]\n{}", b.body),
None => b.body.clone(),
};
if b.key.is_none() && is_eof_block(source, &b) {
map.insert(0, piece);
} else {
map.insert(anchor_line_above(source, b.start_line), b.body);
map.entry(anchor)
.and_modify(|e| {
e.push_str("\n\n");
e.push_str(&piece);
})
.or_insert(piece);
}
}
map
@@ -325,7 +598,7 @@ mod tests {
#[test]
fn parse_and_insert_adjacent() {
let src = "# main\n\n*`x` = 1*\n";
let block = format_block("1");
let block = format_block("1", None);
let next = insert_after_line(src, 3, &block).unwrap();
assert!(next.contains("marqdo-out"));
assert!(!next.contains("@line"));
@@ -342,4 +615,56 @@ mod tests {
let map = writeback_map(src);
assert_eq!(map.get(&3), Some(&"42".to_string()));
}
#[test]
fn keyed_slots_sit_under_anchor_and_do_not_clobber() {
let src = "# main\n\n*`r` = > step *\n\n> print text=after\n";
let with_ok = replace_or_insert_keyed_at(src, 3, "ok", "success-1").unwrap();
let with_both = replace_or_insert_keyed_at(&with_ok, 3, "error", "fail-1").unwrap();
let step_at = with_both.find("`r` = > step").unwrap();
let ok_at = with_both.find("marqdo-out ok").unwrap();
let err_at = with_both.find("marqdo-out error").unwrap();
let after_at = with_both.find("> print text=after").unwrap();
assert!(ok_at > step_at && ok_at < after_at);
assert!(err_at > ok_at && err_at < after_at);
let updated = replace_or_insert_keyed_at(&with_both, 3, "error", "fail-2").unwrap();
assert!(updated.contains("success-1"));
assert!(updated.contains("fail-2"));
assert!(!updated.contains("fail-1"));
}
#[test]
fn keyed_replace_does_not_accumulate_blank_lines() {
let src = "# main\n\n> writeback.record\n<!-- marqdo-out ok\nold\n-->\n\n2. *\n";
let once = replace_or_insert_keyed_at(src, 3, "ok", "new-1").unwrap();
let twice = replace_or_insert_keyed_at(&once, 3, "ok", "new-2").unwrap();
let thrice = replace_or_insert_keyed_at(&twice, 3, "ok", "new-3").unwrap();
assert_eq!(once.matches("\n\n\n").count(), src.matches("\n\n\n").count());
assert_eq!(twice, thrice.replace("new-3", "new-2"));
// Exactly one blank line between `-->` and the next statement.
let after = thrice.split("-->\n").nth(1).unwrap();
assert!(after.starts_with("\n2. *"), "got after -->: {after:?}");
assert!(!after.starts_with("\n\n\n"), "blank lines accumulated");
}
#[test]
fn unkeyed_replace_does_not_accumulate_blank_lines() {
let src = "# main\n\n*`x` = 1*\n<!-- marqdo-out\nold\n-->\n\n> print text=tail\n";
let line = 3u32;
let strip_insert = |s: &str, body: &str| {
let stripped = find_adjacent_block(s, line)
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
.unwrap_or_else(|| s.to_string());
insert_after_line(&stripped, line, &format_block(body, None)).unwrap()
};
let once = strip_insert(src, "a");
let twice = strip_insert(&once, "b");
let thrice = strip_insert(&twice, "c");
assert_eq!(
once.matches("\n\n\n").count(),
thrice.matches("\n\n\n").count()
);
let after = thrice.split("-->\n").nth(1).unwrap();
assert!(after.starts_with("\n> print"), "got after -->: {after:?}");
}
}
+101 -8
View File
@@ -446,11 +446,13 @@ impl Interpreter {
call: &CallExpr,
) -> Result<Value> {
let mut call = call.clone();
let callee = crate::aliases::normalize_call_callee_and_args(
&call.callee,
&mut call.args,
);
call.callee = callee;
if call.path.is_none() {
let callee = crate::aliases::normalize_call_callee_and_args(
&call.callee,
&mut call.args,
);
call.callee = callee;
}
let mut ev_args = Vec::new();
for arg in &call.args {
@@ -471,6 +473,14 @@ impl Interpreter {
return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args);
}
if let Some(path) = &call.path {
return self.eval_path_call(module, path, &ev_args);
}
if let Some(u) = module.uses.iter().find(|u| u.bind == call.callee) {
return self.eval_path_call(module, &u.path, &ev_args);
}
match call.callee.as_str() {
"print" => {
let bound = bind_args(&["text".into()], &ev_args, false)
@@ -637,6 +647,73 @@ impl Interpreter {
}
}
/// Resolve bare path `lib.member` / `lib.Type.member` (definition-tree addressing).
fn eval_path_call(
&mut self,
module: &Module,
path: &[String],
ev_args: &[EvArg],
) -> Result<Value> {
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() {
return Err(self.err(format!(
"`{display}` is an instance method; call it as `var`.{}",
node.name
)));
}
let bound = {
let mut dummy_env = Env::new();
bind_function_args(
self,
lib,
node,
&mut dummy_env,
&node.params,
ev_args,
false,
)
.map_err(|m| self.err(m))?
};
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, &[]);
self.host.pop_call_site_line();
let result = result?;
if node.is_object() {
Ok(tag_instance(&node.name, result))
} else {
Ok(result)
}
}
fn eval_method_call(
&mut self,
module: &Module,
@@ -651,8 +728,7 @@ impl Interpreter {
.cloned()
.ok_or_else(|| self.err(format!("undefined variable `{recv_name}`")))?;
let type_name = instance_type_name(&recv).map_err(|m| self.err(m))?;
let obj = find_top(module, &type_name)
.filter(|f| f.is_object())
let (owner, obj) = find_object_type(module, &type_name)
.ok_or_else(|| self.err(format!("unknown object type `{type_name}`")))?;
let target = obj
.children
@@ -668,7 +744,7 @@ impl Interpreter {
call_env.set("自".into(), recv.clone());
call_env.set("self".into(), recv);
self.host.push_call_site_line(self.host.current_line);
let result = self.run_function(module, target, call_env, &[]);
let result = self.run_function(owner, target, call_env, &[]);
self.host.pop_call_site_line();
result
}
@@ -821,6 +897,23 @@ 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.
fn find_object_type<'a>(module: &'a Module, name: &str) -> Option<(&'a Module, &'a Function)> {
module
.functions
.iter()
.find(|f| f.name == name && f.is_object())
.map(|f| (module, f))
.or_else(|| {
module.import_modules.values().find_map(|lib| {
lib.functions
.iter()
.find(|f| f.name == name && f.is_object())
.map(|f| (lib, f))
})
})
}
fn find_function_anywhere<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
for f in &module.functions {
if f.name == name {
+77 -79
View File
@@ -1,6 +1,6 @@
//! Load `.mq.md` files and merge frontmatter imports.
//! Load `.mq.md` files and bind frontmatter imports as library modules.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::{Path, PathBuf};
@@ -11,7 +11,7 @@ use crate::diagnostics::Diagnostic;
use crate::embedded_lib;
use crate::parse::parse_source;
/// Load `path` and recursively merge imported modules' top-level functions.
/// Load `path` and recursively bind imported modules (no flat merge).
pub fn load_module(path: &Path) -> Result<Module> {
let mut visited = HashSet::new();
load_module_inner(path, &mut visited)
@@ -25,21 +25,33 @@ fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Modu
bail!("circular import involving {}", path.display());
}
let source = read_module_source(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let mut module = parse_source(&source).map_err(|e| attach_path(path, e))?;
let result = (|| {
let source = read_module_source(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let mut module = parse_source(&source).map_err(|e| attach_path(path, e))?;
let base = path.parent().unwrap_or_else(|| Path::new("."));
let imports = module.imports.clone();
for rel in imports {
let dep_path = resolve_import(base, &rel)?;
let dep = load_module_inner(&dep_path, visited)?;
for fun in dep.functions {
merge_top_level(&mut module.functions, fun);
let base = path.parent().unwrap_or_else(|| Path::new("."));
let imports = module.imports.clone();
let mut import_modules = HashMap::new();
for imp in imports {
let dep_path = resolve_import(base, &imp.path)?;
let dep = load_module_inner(&dep_path, visited)?;
if import_modules.contains_key(&imp.bind) {
bail!(
"duplicate import bind `{}` while loading {}",
imp.bind,
path.display()
);
}
import_modules.insert(imp.bind, dep);
}
}
module.import_modules = import_modules;
Ok(module)
Ok(module)
})();
visited.remove(&canon);
result
}
fn read_module_source(path: &Path) -> Result<String> {
@@ -80,49 +92,47 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
if direct.is_file() {
return Ok(direct);
}
let normalized = if let Some(rest) = rel.strip_prefix("std/") {
format!("lib/{rest}")
} else {
rel.clone()
};
if let Some(remainder) = normalized.strip_prefix("lib/") {
if let Some(source) = read_embedded_for_path(Path::new(&rel)) {
let _ = source;
// Prefer real file under search roots; else return a virtual lib/ path for embedded read.
}
if rel.starts_with("lib/") || rel.starts_with("std/") {
let rest = rel
.strip_prefix("lib/")
.or_else(|| rel.strip_prefix("std/"))
.unwrap();
for root in lib_search_roots() {
let as_lib_dir = root.join(remainder);
if as_lib_dir.is_file() {
return Ok(as_lib_dir);
}
let as_repo_root = root.join("lib").join(remainder);
if as_repo_root.is_file() {
return Ok(as_repo_root);
let p = root.join(rest);
if p.is_file() {
return Ok(p);
}
}
if embedded_lib::has_file(remainder) {
return Ok(PathBuf::from("lib").join(remainder));
}
bail!(
"cannot resolve library import `{rel}` (set MARQDO_LIB, keep lib/ next to the project, or use a binary with embedded stdlib)"
);
// Embedded stdlib: synthesize a path under lib/ for read_module_source.
return Ok(PathBuf::from("lib").join(rest));
}
if let Some(remainder) = normalized.strip_prefix("ext/") {
if rel.starts_with("ext/") {
for root in ext_search_roots() {
let as_ext_dir = root.join(remainder);
if as_ext_dir.is_file() {
return Ok(as_ext_dir);
let p = root.join(rel.strip_prefix("ext/").unwrap_or(&rel));
// also try full ext/rel under root
let p2 = root.join(&rel);
if p.is_file() {
return Ok(p);
}
let as_repo_root = root.join("ext").join(remainder);
if as_repo_root.is_file() {
return Ok(as_repo_root);
if p2.is_file() {
return Ok(p2);
}
// MARQDO_EXT is the ext root itself (contains ai/)
let under = root.join(rel.strip_prefix("ext/").unwrap());
if under.is_file() {
return Ok(under);
}
}
bail!(
"cannot resolve extension import `{rel}` (set MARQDO_EXT or keep an ext/ next to the project)"
);
}
Ok(direct)
// Relative again with normalize
if direct.exists() {
return Ok(direct);
}
bail!("cannot resolve import `{rel}` from {}", from_dir.display())
}
fn lib_search_roots() -> Vec<PathBuf> {
@@ -132,16 +142,17 @@ fn lib_search_roots() -> Vec<PathBuf> {
}
if let Ok(cwd) = env::current_dir() {
roots.push(cwd.join("lib"));
roots.push(cwd);
}
if let Ok(exe) = env::current_exe() {
if let Some(dir) = exe.parent() {
roots.push(dir.join("lib"));
roots.push(dir.join("../lib"));
roots.push(dir.join("../../lib"));
roots.push(dir.join("../../../lib"));
roots.push(dir.join("..").join("lib"));
roots.push(dir.join("..").join("..").join("lib"));
}
}
if let Ok(manifest) = env::var("CARGO_MANIFEST_DIR") {
roots.push(PathBuf::from(manifest).join("lib"));
}
roots
}
@@ -150,41 +161,36 @@ fn ext_search_roots() -> Vec<PathBuf> {
if let Ok(h) = env::var("MARQDO_EXT") {
roots.push(PathBuf::from(h));
}
// Official installer default (`marqdo ext add`)
roots.push(crate::ext_cli::default_user_ext_dir());
if let Ok(cwd) = env::current_dir() {
roots.push(cwd.join("ext"));
roots.push(cwd);
}
if let Ok(exe) = env::current_exe() {
if let Some(dir) = exe.parent() {
roots.push(dir.join("ext"));
roots.push(dir.join("../ext"));
roots.push(dir.join("../../ext"));
roots.push(dir.join("../../../ext"));
roots.push(dir.join("..").join("ext"));
roots.push(dir.join("..").join("..").join("ext"));
}
}
if let Ok(manifest) = env::var("CARGO_MANIFEST_DIR") {
roots.push(PathBuf::from(manifest).join("ext"));
}
roots
}
fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
if let Some(d) = err.downcast_ref::<Diagnostic>() {
if d.path.is_none() {
return Diagnostic::at(path, d.span, d.message.clone()).into();
}
return err;
}
let msg = err.to_string();
if let Some((loc, rest)) = msg.split_once(": ") {
if let Some((line_s, col_s)) = loc.split_once(':') {
if let (Ok(line), Ok(col)) = (line_s.parse::<u32>(), col_s.parse::<u32>()) {
return Diagnostic::at(path, crate::diagnostics::Span::new(line, col), rest).into();
match err.downcast::<Diagnostic>() {
Ok(mut d) => {
if d.path.is_none() {
d.path = Some(path.to_path_buf());
}
d.into()
}
Err(e) => anyhow::anyhow!("{}: {e}", path.display()),
}
err.context(format!("in {}", path.display()))
}
/// Kept for tests / tooling that expect a flat list (local tops only).
#[allow(dead_code)]
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
*existing = fun;
@@ -209,12 +215,4 @@ mod tests {
let p2 = resolve_import(Path::new("tests/keywords"), "std/text.mq.md").unwrap();
assert!(p2.ends_with("text.mq.md"));
}
#[test]
fn resolve_embedded_lib_source() {
let p = resolve_import(Path::new("/nonexistent"), "lib/writeback.mq.md").unwrap();
assert!(p.to_string_lossy().replace('\\', "/").contains("lib/writeback.mq.md"));
let src = read_module_source(&p).unwrap();
assert!(src.contains("host_writeback"));
}
}
+25 -4
View File
@@ -433,7 +433,7 @@ fn is_word_end(s: &str, len: usize) -> bool {
}
/// Parse `name key=val …` / positional args; returns call + bytes consumed.
/// Callee may be a bare name or method form `` `recv`.method ``.
/// Callee may be a bare name, library path `time.parse`, or method `` `recv`.method ``.
pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
use crate::ast::Arg;
@@ -448,9 +448,14 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
.to_string()
};
let (receiver, callee) = split_method_callee(&callee_tok)
.map(|(r, m)| (Some(r), m))
.unwrap_or((None, callee_tok.clone()));
let (receiver, callee, path) = if let Some((r, m)) = split_method_callee(&callee_tok) {
(Some(r), m, None)
} else if let Some(segments) = split_lib_path_callee(&callee_tok) {
let last = segments.last().cloned().unwrap_or_default();
(None, last, Some(segments))
} else {
(None, callee_tok.clone(), None)
};
let after_callee_offset = {
let idx = s.find(&callee_tok).unwrap();
@@ -486,6 +491,7 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
Ok((
CallExpr {
callee,
path,
receiver,
args,
},
@@ -512,6 +518,21 @@ fn split_method_callee(tok: &str) -> Option<(String, String)> {
Some((recv, method.to_string()))
}
/// Bare `time.parse` / `agent.agent` → path segments (len ≥ 2).
fn split_lib_path_callee(tok: &str) -> Option<Vec<String>> {
if tok.starts_with('`') || !tok.contains('.') {
return None;
}
let parts: Vec<String> = tok.split('.').map(|s| s.to_string()).collect();
if parts.len() < 2 {
return None;
}
if parts.iter().any(|p| p.is_empty() || p.contains('`')) {
return None;
}
Some(parts)
}
/// If `s` begins with `ident=`, return (ident, rest_after_eq).
fn try_named_arg(s: &str) -> Option<(String, &str)> {
let s = s.trim_start();
+133 -11
View File
@@ -7,7 +7,7 @@ pub use expr::{parse_call_after_gt, parse_expr, parse_value_or_interp};
use anyhow::{bail, Result};
use crate::ast::{
BranchArm, Expr, Function, Literal, Module, Stmt,
BranchArm, Expr, Function, Import, Literal, Module, Stmt, Use,
};
use crate::diagnostics::{Diagnostic, Span};
use crate::lex::{classify_source, ClassifiedLine, LineKind};
@@ -22,7 +22,7 @@ pub fn parse_source(source: &str) -> Result<Module> {
pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
let mut cur = Cursor::new(lines);
let imports = cur.parse_frontmatter()?;
let (imports, uses) = cur.parse_frontmatter()?;
let mut functions = Vec::new();
while cur.skip_noise() {
let Some(line) = cur.peek() else { break };
@@ -36,7 +36,20 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
);
}
}
Ok(Module { imports, functions })
for u in &uses {
if imports.iter().any(|i| i.bind == u.bind) {
bail!("use bind `{}` conflicts with import library name", u.bind);
}
if functions.iter().any(|f| f.name == u.bind) {
bail!("use bind `{}` conflicts with top-level name", u.bind);
}
}
Ok(Module {
imports,
uses,
functions,
import_modules: std::collections::HashMap::new(),
})
}
struct Cursor<'a> {
@@ -72,16 +85,17 @@ impl<'a> Cursor<'a> {
false
}
fn parse_frontmatter(&mut self) -> Result<Vec<String>> {
fn parse_frontmatter(&mut self) -> Result<(Vec<Import>, Vec<Use>)> {
let mut imports = Vec::new();
let mut uses = Vec::new();
if !self.skip_noise() {
return Ok(imports);
return Ok((imports, uses));
}
let Some(first) = self.peek() else {
return Ok(imports);
return Ok((imports, uses));
};
if first.text.trim() != "---" {
return Ok(imports);
return Ok((imports, uses));
}
self.bump();
while let Some(line) = self.peek() {
@@ -91,14 +105,26 @@ impl<'a> Cursor<'a> {
break;
}
if t.starts_with('>') {
let path = t[1..].trim();
if path.ends_with(".mq.md") {
imports.push(path.to_string());
let rest = t[1..].trim();
if let Some(imp) = parse_import_spec(rest) {
if imports.iter().any(|i| i.bind == imp.bind) {
bail!(
"{}:1: duplicate import bind `{}`",
line.line_no,
imp.bind
);
}
imports.push(imp);
} else if let Some(u) = parse_use_spec(rest) {
if uses.iter().any(|x| x.bind == u.bind) {
bail!("{}:1: duplicate use bind `{}`", line.line_no, u.bind);
}
uses.push(u);
}
}
self.bump();
}
Ok(imports)
Ok((imports, uses))
}
fn parse_function(&mut self, min_level: u8) -> Result<Function> {
@@ -694,6 +720,102 @@ fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
Some((level, name))
}
/// Parse `lib/time.mq.md` / `lib/time.mq.md as time` / `lib/时间.mq.md 作为 时间`.
pub fn parse_import_spec(rest: &str) -> Option<Import> {
let rest = rest.trim();
const SUFFIX: &str = ".mq.md";
let idx = rest.find(SUFFIX)?;
let path = rest[..idx + SUFFIX.len()].trim().to_string();
if !path.ends_with(SUFFIX) {
return None;
}
let after = rest[idx + SUFFIX.len()..].trim();
let bind = if after.is_empty() {
default_import_bind(&path)
} else if let Some(name) = after.strip_prefix("as") {
let name = name.trim();
if name.is_empty() || name.split_whitespace().count() != 1 {
return None;
}
name.to_string()
} else if let Some(name) = after.strip_prefix("作为") {
let name = name.trim();
if name.is_empty() || name.split_whitespace().count() != 1 {
return None;
}
name.to_string()
} else {
return None;
};
Some(Import { path, bind })
}
fn default_import_bind(path: &str) -> String {
let path = path.replace('\\', "/");
let file = path.rsplit('/').next().unwrap_or(path.as_str());
file.strip_suffix(".mq.md").unwrap_or(file).to_string()
}
/// Parse `use time.format` / `use time.format as fmt` / `使用 时间.格式化` / `使用 时间.格式化 作为 fmt`.
pub fn parse_use_spec(rest: &str) -> Option<Use> {
let rest = rest.trim();
let after = if rest.starts_with("use")
&& rest
.get(3..)
.is_some_and(|s| s.starts_with(|c: char| c.is_whitespace()))
{
rest[3..].trim()
} else if let Some(a) = rest.strip_prefix("使用") {
let a = a.trim();
if a.is_empty() {
return None;
}
a
} else {
return None;
};
if after.is_empty() {
return None;
}
let (path_str, bind_opt) = if let Some((left, right)) = after.split_once(" as ") {
(left.trim(), Some(right.trim()))
} else if let Some((left, right)) = after.split_once(" 作为 ") {
(left.trim(), Some(right.trim()))
} else if let Some((left, right)) = after.split_once("作为") {
let left = left.trim();
let right = right.trim();
if left.is_empty() || right.is_empty() {
(after, None)
} else {
(left, Some(right))
}
} else {
(after, None)
};
if path_str.is_empty() || path_str.contains('`') {
return None;
}
let path: Vec<String> = path_str
.split('.')
.map(|s| s.trim().to_string())
.collect();
if path.len() < 2 || path.iter().any(|p| p.is_empty()) {
return None;
}
let bind = match bind_opt {
Some(b) => {
if b.is_empty() || b.split_whitespace().count() != 1 || b.contains('.') {
return None;
}
b.to_string()
}
None => path.last()?.clone(),
};
Some(Use { path, bind })
}
fn is_heading(trimmed: &str) -> bool {
parse_heading(trimmed).is_some()
}
+15 -2
View File
@@ -174,7 +174,16 @@ pub fn render_module_structure_mode(
if !module.imports.is_empty() {
out.push_str("<div class=\"card\"><span class=\"badge\">import</span>");
for imp in &module.imports {
out.push_str(&format!("<span class=\"chip\">{}</span>", escape(imp)));
let label = format!("{} as {}", imp.path, imp.bind);
out.push_str(&format!("<span class=\"chip\">{}</span>", escape(&label)));
}
out.push_str("</div>");
}
if !module.uses.is_empty() {
out.push_str("<div class=\"card\"><span class=\"badge\">use</span>");
for u in &module.uses {
let label = format!("{} as {}", u.path.join("."), u.bind);
out.push_str(&format!("<span class=\"chip\">{}</span>", escape(&label)));
}
out.push_str("</div>");
}
@@ -606,8 +615,12 @@ fn call_display(call: &CallExpr) -> String {
s.push_str(recv);
s.push('`');
s.push('.');
s.push_str(&call.callee);
} else if let Some(path) = &call.path {
s.push_str(&path.join("."));
} else {
s.push_str(&call.callee);
}
s.push_str(&call.callee);
for a in &call.args {
match a {
Arg::Positional(e) => {