feat(ext): single callable binding, provider v2 CLI, capability handlers, stdlib aliases

Implements RFC-EXT-0001 PR-00..PR-07 first pass:
- CallSiteKey/CallBindingTable + one frontend binding pass; runtime dispatch by identity
- prepare composition root shared by check/run/inspect/Analysis; exact plugin reconciliation
- provider.json v2 --provider/--allow-provider worker CLI with fail-closed verification
- capability handler registry with real fs.read and audit
- verified stdlib public aliases replace print_override/AST scan
- docs: specs, ADR-0054/0055/0057/0058, README, CI/release gates, evidence

PR-04 extension selection/lock v4 and final frozen-binary evidence remain.
This commit is contained in:
cflmy committed 2026-11-22 00:17:36 +08:00
1 parent 9aa536c2c9
commit 1f6fd644a0
54 files changed
+8710 -828

No files matched your search

+122
View File
@@ -272,3 +272,125 @@ fn walk_rs(root: &Path) -> Vec<PathBuf> {
}
files
}
/// RFC-EXT-0001 §4/§14: the runtime must dispatch by the prepared binding and
/// never re-resolve a name or special-case a print function.
#[test]
fn callable_binding_is_the_only_static_resolution_path() {
let root = repo_root();
let loader = read(&root.join("crates/cli/src/loader.rs"));
let interpreter = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
let run = read(&root.join("crates/cli/src/commands/run.rs"));
let frontend = read(&root.join("crates/marqdo-frontend/src/calls.rs"));
assert!(
!loader.contains("program_uses_print"),
"loader must not scan for per-function names (ADR-0058)"
);
assert!(
!interpreter.contains("print_override"),
"the runtime must not special-case print (ADR-0054/0058)"
);
assert!(
!interpreter.contains("external_callables.is_empty"),
"the runtime must not fall back to plugin guessing (ADR-0054)"
);
assert!(
interpreter.contains("call_bindings.get"),
"the runtime must dispatch by the prepared call binding table"
);
assert!(
!interpreter.contains("builtins::find(&qualified)"),
"a qualified name must not be re-resolved at run time"
);
assert!(
!run.contains("external_callables")
|| !run.contains("external_callables")
|| !run.contains("push(marqdo_ir::callable::CallableDescriptor"),
"run must not synthesise plugin descriptors (ADR-0054/§4.5)"
);
assert!(
frontend.contains("bind_program_calls"),
"the frontend must expose the single binding entry point"
);
}
/// RFC-EXT-0001 §14.2/S4: no business-domain builtin or host-op branch may be
/// added for an ecosystem feature. These must be implemented as `.mq.md`,
/// plugin exports or provider streams.
#[test]
fn no_business_domain_builtins_or_host_ops() {
let root = repo_root();
let builtins = read(&root.join("crates/marqdo-ir/src/builtins.rs"));
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
for forbidden in ["quantum.", "ai.chat", "vendor.", "demo.sensor", "marqdo."] {
assert!(
!builtins.contains(forbidden),
"business builtin namespace `{forbidden}` must not exist"
);
}
assert!(
!host.contains("\"demo.sensor\""),
"provider kinds must be data, not host-op string branches"
);
}
/// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not
/// hard-coded runtime names. Recompute the canonical metadata digest.
#[test]
fn official_stdlib_public_aliases_are_verified_metadata() {
let root = repo_root().join("stdlib");
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
let aliases = manifest["public_aliases"]
.as_array()
.expect("stdlib.json must declare public_aliases");
assert!(!aliases.is_empty());
let mut hasher = Sha256::new();
let mut entries: Vec<&serde_json::Value> = aliases.iter().collect();
entries.sort_by_key(|alias| {
(
alias["target_module"].as_str().unwrap_or("").to_string(),
alias["target_function"].as_str().unwrap_or("").to_string(),
)
});
for alias in &entries {
hasher.update(alias["target_module"].as_str().unwrap().as_bytes());
hasher.update([0]);
hasher.update(alias["target_function"].as_str().unwrap().as_bytes());
hasher.update([0]);
let mut names: Vec<&str> = alias["public_names"]
.as_array()
.unwrap()
.iter()
.filter_map(serde_json::Value::as_str)
.collect();
names.sort();
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
}
let actual = format!("sha256:{}", hex(&hasher.finalize()));
assert_eq!(
manifest["aliases_digest"], actual,
"stdlib.json aliases_digest must cover the public alias table"
);
for alias in aliases {
let target_module = alias["target_module"].as_str().unwrap();
let target_function = alias["target_function"].as_str().unwrap();
let module = read(&root.join(target_module));
assert!(
module.contains(&format!("## {target_function}")),
"public alias target `{target_module}::{target_function}` must exist"
);
}
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
+653
View File
@@ -0,0 +1,653 @@
//! Black-box callable resolution / binding conformance (RFC-EXT-0001 §4.6).
//!
//! Every test drives the real `marqdo` binary through the public CLI. The
//! point is to prove that `check` and `run` share one static resolution and
//! that the runtime never guesses a plugin from a dotted string prefix.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-callable-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn write(path: &Path, text: &str) {
std::fs::write(path, text).unwrap();
}
fn library_name() -> &'static str {
if cfg!(target_os = "macos") {
"solver.dylib"
} else {
"solver.so"
}
}
fn shared_flags() -> &'static [&'static str] {
if cfg!(target_os = "macos") {
&["-dynamiclib", "-fPIC"]
} else {
&["-shared", "-fPIC"]
}
}
fn have_cc() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn compile_plugin(dir: &Path, extra: &[&str]) -> PathBuf {
let output = dir.join(library_name());
let status = Command::new("cc")
.args(["-std=c11", "-O2"])
.args(shared_flags())
.arg("-I")
.arg(repo().join("include"))
.args(extra)
.arg(repo().join("examples/plugin-demo/solver.c"))
.arg("-o")
.arg(&output)
.status()
.expect("cc");
assert!(status.success(), "cc failed");
output
}
fn write_worker_manifest(dir: &Path, artifact: &Path, exports: &str) {
let sha = sha256_file(artifact).unwrap();
write(
&dir.join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.solver
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
{exports} requires:
- math.compute
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
}
fn add_export(name: &str, signature: &str) -> String {
format!(" - name: {name}\n signature: \"{signature}\"\n")
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
// CALL-01
#[test]
fn import_alias_conflicting_with_builtin_namespace_is_rejected() {
let dir = TempDir::new("call01");
write(
&dir.path().join("math.mq.md"),
"## @exec eval\n\n`params(a: Int)`\n\n`return a + 100`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n math: \"./math.mq.md\"\n---\n\n## @exec main\n\n`return math.eval(a=1)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.import_namespace_conflict"),
"{}",
stderr(&check)
);
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1));
assert!(stdout(&run).is_empty());
assert!(
stderr(&run).contains("ext.import_namespace_conflict"),
"{}",
stderr(&run)
);
}
// CALL-02
#[test]
fn dotted_builtin_call_binds_without_an_import() {
let output = cli(&["check", "examples/math.mq.md"], &repo());
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let run = cli(&["call", "examples/math.mq.md", "计算圆面积"], &repo());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
// CALL-03
#[test]
fn renamed_import_alias_binds_the_module_function() {
let dir = TempDir::new("call03");
write(
&dir.path().join("math.mq.md"),
"## @exec eval\n\n`params(a: Int)`\n\n`return a + 100`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n mymath: \"./math.mq.md\"\n---\n\n## @exec main\n\n`return mymath.eval(a=1)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "101"})
);
}
// CALL-04 / CALL-05
#[test]
fn unknown_plugin_export_is_a_static_symbol_error() {
let dir = TempDir::new("call04");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1));
assert!(
stderr(&check).contains("symbol.unknown"),
"{}",
stderr(&check)
);
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1));
assert!(stderr(&run).contains("symbol.unknown"), "{}", stderr(&run));
assert!(stdout(&run).is_empty());
// CALL-05: the diagnostic does not change when an unrelated plugin is
// loaded, because the static export table is still the only source.
if !have_cc() {
return;
}
let plugin_dir = TempDir::new("call05-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.subtract(a=1, b=2)`\n",
);
let with_plugin = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(with_plugin.status.code(), Some(1));
assert!(
stderr(&with_plugin).contains("symbol.unknown"),
"{}",
stderr(&with_plugin)
);
}
// CALL-06
#[test]
fn plugin_with_two_prefixes_binds_both_exports() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call06");
let plugin_dir = TempDir::new("call06-plugin");
let artifact = compile_plugin(plugin_dir.path(), &["-DMQ_SOLVER_MULTI_EXPORT"]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&(add_export("solver.add", "($a: Int, $b: Int) -> Int")
+ &add_export("solver.neg", "($a: Int) -> Int")),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`和 = solver.add(20, b=22)`\n\n`相反数 = solver.neg(7)`\n\n`打印(和)`\n\n`打印(相反数)`\n",
);
let output = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
assert_eq!(stdout(&output), "42\n-7\n");
}
// CALL-07
#[test]
fn duplicate_complete_export_across_plugins_is_rejected_at_prepare() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call07");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let mut plugins = Vec::new();
for tag in ["a", "b"] {
let plugin_dir = TempDir::new(tag);
let artifact = compile_plugin(plugin_dir.path(), &[]);
let sha = sha256_file(&artifact).unwrap();
write(
&plugin_dir.path().join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.{tag}.solver
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: solver.add
signature: "($a: Int, $b: Int) -> Int"
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
plugins.push(plugin_dir);
}
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugins[0].path().to_str().unwrap(),
"--plugin",
plugins[1].path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(2), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.duplicate_callable"),
"{}",
stderr(&check)
);
}
// CALL-08
#[test]
fn bad_plugin_arguments_fail_in_check_and_run_identically() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call08");
let plugin_dir = TempDir::new("call08-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
for (tag, call) in [
("missing", "solver.add(a=1)"),
("unknown", "solver.add(a=1, b=2, c=3)"),
("duplicate", "solver.add(a=1, a=2, b=3)"),
("too-many-positional", "solver.add(1, 2, 3)"),
] {
write(
&dir.path().join("index.mq.md"),
&format!("## @exec main\n\n`return {call}`\n"),
);
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(1), "{tag}: {}", stderr(&check));
let expected = if tag == "duplicate" {
// The expression grammar rejects duplicate named arguments before
// call binding; either way the failure is static.
"sem.syntax"
} else {
"call.arity"
};
assert!(
stderr(&check).contains(expected),
"{tag}: {}",
stderr(&check)
);
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(1), "{tag}: {}", stderr(&run));
assert!(stdout(&run).is_empty(), "{tag}");
// `check` appends a summary line and `run` a refusal line, but the
// structured call.arity diagnostic itself must be identical.
let arity = |text: &str| {
text.lines()
.filter(|line| line.contains("call.arity") || line.contains("sem.syntax"))
.map(ToString::to_string)
.collect::<Vec<_>>()
};
assert!(!arity(&stderr(&check)).is_empty(), "{tag}");
assert_eq!(
arity(&stderr(&check)),
arity(&stderr(&run)),
"{tag}: check != run"
);
}
}
// CALL-09
#[test]
fn changed_artifact_digest_is_rejected_before_main_runs() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call09");
let plugin_dir = TempDir::new("call09-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(\"must-not-run\")`\n\n`return solver.add(a=1, b=2)`\n",
);
// Static check succeeds: it never opens the artifact.
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
// Corrupt the artifact bytes; run must reject before the entry function.
let mut bytes = std::fs::read(&artifact).unwrap();
bytes.push(0);
std::fs::write(&artifact, bytes).unwrap();
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(1), "{}", stderr(&run));
assert!(
stderr(&run).contains("ext.artifact_integrity"),
"{}",
stderr(&run)
);
assert!(stdout(&run).is_empty(), "{}", stdout(&run));
}
// CALL-11
#[test]
fn local_function_reference_is_a_dynamic_language_call() {
let dir = TempDir::new("call11");
write(
&dir.path().join("index.mq.md"),
"## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n",
);
let run = cli(&["call", "index.mq.md", "主", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "16"})
);
}
// CALL-12
#[test]
fn calling_a_text_value_is_not_callable_and_never_reaches_the_host() {
let dir = TempDir::new("call12");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`f = \"text\"`\n\n`return f()`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1), "{}", stderr(&run));
assert!(
stderr(&run).contains("call.not_callable") || stderr(&run).contains("not_callable"),
"{}",
stderr(&run)
);
}
// CALL-13
#[test]
fn explicit_import_aliases_bind_same_named_functions_independently() {
let dir = TempDir::new("call13");
write(
&dir.path().join("a.mq.md"),
"## @exec value\n\n`params()`\n\n`return 10`\n",
);
write(
&dir.path().join("b.mq.md"),
"## @exec value\n\n`params()`\n\n`return 20`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n aa: \"./a.mq.md\"\n bb: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return aa.value() + bb.value()`\n",
);
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "30"})
);
}
// CALL-14
#[test]
fn check_never_executes_a_plugin_artifact_or_side_effect_script() {
let dir = TempDir::new("call14");
let plugin_dir = TempDir::new("call14-plugin");
let marker = plugin_dir.path().join("executed.marker");
let artifact = plugin_dir.path().join(library_name());
write(
&artifact,
&format!("#!/bin/sh\ntouch '{}'\nexit 0\n", marker.display()),
);
let sha = sha256_file(&artifact).unwrap();
write(
&plugin_dir.path().join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.script
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: demo.run
signature: "() -> Int"
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return demo.run()`\n",
);
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
assert!(!marker.exists(), "check executed the artifact");
}
// CALL-15
#[test]
fn check_emit_and_run_share_the_same_static_binding_source() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call15");
let plugin_dir = TempDir::new("call15-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let analysis_path = dir.path().join("analysis.json");
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let functions = analysis["modules"]
.as_array()
.and_then(|modules| modules.first())
.and_then(|module| module["functions"].as_array())
.unwrap_or_else(|| panic!("analysis has no module functions: {analysis}"));
assert!(!functions.is_empty());
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
"--json",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
// Without the descriptor the same call is statically unknown: run/check
// consume the same prepared binding, not a runtime name probe.
let without = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(without.status.code(), Some(1));
assert!(stderr(&without).contains("symbol.unknown"));
}
// CALL-16
#[test]
fn print_alias_keeps_the_existing_output_bytes() {
let run = cli(&["run", "examples/hello.mq.md"], &repo());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
assert_eq!(stdout(&run), "你好,Marqdo\n");
}
+80 -18
View File
@@ -166,8 +166,8 @@ fn semantic_goldens_match_end_to_end_execution() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
install_stdlib_print(&mut program);
install_entry_stdlib_imports(&mut program, &module_id, &analysis);
bind_calls_with_stdlib_aliases(&mut program);
let mut capabilities = Capabilities::pure();
if grant_foreign {
@@ -284,26 +284,88 @@ fn normalise_relative(path: &Path) -> String {
.join("/")
}
/// Load the bundled stdlib print modules for direct-runtime fixtures.
/// Bind direct-runtime fixtures exactly like the CLI composition root.
///
/// The CLI loader normally injects these for Compat-B. The semantic harness
/// builds a Program directly, so it mirrors the same resolution here; without
/// it, fixtures that call `打印` would hit the Compat-C "no bundle" error.
fn install_stdlib_print(program: &mut Program) {
/// The semantic harness builds a `Program` directly, so it mirrors the
/// production path: load the official stdlib public-alias targets, build the
/// unique registry, run the single binding pass and install its table. There is
/// no `print_override` and no runtime name guessing.
fn bind_calls_with_stdlib_aliases(program: &mut Program) {
let root = repo_root().join("stdlib");
if !root.join("stdlib.json").is_file() {
return;
}
let mut loaded = std::collections::BTreeSet::new();
let io = match load_stdlib_module(&root, "io.mq.md", program, &mut loaded) {
Ok(id) => id,
Err(error) => panic!("cannot load bundled stdlib: {error}"),
};
let function = program
.module(&io)
.and_then(|module| module.function("写值"))
.unwrap_or_else(|| panic!("stdlib io has no 写值 function"));
program.print_override = Some(function.id.clone());
let mut official = Vec::new();
if root.join("stdlib.json").is_file() {
let text = fs::read_to_string(root.join("stdlib.json"))
.unwrap_or_else(|error| panic!("cannot read stdlib.json: {error}"));
let manifest: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("invalid stdlib.json: {error}"));
if let Some(aliases) = manifest
.get("public_aliases")
.and_then(serde_json::Value::as_array)
{
for entry in aliases {
let public_names: Vec<String> = entry
.get("public_names")
.and_then(serde_json::Value::as_array)
.unwrap_or_else(|| panic!("public alias has no public_names"))
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect();
let target_module = entry
.get("target_module")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("public alias has no target_module"));
let target_function = entry
.get("target_function")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("public alias has no target_function"));
let module_id = load_stdlib_module(&root, target_module, program, &mut loaded)
.unwrap_or_else(|error| panic!("cannot load stdlib alias module: {error}"));
let function = program
.module(&module_id)
.and_then(|module| module.function(target_function))
.unwrap_or_else(|| {
panic!("stdlib alias target `{target_function}` is missing")
});
let effects = entry
.get("effects")
.and_then(serde_json::Value::as_array)
.map(|effects| {
effects
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect()
})
.unwrap_or_default();
official.push(marqdo_ir::callable::OfficialAlias {
public_names,
function: function.id.clone(),
signature: marqdo_ir::callable::CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
owner_package: module_id.instance.clone(),
effects_requested: effects,
});
}
}
}
let mut registry = program.callable_registry();
for alias in official {
registry
.insert_official_alias(alias)
.unwrap_or_else(|error| panic!("cannot register stdlib alias: {error}"));
}
let bound = marqdo_frontend::calls::bind_program_calls(program, &registry);
if !bound.diagnostics.is_empty() {
panic!(
"fixture failed static call binding: {:#?}",
bound.diagnostics
);
}
program.set_call_bindings(bound.bindings);
}
fn load_stdlib_module(
+13
View File
@@ -224,6 +224,7 @@ fn runtime_negative_goldens() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
bind_program_calls(&mut program);
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
@@ -284,3 +285,15 @@ fn runtime_negative_goldens() {
}
let _ = fs::remove_dir_all(&project_root);
}
/// Bind direct-runtime fixtures exactly like the CLI composition root.
fn bind_program_calls(program: &mut marqdo_ir::Program) {
let registry = program.callable_registry();
let bound = marqdo_frontend::calls::bind_program_calls(program, &registry);
assert!(
bound.diagnostics.is_empty(),
"fixture failed static call binding: {:#?}",
bound.diagnostics
);
program.set_call_bindings(bound.bindings);
}
+8
View File
@@ -395,6 +395,14 @@ fn narration_removal_preserves_execution() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
let registry = program.callable_registry();
let bound = marqdo_frontend::calls::bind_program_calls(&program, &registry);
assert!(
bound.diagnostics.is_empty(),
"property fixture failed binding: {:#?}",
bound.diagnostics
);
program.set_call_bindings(bound.bindings);
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
File diff suppressed because it is too large. Load diff
+260
View File
@@ -0,0 +1,260 @@
//! Official stdlib public alias routing (RFC-EXT-0001 §8, ADR-0058).
//!
//! `打印`/`print` are ordinary `Marqdo` bindings to `io.mq.md::写值` declared
//! in the verified `stdlib.json` metadata. There is no `print_override`, no
//! runtime name special case and no hard-coded per-function scan.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-stdlib-alias-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
command.args(args).current_dir(dir);
for (key, value) in env {
command.env(key, value);
}
command.output().unwrap()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn copy_stdlib(target: &Path) {
let source = repo().join("stdlib");
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
copy_dir(&path, &target.join(entry.file_name()));
} else {
std::fs::copy(&path, target.join(entry.file_name())).unwrap();
}
}
}
fn copy_dir(source: &Path, target: &Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
copy_dir(&path, &target.join(entry.file_name()));
} else {
std::fs::copy(&path, target.join(entry.file_name())).unwrap();
}
}
}
#[test]
fn print_and_its_alias_are_bound_to_the_official_module() {
let dir = TempDir::new("print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(1)`\n\n`print(\"two\")`\n\n`return None`\n",
)
.unwrap();
let output = cli(&["run", "index.mq.md"], dir.path(), &[]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
assert_eq!(stdout(&output), "1\ntwo\n");
}
#[test]
fn program_without_print_does_not_load_the_stdlib_module_graph() {
let dir = TempDir::new("no-print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`params()`\n\n`return 1 + 2`\n",
)
.unwrap();
let analysis_path = dir.path().join("factorial.json");
let output = cli(
&[
"check",
"index.mq.md",
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
&[],
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let modules = analysis["modules"].as_array().unwrap();
assert!(
modules
.iter()
.all(|module| !module["id"].as_str().unwrap_or("").starts_with("std:")),
"a program without print must not load the stdlib: {analysis}"
);
}
#[test]
fn print_program_loads_exactly_the_declared_alias_target() {
let dir = TempDir::new("with-print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(\"x\")`\n\n`return None`\n",
)
.unwrap();
let analysis_path = dir.path().join("hello.json");
let output = cli(
&[
"check",
"index.mq.md",
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
&[],
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let ids: Vec<&str> = analysis["modules"]
.as_array()
.unwrap()
.iter()
.filter_map(|module| module["id"].as_str())
.collect();
assert!(
ids.iter().any(|id| id.ends_with("::io.mq.md")),
"print must load io.mq.md: {ids:?}"
);
assert!(
ids.iter().any(|id| id.ends_with("::format.mq.md")),
"io.mq.md imports format.mq.md: {ids:?}"
);
}
#[test]
fn tampered_public_alias_metadata_digest_is_rejected() {
let dir = TempDir::new("alias-digest");
let stdlib = dir.path().join("stdlib");
copy_stdlib(&stdlib);
let manifest_path = stdlib.join("stdlib.json");
let text = std::fs::read_to_string(&manifest_path).unwrap();
let mut manifest: serde_json::Value = serde_json::from_str(&text).unwrap();
manifest["aliases_digest"] = serde_json::json!("sha256:".to_string() + &"0".repeat(64));
std::fs::write(
&manifest_path,
serde_json::to_string_pretty(&manifest).unwrap() + "\n",
)
.unwrap();
let doc = dir.path().join("index.mq.md");
std::fs::write(&doc, "## @exec main\n\n`打印(1)`\n\n`return None`\n").unwrap();
let output = cli(
&["run", doc.to_str().unwrap()],
dir.path(),
&[("MARQDO_STDLIB_DIR", &stdlib)],
);
assert!(!output.status.success(), "{}", stderr(&output));
assert!(
stderr(&output).contains("public-alias metadata digest mismatch"),
"{}",
stderr(&output)
);
}
#[test]
fn tampered_alias_target_signature_is_rejected() {
let dir = TempDir::new("alias-target");
let stdlib = dir.path().join("stdlib");
copy_stdlib(&stdlib);
let manifest_path = stdlib.join("stdlib.json");
let text = std::fs::read_to_string(&manifest_path).unwrap();
let mut manifest: serde_json::Value = serde_json::from_str(&text).unwrap();
manifest["public_aliases"][0]["expected_signature"] = serde_json::json!("params(值, 额外)");
// Recompute the declared metadata digest so only the target check can fail.
let canonical = manifest["public_aliases"][0].clone();
let module = canonical["target_module"].as_str().unwrap();
let function = canonical["target_function"].as_str().unwrap();
let mut names: Vec<&str> = canonical["public_names"]
.as_array()
.unwrap()
.iter()
.filter_map(serde_json::Value::as_str)
.collect();
names.sort();
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(module.as_bytes());
hasher.update([0]);
hasher.update(function.as_bytes());
hasher.update([0]);
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
let digest = format!("sha256:{}", hex(&hasher.finalize()));
manifest["aliases_digest"] = serde_json::json!(digest);
std::fs::write(
&manifest_path,
serde_json::to_string_pretty(&manifest).unwrap() + "\n",
)
.unwrap();
let doc = dir.path().join("index.mq.md");
std::fs::write(&doc, "## @exec main\n\n`打印(1)`\n\n`return None`\n").unwrap();
let output = cli(
&["run", doc.to_str().unwrap()],
dir.path(),
&[("MARQDO_STDLIB_DIR", &stdlib)],
);
assert!(!output.status.success(), "{}", stderr(&output));
assert!(
stderr(&output).contains("expected signature") || stderr(&output).contains("alias"),
"{}",
stderr(&output)
);
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}