fix: float wire precision, native stack safety, refs diagnostics and fixtures

Findings from the conformance corpus workstream, all fixed at the source:

- value/wire: enable serde_json's float_roundtrip so typed wire floats keep
  their exact digits across foreign/plugin boundaries (Python pi*9 now stays
  28.274333882308138).
- host: default interpreter stack budget lowered to 128 frames so deeply
  recursive documents hit a structured resource.exhausted instead of exhausting
  the native debug-build Rust stack; --stack remains available.
- frontend/map: calling an external HTTP(S) link is reported as ref.unresolved
  (consistent with other unresolvable call targets) instead of math.unsupported.
- frontend/analyze: invalid front matter emits a single frontmatter.invalid
  diagnostic (the YAML error is not repeated by the imports pass).
- spec/mapping: clarify that would-be execution nodes outside any function body
  are inert with a markdown.inert_executable warning (no "return outside a
  function" hard-error claim).
- tests: add the conformance corpus and harness (150 AST goldens, 36 semantic
  goldens, 48 hard-error + 6 warning + 10 runtime-error negatives, CLI/module/
  plugin integration tests, prose-invariance properties) and update the
  three reported observations to the fixed behaviour.
This commit is contained in:
cflmy committed 2026-11-20 10:54:16 +08:00
1 parent 33341a0e92
commit 847c2c1580
511 files changed
+11678 -26

No files matched your search

+215
View File
@@ -0,0 +1,215 @@
//! AST conformance golden tests for the frozen `marqdo.md.v1` Markdown profile.
//!
//! Each `tests/conformance/ast/*.mq.md` fixture is parsed with
//! [`marqdo_markdown::parse`] and the canonical AST root is serialized to
//! pretty JSON. The result is compared byte-for-byte with the sibling
//! `*.ast.json` golden.
//!
//! Regenerate goldens deliberately with:
//!
//! ```text
//! UPDATE_GOLDENS=1 cargo test -p marqdo-cli --test conformance_ast
//! ```
//!
//! Updating is the *only* way goldens change; the test fails if a fixture has
//! no golden and if a golden has no fixture.
use std::fs;
use std::path::{Path, PathBuf};
/// Repository root (the workspace above `crates/cli`).
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates/cli has a parent")
.parent()
.expect("crates has a parent")
.to_path_buf()
}
fn ast_dir() -> PathBuf {
repo_root().join("tests").join("conformance").join("ast")
}
/// All fixture paths, sorted by file name for deterministic ordering.
fn fixture_paths() -> Vec<PathBuf> {
let dir = ast_dir();
let mut paths: Vec<PathBuf> = fs::read_dir(&dir)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", dir.display()))
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "md"))
.collect();
paths.sort();
paths
}
/// Serialize the canonical AST view with a trailing newline.
fn golden_text(source: &str) -> String {
let document = marqdo_markdown::parse(source);
let mut text = serde_json::to_string_pretty(&document.root)
.expect("the canonical AST view is always serializable");
text.push('\n');
text
}
/// Golden path for a fixture: `foo.mq.md` -> `foo.ast.json` (the extension
/// replacement must keep the `.mq` marker, not overwrite `md` only).
fn golden_path(fixture: &Path) -> PathBuf {
let name = fixture
.file_name()
.expect("fixture has a file name")
.to_string_lossy();
let stem = name
.strip_suffix(".mq.md")
.unwrap_or_else(|| panic!("fixture `{}` must end in .mq.md", fixture.display()));
fixture.with_file_name(format!("{stem}.ast.json"))
}
fn write_golden(path: &Path, text: &str) {
fs::write(path, text)
.unwrap_or_else(|error| panic!("cannot write golden {}: {error}", path.display()));
}
/// Report a compact, line-based diff summary for one fixture.
fn report_mismatch(fixture: &Path, expected: &str, actual: &str) {
let expected_lines: Vec<&str> = expected.lines().collect();
let actual_lines: Vec<&str> = actual.lines().collect();
let mut differences = 0usize;
let mut first: Option<usize> = None;
for index in 0..expected_lines.len().max(actual_lines.len()) {
if expected_lines.get(index) != actual_lines.get(index) {
differences += 1;
if first.is_none() {
first = Some(index);
}
}
}
let first = first.unwrap_or(0);
let start = first.saturating_sub(3);
let end = (first + 8).min(expected_lines.len().max(actual_lines.len()));
let mut message = format!(
"AST golden mismatch for `{}`.\n\
{} line(s) differ (first at line {}).\n\
--- expected (golden) ---\n",
fixture.display(),
differences,
first + 1
);
for index in start..end {
message.push_str(&format!(
"{:>4} | {}\n",
index + 1,
expected_lines.get(index).copied().unwrap_or("<missing>")
));
}
message.push_str("--- actual (parser) ---\n");
for index in start..end {
message.push_str(&format!(
"{:>4} | {}\n",
index + 1,
actual_lines.get(index).copied().unwrap_or("<missing>")
));
}
// The most common cause is an executable payload of the wrong shape. Point
// at the offending source region so authors can fix the fixture quickly.
if let Ok(source) = fs::read_to_string(fixture) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(expected) {
if let Some(span) = value.get("span") {
let start = span.get("start").and_then(serde_json::Value::as_u64);
let end = span.get("end").and_then(serde_json::Value::as_u64);
if let (Some(start), Some(end)) = (start, end) {
let slice = source.get(start as usize..end as usize).unwrap_or("");
message.push_str(&format!("first node source: {slice:?}\n"));
}
}
}
}
message.push_str(
"Run `UPDATE_GOLDENS=1 cargo test -p marqdo-cli --test conformance_ast` \
only for an intentional profile change.\n",
);
panic!("{message}");
}
#[test]
fn ast_goldens_match_the_frozen_profile() {
let fixtures = fixture_paths();
assert!(
fixtures.len() >= 100,
"the P0 corpus must keep at least 100 AST fixtures, found {}",
fixtures.len()
);
let update = std::env::var_os("UPDATE_GOLDENS").is_some_and(|value| value == "1");
let mut updated = 0usize;
let mut failures: Vec<String> = Vec::new();
for fixture in &fixtures {
let source = fs::read_to_string(fixture)
.unwrap_or_else(|error| panic!("cannot read fixture {}: {error}", fixture.display()));
let golden = golden_path(fixture);
let actual = golden_text(&source);
if update {
write_golden(&golden, &actual);
updated += 1;
continue;
}
let expected = fs::read_to_string(&golden).unwrap_or_else(|error| {
panic!(
"missing AST golden for `{}` ({error}).\n\
Run `UPDATE_GOLDENS=1 cargo test -p marqdo-cli --test conformance_ast`.",
fixture.display()
)
});
if expected != actual {
failures.push(fixture.display().to_string());
}
}
if update {
println!(
"UPDATE_GOLDENS=1: rewrote {updated} AST golden(s) under {}",
ast_dir().display()
);
return;
}
// A golden without a fixture is stale corpus output; fail rather than keep
// silently ignored files.
let golden_count = fs::read_dir(ast_dir())
.expect("ast fixture directory is readable")
.filter_map(Result::ok)
.filter(|entry| {
entry
.path()
.extension()
.is_some_and(|extension| extension == "json")
})
.count();
assert_eq!(
golden_count,
fixtures.len(),
"every AST fixture needs exactly one golden (orphan *.ast.json files?)"
);
if failures.is_empty() {
return;
}
// Re-read the mismatching fixtures to produce a detailed, line-based diff.
// This keeps the common pass path cheap and the failure path informative.
for fixture in &fixtures {
let source = fs::read_to_string(fixture).expect("fixture is readable");
let golden = golden_path(fixture);
let expected = fs::read_to_string(&golden).expect("golden is readable");
let actual = golden_text(&source);
if expected != actual {
report_mismatch(fixture, &expected, &actual);
}
}
}
+265
View File
@@ -0,0 +1,265 @@
//! End-to-end semantic conformance tests.
//!
//! Each `tests/conformance/semantics/*.mq.md` fixture is analysed by
//! [`marqdo_frontend::analyze_source`], assembled into an
//! [`marqdo_ir::Program`] and executed through [`marqdo_runtime::run`] with a
//! [`marqdo_host::StdHost`] in `project` mode. The typed wire representation
//! ([`marqdo_value::to_wire`]) of the returned value and the captured program
//! stdout are compared with the sibling `*.expected.json`:
//!
//! ```json
//! {"function": "<name>", "args": {"name": <wire value>},
//! "value": <wire value>, "stdout": "..."}
//! ```
//!
//! Fixtures that need an explicit grant declare it as
//! `"grants": ["foreign"]`; they are skipped when the kernel is unavailable.
//!
//! Developer note: `UPDATE_SEMANTICS_GOLDENS=1` rewrites `value`/`stdout` from
//! the implementation. Never use it without hand-checking every rewritten
//! expectation; the checked-in goldens were reviewed individually.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_ir::ModuleId;
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates/cli has a parent")
.parent()
.expect("crates has a parent")
.to_path_buf()
}
fn semantics_dir() -> PathBuf {
repo_root()
.join("tests")
.join("conformance")
.join("semantics")
}
fn fixture_paths() -> Vec<PathBuf> {
let dir = semantics_dir();
let mut paths: Vec<PathBuf> = fs::read_dir(&dir)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", dir.display()))
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|extension| extension == "md"))
.collect();
paths.sort();
paths
}
fn expected_path(fixture: &Path) -> PathBuf {
let name = fixture
.file_name()
.expect("fixture has a file name")
.to_string_lossy();
let stem = name
.strip_suffix(".mq.md")
.unwrap_or_else(|| panic!("fixture `{}` must end in .mq.md", fixture.display()));
fixture.with_file_name(format!("{stem}.expected.json"))
}
fn python_available() -> bool {
Command::new("python3")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
/// Unique scratch directory for the host project root. Program fixtures are
/// pure, so nothing is read from or written to it; it only satisfies the host
/// constructor contract.
fn scratch_project_root() -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0);
let dir = std::env::temp_dir().join(format!(
"marqdo-conformance-semantics-{}-{nanos}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap_or_else(|error| {
panic!(
"cannot create scratch project root {}: {error}",
dir.display()
)
});
dir
}
fn render_diagnostics(result: &marqdo_frontend::AnalysisResult) -> String {
let mut out = String::new();
for diagnostic in &result.diagnostics {
out.push_str(&format!(
" {}[{}]: {}\n",
diagnostic.severity, diagnostic.code, diagnostic.message
));
}
out
}
#[test]
fn semantic_goldens_match_end_to_end_execution() {
let fixtures = fixture_paths();
assert!(
fixtures.len() >= 25,
"the P0 corpus must keep at least 25 semantic fixtures, found {}",
fixtures.len()
);
let update = std::env::var_os("UPDATE_SEMANTICS_GOLDENS").is_some_and(|value| value == "1");
let has_python = python_available();
let project_root = scratch_project_root();
let mut skipped = 0usize;
let mut updated = 0usize;
for fixture in &fixtures {
let expected_path = expected_path(fixture);
let expected_text = fs::read_to_string(&expected_path).unwrap_or_else(|error| {
panic!(
"missing semantic golden {}: {error}",
expected_path.display()
)
});
let mut expected: serde_json::Value = serde_json::from_str(&expected_text)
.unwrap_or_else(|error| panic!("invalid JSON in {}: {error}", expected_path.display()));
let object = expected
.as_object()
.unwrap_or_else(|| panic!("{} must be a JSON object", expected_path.display()));
let function = object
.get("function")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("{} has no `function`", expected_path.display()))
.to_string();
let grant_foreign = object
.get("grants")
.and_then(serde_json::Value::as_array)
.is_some_and(|grants| grants.iter().any(|grant| grant == "foreign"));
if grant_foreign && !has_python {
skipped += 1;
println!(
"skipping {}: python3 is unavailable (foreign kernel fixture)",
fixture.display()
);
continue;
}
let source = fs::read_to_string(fixture)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", fixture.display()));
let module_id = ModuleId::from("index.mq.md");
let analysis = marqdo_frontend::analyze_source(&module_id.0, &source);
if analysis.has_errors() {
panic!(
"semantic fixture `{}` must compile without errors:\n{}",
fixture.display(),
render_diagnostics(&analysis)
);
}
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
let mut capabilities = Capabilities::pure();
if grant_foreign {
capabilities = capabilities.allow_foreign();
}
let mut host = StdHost::new(SandboxMode::Project, capabilities, project_root.clone());
let args_value = object
.get("args")
.cloned()
.unwrap_or_else(|| serde_json::json!({}));
let args_object = args_value
.as_object()
.unwrap_or_else(|| panic!("`args` of {} must be an object", expected_path.display()));
let mut runtime_args = Vec::new();
// BTreeMap-backed JSON objects iterate in sorted key order; argument
// evaluation order is irrelevant here because arguments are constants.
for (name, wire) in args_object {
let value = marqdo_value::from_wire(wire).unwrap_or_else(|error| {
panic!(
"invalid wire argument `{name}` in {}: {error}",
expected_path.display()
)
});
runtime_args.push(EvaluatedArg::named(
name.clone(),
value,
marqdo_span::Span::default(),
));
}
let outcome =
run(&program, &mut host, &module_id, &function, runtime_args).unwrap_or_else(|error| {
panic!(
"semantic fixture `{}` failed with {}: {}\nframes: {:?}",
fixture.display(),
error.code(),
error.message,
error.frames
)
});
let stdout = String::from_utf8_lossy(&host.take_output()).to_string();
let value = marqdo_value::to_wire(&outcome.value);
if update {
let mut object = expected.as_object().cloned().expect("object");
object.insert("value".into(), value);
object.insert("stdout".into(), serde_json::Value::String(stdout));
expected = serde_json::Value::Object(object);
let mut text = serde_json::to_string_pretty(&expected).expect("serializable");
text.push('\n');
fs::write(&expected_path, text).unwrap_or_else(|error| {
panic!("cannot write {}: {error}", expected_path.display())
});
updated += 1;
continue;
}
let expected_value = object.get("value").unwrap_or_else(|| {
panic!(
"{} has no `value`; regenerate it with UPDATE_SEMANTICS_GOLDENS=1 \
after reviewing the behaviour",
expected_path.display()
)
});
let expected_stdout = object
.get("stdout")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("{} has no `stdout`", expected_path.display()));
assert_eq!(
&value,
expected_value,
"value mismatch for `{}`\n expected: {}\n actual: {}",
fixture.display(),
expected_value,
value
);
assert_eq!(
stdout,
expected_stdout,
"stdout mismatch for `{}`",
fixture.display()
);
}
if update {
println!("UPDATE_SEMANTICS_GOLDENS=1: rewrote {updated} semantic golden(s)");
return;
}
let _ = fs::remove_dir_all(&project_root);
println!(
"semantic conformance: {} fixture(s) checked, {skipped} skipped",
fixtures.len()
);
}
+684
View File
@@ -0,0 +1,684 @@
//! CLI integration tests.
//!
//! These tests drive the real `marqdo` binary (`CARGO_BIN_EXE_marqdo`) with
//! [`std::process::Command`] in throw-away temporary directories. They cover
//! the public contract from `spec`/blueprint section 13: `init`, `check`,
//! `run`, `call`, `inspect`, `fmt`, multi-module imports and cycles, lock/sync
//! reproducibility, plugin inspection and plugin invocation.
//!
//! Temporary directories live under the OS temp directory and are removed on
//! drop; the repository itself is never modified.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use sha2::Digest;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates/cli has a parent")
.parent()
.expect("crates has a parent")
.to_path_buf()
}
/// Remove a directory tree on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0);
let path = std::env::temp_dir().join(format!(
"marqdo-cli-integration-{tag}-{}-{nanos}",
std::process::id()
));
fs::create_dir_all(&path)
.unwrap_or_else(|error| panic!("cannot create {}: {error}", path.display()));
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn write(&self, relative: &str, contents: &str) {
let path = self.path.join(relative);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.unwrap_or_else(|error| panic!("cannot create {}: {error}", parent.display()));
}
fs::write(&path, contents)
.unwrap_or_else(|error| panic!("cannot write {}: {error}", path.display()));
}
fn read(&self, relative: &str) -> String {
fs::read_to_string(self.path.join(relative))
.unwrap_or_else(|error| panic!("cannot read `{relative}`: {error}"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// Run the CLI in `dir`.
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap_or_else(|error| panic!("cannot run marqdo {args:?}: {error}"))
}
fn stdout_text(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn stderr_text(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn exit_code(output: &Output) -> i32 {
output
.status
.code()
.unwrap_or_else(|| panic!("marqdo terminated by a signal: {:?}", output.status))
}
fn assert_exit(output: &Output, expected: i32, context: &str) {
assert_eq!(
exit_code(output),
expected,
"{context}\n stdout: {}\n stderr: {}",
stdout_text(output),
stderr_text(output)
);
}
fn json_stdout(output: &Output) -> serde_json::Value {
let text = stdout_text(output);
serde_json::from_str(&text).unwrap_or_else(|error| {
panic!("stdout is not a single JSON document: {error}\nstdout: {text}")
})
}
fn python_available() -> bool {
Command::new("python3")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn cc_available() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
#[test]
fn init_creates_a_runnable_project() {
let dir = TempDir::new("init");
let output = cli(dir.path(), &["init", "proj"]);
assert_exit(&output, 0, "init must succeed");
assert!(stdout_text(&output).contains("Initialized Marqdo project"));
let project = dir.path().join("proj");
assert!(project.join("marqdo.yaml").is_file(), "manifest missing");
assert!(
project.join("index.mq.md").is_file(),
"entry document missing"
);
let check = cli(&project, &["check", "index.mq.md"]);
assert_exit(&check, 0, "generated project must check cleanly");
assert!(stdout_text(&check).contains("checked 1 module(s): ok"));
assert!(stderr_text(&check).is_empty());
let run = cli(&project, &["run", "index.mq.md"]);
assert_exit(&run, 0, "generated project must run");
assert_eq!(stdout_text(&run), "你好,Marqdo\n");
let json = cli(&project, &["check", "index.mq.md", "--json"]);
assert_exit(&json, 0, "check --json must succeed");
let value = json_stdout(&json);
assert_eq!(value["command"], "check");
assert_eq!(value["success"], true);
assert_eq!(value["errors"], 0);
assert!(value["diagnostics"].as_array().is_some());
assert!(
stderr_text(&json).is_empty(),
"--json must not mix stderr text"
);
// `init` refuses to overwrite an existing project.
let again = cli(dir.path(), &["init", "proj"]);
assert_exit(&again, 1, "init must refuse an existing manifest");
assert!(stderr_text(&again).contains("already contains"));
}
#[test]
fn check_exit_codes_and_diagnostics() {
let dir = TempDir::new("check");
dir.write("good.mq.md", "## main\n\n*1 + 1*\n");
dir.write("bad.mq.md", "## f\n\n**a *b* c**\n");
dir.write("warning.mq.md", "**x = 1**\n\n## main\n\n*1*\n");
let good = cli(dir.path(), &["check", "good.mq.md"]);
assert_exit(&good, 0, "clean document");
assert!(stdout_text(&good).contains("checked 1 module(s): ok"));
let bad = cli(dir.path(), &["check", "bad.mq.md"]);
assert_exit(&bad, 1, "invalid executable shape is a hard error");
let bad_stderr = stderr_text(&bad);
assert!(bad_stderr.contains("error[markdown.invalid_construct]"));
assert!(bad_stderr.contains("check failed"));
assert!(stdout_text(&bad).is_empty());
let bad_json = cli(dir.path(), &["check", "bad.mq.md", "--json"]);
assert_exit(&bad_json, 1, "check --json keeps the exit code");
let value = json_stdout(&bad_json);
assert_eq!(value["command"], "check");
assert_eq!(value["success"], false);
assert_eq!(value["errors"], 1);
let diagnostics = value["diagnostics"].as_array().expect("diagnostics array");
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0]["code"], "markdown.invalid_construct");
assert_eq!(diagnostics[0]["severity"], "error");
assert_eq!(diagnostics[0]["line"], 3);
assert!(stderr_text(&bad_json).is_empty());
let warning = cli(dir.path(), &["check", "warning.mq.md"]);
assert_exit(&warning, 0, "a warning does not fail check");
assert!(stdout_text(&warning).contains("checked 1 module(s): ok"));
assert!(stderr_text(&warning).contains("warning[markdown.inert_executable]"));
let warning_json = cli(dir.path(), &["check", "warning.mq.md", "--json"]);
let value = json_stdout(&warning_json);
assert_eq!(value["success"], true);
assert_eq!(value["diagnostics"][0]["severity"], "warning");
let missing = cli(dir.path(), &["check", "missing.mq.md"]);
assert_exit(&missing, 2, "missing file is a usage/IO error");
assert!(stderr_text(&missing).contains("error"));
}
#[test]
fn run_json_embeds_program_stdout() {
let dir = TempDir::new("run-json");
dir.write(
"print.mq.md",
"## main\n\n> 打印(\"你好\")\n\n> 打印(42)\n\n*None*\n",
);
let output = cli(dir.path(), &["run", "print.mq.md", "--json"]);
assert_exit(&output, 0, "run --json must succeed");
// Exactly one JSON document on stdout: program output is embedded, never
// interleaved with the machine-readable envelope.
let value = json_stdout(&output);
assert_eq!(value["command"], "run");
assert_eq!(value["success"], true);
assert_eq!(value["stdout"], "你好\n42\n");
assert_eq!(value["value"]["type"], "none");
assert!(value["trace"].as_array().is_some());
assert!(stderr_text(&output).is_empty());
// Text mode writes program output only to stdout, no JSON envelope.
let text = cli(dir.path(), &["run", "print.mq.md"]);
assert_exit(&text, 0, "run must succeed");
assert_eq!(stdout_text(&text), "你好\n42\n");
}
#[test]
fn run_refuses_documents_with_compile_errors() {
let dir = TempDir::new("run-errors");
dir.write("bad.mq.md", "## f\n\n**a *b* c**\n");
let output = cli(dir.path(), &["run", "bad.mq.md"]);
assert_exit(&output, 1, "compile errors must prevent execution");
let stderr = stderr_text(&output);
assert!(stderr.contains("markdown.invalid_construct"));
assert!(stderr.contains("refusing to run"));
assert!(stdout_text(&output).is_empty());
}
#[test]
fn call_executes_examples_with_typed_arguments() {
let root = repo_root();
let examples = root.join("examples");
let factorial = examples.join("factorial.mq.md");
let output = cli(
&root,
&[
"call",
factorial.to_str().unwrap(),
"数学.阶乘",
"--arg",
"n=5",
"--json",
],
);
assert_exit(&output, 0, "call must execute factorial");
let value = json_stdout(&output);
assert_eq!(value["success"], true);
assert_eq!(value["value"]["type"], "int");
assert_eq!(value["value"]["decimal"], "120");
let math = examples.join("math.mq.md");
let output = cli(
&root,
&["call", math.to_str().unwrap(), "计算圆面积", "--json"],
);
assert_exit(&output, 0, "call must execute the math example");
let value = json_stdout(&output);
assert_eq!(value["value"]["type"], "float");
let area = value["value"]["value"].as_f64().expect("float value");
assert!(
(area - std::f64::consts::PI * 16.0).abs() < 1e-12,
"area={area}"
);
let references = examples.join("references.mq.md");
let output = cli(
&root,
&["call", references.to_str().unwrap(), "计算作用力", "--json"],
);
assert_exit(&output, 0, "call must execute the references example");
let value = json_stdout(&output);
assert_eq!(value["value"]["decimal"], "6");
let hello = examples.join("hello.mq.md");
let output = cli(&root, &["run", hello.to_str().unwrap()]);
assert_exit(&output, 0, "hello example");
assert_eq!(stdout_text(&output), "你好,Marqdo\n");
}
#[test]
fn examples_run_end_to_end_including_foreign_when_available() {
let root = repo_root();
let multi = root
.join("examples")
.join("multi-module")
.join("index.mq.md");
let output = cli(&root, &["run", multi.to_str().unwrap()]);
assert_exit(&output, 0, "multi-module example");
let printed = stdout_text(&output);
let area: f64 = printed.trim().parse().expect("printed float");
assert!((area - std::f64::consts::PI * 4.0).abs() < 1e-12);
if !python_available() {
println!("skipping python foreign example: python3 is unavailable");
return;
}
let foreign = root.join("examples").join("python-foreign.mq.md");
let output = cli(
&root,
&["run", foreign.to_str().unwrap(), "--allow-foreign"],
);
assert_exit(&output, 0, "python foreign example");
let printed = stdout_text(&output);
assert!(
printed.starts_with("28.27"),
"unexpected foreign output: {printed:?}"
);
}
#[test]
fn strict_mode_refuses_without_isolation() {
let root = repo_root();
let hello = root.join("examples").join("hello.mq.md");
let output = cli(&root, &["run", hello.to_str().unwrap(), "--mode", "strict"]);
assert_exit(
&output,
1,
"strict mode must refuse when isolation is absent",
);
let stderr = stderr_text(&output);
assert!(
stderr.contains("refusing to run in strict mode"),
"stderr: {stderr}"
);
assert!(stderr.contains("isolation"), "stderr: {stderr}");
assert!(stdout_text(&output).is_empty());
let json = cli(
&root,
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"],
);
assert_exit(&json, 1, "strict refusal keeps exit code 1 in JSON mode");
let value = json_stdout(&json);
assert_eq!(value["success"], false);
assert!(value["error"]
.as_str()
.expect("error string")
.contains("strict mode"));
}
#[test]
fn inspect_outputs_ast_units_signatures_ir_and_refs() {
let root = repo_root();
let factorial = root.join("examples").join("factorial.mq.md");
let factorial = factorial.to_str().unwrap();
let ast = cli(&root, &["inspect", factorial, "--ast", "--json"]);
assert_exit(&ast, 0, "inspect --ast");
let value = json_stdout(&ast);
assert_eq!(value["command"], "inspect");
assert_eq!(value["ast"]["kind"], "document");
let units = cli(&root, &["inspect", factorial, "--units", "--json"]);
assert_exit(&units, 0, "inspect --units");
let value = json_stdout(&units);
let units = value["units"].as_array().expect("units array");
assert!(units.iter().any(|unit| unit["kind"] == "function"));
let signatures = cli(&root, &["inspect", factorial, "--signature", "--json"]);
assert_exit(&signatures, 0, "inspect --signature");
let value = json_stdout(&signatures);
let signature = value["signatures"]
.as_array()
.expect("signatures array")
.iter()
.find(|entry| entry["name"] == "数学.阶乘")
.expect("factorial signature");
assert_eq!(signature["signature"], "inferred");
assert_eq!(signature["params"][0]["name"], "n");
let ir = cli(&root, &["inspect", factorial, "--ir", "--json"]);
assert_exit(&ir, 0, "inspect --ir");
let value = json_stdout(&ir);
let functions = value["ir"].as_array().expect("IR array");
assert!(!functions.is_empty());
assert!(functions[0]["body"].is_array());
// A link that resolves cleanly.
let references = root.join("examples").join("references.mq.md");
let refs = cli(
&root,
&["inspect", references.to_str().unwrap(), "--refs", "--json"],
);
assert_exit(&refs, 0, "inspect --refs");
let value = json_stdout(&refs);
let edges = value["refs"].as_array().expect("refs array");
assert!(edges.iter().any(|edge| edge["resolved"] == true));
// A broken #anchor is reported as unresolved by `inspect --refs`.
let dir = TempDir::new("refs");
dir.write(
"broken.mq.md",
"## main\n\n见[断链](#不存在的标题)。\n\n*1*\n",
);
let broken = cli(dir.path(), &["inspect", "broken.mq.md", "--refs", "--json"]);
assert_exit(&broken, 0, "inspect --refs never executes the document");
let value = json_stdout(&broken);
let edges = value["refs"].as_array().expect("refs array");
assert_eq!(edges.len(), 1);
assert_eq!(edges[0]["url"], "#不存在的标题");
assert_eq!(edges[0]["resolved"], false);
}
#[test]
fn fmt_normalises_line_endings_and_trailing_newlines() {
let dir = TempDir::new("fmt");
dir.write("doc.mq.md", "## main\r\n\r\n*1*\r\n\r\n\r\n");
let before = cli(dir.path(), &["fmt", "--check", "doc.mq.md"]);
assert_exit(&before, 1, "unformatted document is detected");
assert!(stderr_text(&before).contains("is not formatted"));
let format = cli(dir.path(), &["fmt", "doc.mq.md"]);
assert_exit(&format, 0, "fmt must rewrite the document");
let formatted = dir.read("doc.mq.md");
assert_eq!(formatted, "## main\n\n*1*\n");
assert!(!formatted.contains('\r'));
let after = cli(dir.path(), &["fmt", "--check", "doc.mq.md"]);
assert_exit(&after, 0, "formatted document is accepted");
}
#[test]
fn multi_module_imports_and_cycles() {
let dir = TempDir::new("modules");
dir.write(
"geometry.mq.md",
"## 圆面积\n\n`(r: Number)`\n\n*math.eval(ref(\"#公式\"), {\"r\": r}, target=\"A\")*\n\n### 公式\n\n$$\nA = \\pi r^2\n$$\n",
);
dir.write(
"index.mq.md",
"---\nimport:\n geometry: \"./geometry.mq.md\"\n---\n\n## main\n\n**面积 = geometry.圆面积(r=2)**\n\n> 打印(面积)\n",
);
let run = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&run, 0, "multi-module import must run");
let printed: f64 = stdout_text(&run).trim().parse().expect("printed float");
assert!((printed - std::f64::consts::PI * 4.0).abs() < 1e-12);
let check = cli(dir.path(), &["check", "index.mq.md"]);
assert_exit(&check, 0, "multi-module import must check");
// Import cycle diagnostics.
let cycle = TempDir::new("cycle");
cycle.write(
"a.mq.md",
"---\nimport:\n b: \"./b.mq.md\"\n---\n\n## main\n\n*1*\n",
);
cycle.write(
"b.mq.md",
"---\nimport:\n a: \"./a.mq.md\"\n---\n\n## f\n\n*1*\n",
);
let output = cli(cycle.path(), &["check", "a.mq.md"]);
assert_exit(&output, 1, "import cycle is an error");
let stderr = stderr_text(&output);
assert!(stderr.contains("module.cycle"), "stderr: {stderr}");
assert!(stderr.contains("import cycle"), "stderr: {stderr}");
// A missing import target is a module.unresolved error.
let missing = TempDir::new("missing-import");
missing.write(
"index.mq.md",
"---\nimport:\n gone: \"./gone.mq.md\"\n---\n\n## main\n\n*1*\n",
);
let output = cli(missing.path(), &["check", "index.mq.md"]);
assert_exit(&output, 1, "missing import target is an error");
assert!(stderr_text(&output).contains("module.unresolved"));
}
#[test]
fn lock_and_sync_locked_detect_dependency_tampering() {
let dir = TempDir::new("lock");
dir.write(
"marqdo.yaml",
"project:\n name: locktest\n version: 0.1.0\ndependencies:\n dep:\n path: \"./dep\"\n",
);
dir.write("index.mq.md", "## main\n\n*1*\n");
dir.write("dep/index.mq.md", "## main\n\n*1*\n");
let lock = cli(dir.path(), &["lock"]);
assert_exit(&lock, 0, "lock must succeed");
assert!(stdout_text(&lock).contains("locked 1 package(s)"));
let lockfile = dir.read("marqdo.lock");
assert!(lockfile.contains("name: dep"));
let sync = cli(dir.path(), &["sync", "--locked"]);
assert_exit(&sync, 0, "sync --locked must succeed after lock");
assert!(stdout_text(&sync).contains("synchronized 1 package(s)"));
// Tamper with the dependency contents: `sync --locked` must fail.
dir.write("dep/index.mq.md", "## main\n\n*2*\n");
let tampered = cli(dir.path(), &["sync", "--locked"]);
assert_exit(&tampered, 1, "tampered dependency must fail sync --locked");
assert!(stderr_text(&tampered).contains("lockfile is out of date"));
// Re-locking restores a consistent state.
let relock = cli(dir.path(), &["lock"]);
assert_exit(&relock, 0, "re-lock after tampering");
let synced = cli(dir.path(), &["sync", "--locked"]);
assert_exit(&synced, 0, "sync --locked after re-lock");
}
/// Build the C demo plugin in a temporary copy and refresh the manifest hash in
/// that copy only. The repository copy is never touched and the `.so` is never
/// committed.
fn build_plugin_copy(tag: &str) -> Option<(TempDir, PathBuf)> {
if !cc_available() {
println!("skipping plugin test: `cc` is unavailable");
return None;
}
let dir = TempDir::new(tag);
let source = repo_root().join("examples").join("plugin-demo");
let target = dir.path().join("plugin-demo");
fs::create_dir_all(&target).expect("create plugin copy");
for entry in fs::read_dir(&source).expect("read plugin-demo") {
let entry = entry.expect("plugin-demo entry");
if !entry.path().is_file() {
continue;
}
// Copy manifest/source/readme but never a stale compiled artifact.
if entry
.path()
.extension()
.is_some_and(|extension| extension == "so")
{
continue;
}
fs::copy(entry.path(), target.join(entry.file_name()))
.unwrap_or_else(|error| panic!("copy plugin file: {error}"));
}
let include = repo_root().join("include");
let status = Command::new("cc")
.args([
"-shared",
"-fPIC",
"-I",
include.to_str().expect("utf-8 include path"),
"-o",
target.join("solver.so").to_str().expect("utf-8 path"),
target.join("solver.c").to_str().expect("utf-8 path"),
])
.status()
.unwrap_or_else(|error| panic!("cannot run cc: {error}"));
assert!(status.success(), "building the demo plugin failed");
let bytes = fs::read(target.join("solver.so")).expect("read solver.so");
let digest = hex::encode(sha2::Sha256::digest(&bytes));
let manifest_path = target.join("plugin.yaml");
let manifest = fs::read_to_string(&manifest_path).expect("read plugin.yaml");
let placeholder = "0000000000000000000000000000000000000000000000000000000000000000";
assert!(
manifest.contains(placeholder),
"manifest placeholder missing"
);
fs::write(&manifest_path, manifest.replace(placeholder, &digest))
.expect("refresh plugin.yaml sha256");
Some((dir, target))
}
#[test]
fn plugin_inspect_and_explicit_trusted_invocation() {
let Some((_dir, plugin_dir)) = build_plugin_copy("plugin") else {
return;
};
// Inspection never loads plugin code and verifies the artifact hash.
let inspect = cli(
repo_root().as_path(),
&["plugin", "inspect", plugin_dir.to_str().unwrap(), "--json"],
);
assert_exit(&inspect, 0, "plugin inspect");
let value = json_stdout(&inspect);
assert_eq!(value["command"], "plugin.inspect");
assert_eq!(value["success"], true);
assert_eq!(value["loaded"], false);
assert_eq!(value["artifact"]["verified"], true);
assert_eq!(value["exports"][0]["name"], "solver.add");
// Invoking a plugin export from a document requires an explicit trust
// decision, a permission grant and the plugin load itself.
let dir = TempDir::new("plugin-run");
dir.write(
"doc.mq.md",
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
);
let plugin_path = plugin_dir.to_str().unwrap();
let doc = dir.path().join("doc.mq.md");
let doc = doc.to_str().unwrap();
let output = cli(
dir.path(),
&[
"run",
doc,
"--plugin",
plugin_path,
"--trust-native-plugin",
"--allow-plugin",
"demo.solver",
],
);
assert_exit(&output, 0, "trusted plugin invocation");
assert_eq!(stdout_text(&output), "42\n");
let untrusted = cli(
dir.path(),
&[
"run",
doc,
"--plugin",
plugin_path,
"--allow-plugin",
"demo.solver",
],
);
assert_exit(&untrusted, 1, "in-process loading needs explicit trust");
assert!(stderr_text(&untrusted).contains("--trust-native-plugin"));
let ungranted = cli(
dir.path(),
&["run", doc, "--plugin", plugin_path, "--trust-native-plugin"],
);
assert_exit(&ungranted, 1, "plugin permission is required");
assert!(stderr_text(&ungranted).contains("permission.denied"));
// Unknown plugin namespace is a hard runtime symbol error.
dir.write(
"unknown.mq.md",
"## main\n\n**结果 = other.add(a=1, b=1)**\n",
);
let unknown = cli(
dir.path(),
&[
"run",
"unknown.mq.md",
"--plugin",
plugin_path,
"--trust-native-plugin",
"--allow-plugin",
"demo.solver",
],
);
assert_exit(&unknown, 1, "unknown plugin namespace");
assert!(stderr_text(&unknown).contains("symbol.unknown"));
// The export signature requires both named arguments: a missing argument
// becomes a structured plugin failure, never a panic.
dir.write("args.mq.md", "## main\n\n**结果 = solver.add(a=1)**\n");
let bad_args = cli(
dir.path(),
&[
"run",
"args.mq.md",
"--plugin",
plugin_path,
"--trust-native-plugin",
"--allow-plugin",
"demo.solver",
],
);
assert_exit(&bad_args, 1, "plugin argument failure");
assert!(stderr_text(&bad_args).contains("plugin.failure"));
}
+286
View File
@@ -0,0 +1,286 @@
//! Negative conformance tests: executable shapes that must be hard errors.
//!
//! Three suites share this file:
//!
//! * `tests/negative/*.mq.md` — compile-time errors (`marqdo_frontend`). The
//! expected `*.expected.json` is `{"codes": [...]}` and must match the exact
//! sorted list of **error** codes. Warnings emitted by the same document are
//! ignored here (they are asserted separately) so the contract is precise.
//! * `tests/negative/warnings/*.mq.md` — inert-executable warnings. Expected
//! shape is `{"severity": "warning", "codes": [...]}`; the document must
//! compile without errors and the exact sorted warning-code multiset must
//! match.
//! * `tests/negative/runtime/*.mq.md` — documents that compile but fail at
//! runtime. Expected shape is
//! `{"function": "...", "args": {...}, "codes": [...]}` plus the optional
//! `"stack_limit"` budget override. Every entry is executed and the first
//! runtime error code must match.
//!
//! No fallback to prose is ever accepted: each fixture must produce at least
//! one diagnostic or runtime error with the expected stable code.
use std::fs;
use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, StdHost};
use marqdo_ir::ModuleId;
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates/cli has a parent")
.parent()
.expect("crates has a parent")
.to_path_buf()
}
fn fixtures_in(dir: &Path) -> Vec<PathBuf> {
let mut paths: Vec<PathBuf> = fs::read_dir(dir)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", dir.display()))
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|extension| extension == "md"))
.collect();
paths.sort();
paths
}
fn expected_path(fixture: &Path) -> PathBuf {
let name = fixture
.file_name()
.expect("fixture has a file name")
.to_string_lossy();
let stem = name
.strip_suffix(".mq.md")
.unwrap_or_else(|| panic!("fixture `{}` must end in .mq.md", fixture.display()));
fixture.with_file_name(format!("{stem}.expected.json"))
}
fn read_expected(fixture: &Path) -> serde_json::Value {
let path = expected_path(fixture);
let text = fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("missing expectation {}: {error}", path.display()));
serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("invalid JSON in {}: {error}", path.display()))
}
fn expected_codes(expected: &serde_json::Value, fixture: &Path) -> Vec<String> {
expected
.get("codes")
.and_then(serde_json::Value::as_array)
.unwrap_or_else(|| panic!("{} has no `codes` array", expected_path(fixture).display()))
.iter()
.map(|code| {
code.as_str()
.unwrap_or_else(|| {
panic!("non-string code in {}", expected_path(fixture).display())
})
.to_string()
})
.collect()
}
/// Compile-time hard errors, exact sorted error-code multiset.
#[test]
fn compile_time_negative_goldens() {
let dir = repo_root().join("tests").join("negative");
let fixtures = fixtures_in(&dir);
assert!(
fixtures.len() >= 30,
"the P0 corpus must keep at least 30 hard-error fixtures, found {}",
fixtures.len()
);
for fixture in &fixtures {
let source = fs::read_to_string(fixture)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", fixture.display()));
let analysis = marqdo_frontend::analyze_source("index.mq.md", &source);
let mut actual: Vec<String> = analysis
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.is_error())
.map(|diagnostic| diagnostic.code.clone())
.collect();
actual.sort();
let expected = expected_codes(&read_expected(fixture), fixture);
assert!(
!actual.is_empty(),
"negative fixture `{}` produced no error; invalid executable shapes must \
never fall back to prose",
fixture.display()
);
assert_eq!(
actual,
expected,
"error-code mismatch for `{}`\n expected: {expected:?}\n actual: {actual:?}",
fixture.display()
);
// Code lists are contract data: every expected code must really be an
// error severity (never a warning or info diagnostic).
for diagnostic in &analysis.diagnostics {
if expected.contains(&diagnostic.code) {
assert_eq!(
diagnostic.severity,
marqdo_value::Severity::Error,
"code `{}` in `{}` is not an error",
diagnostic.code,
fixture.display()
);
}
}
}
}
/// Inert-executable warnings inside/outside functions.
#[test]
fn warning_goldens() {
let dir = repo_root().join("tests").join("negative").join("warnings");
let fixtures = fixtures_in(&dir);
assert!(!fixtures.is_empty(), "warning corpus must not be empty");
for fixture in &fixtures {
let expected = read_expected(fixture);
assert_eq!(
expected.get("severity").and_then(serde_json::Value::as_str),
Some("warning"),
"{} must declare `\"severity\": \"warning\"`",
expected_path(fixture).display()
);
let source = fs::read_to_string(fixture)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", fixture.display()));
let analysis = marqdo_frontend::analyze_source("index.mq.md", &source);
assert!(
!analysis.has_errors(),
"warning fixture `{}` must compile without errors",
fixture.display()
);
let mut actual: Vec<String> = analysis
.diagnostics
.iter()
.map(|diagnostic| diagnostic.code.clone())
.collect();
actual.sort();
let expected = expected_codes(&expected, fixture);
assert_eq!(
actual,
expected,
"warning-code mismatch for `{}`: expected {expected:?}, actual {actual:?}",
fixture.display()
);
for diagnostic in &analysis.diagnostics {
assert!(
diagnostic.severity == marqdo_value::Severity::Warning,
"`{}` emitted non-warning diagnostic {}: {}",
fixture.display(),
diagnostic.code,
diagnostic.message
);
}
}
}
/// Runtime error codes for documents that compile but fail while executing.
#[test]
fn runtime_negative_goldens() {
let dir = repo_root().join("tests").join("negative").join("runtime");
let fixtures = fixtures_in(&dir);
assert!(
!fixtures.is_empty(),
"runtime negative corpus must not be empty"
);
let project_root = std::env::temp_dir().join(format!(
"marqdo-conformance-negative-{}",
std::process::id()
));
fs::create_dir_all(&project_root)
.unwrap_or_else(|error| panic!("cannot create {}: {error}", project_root.display()));
for fixture in &fixtures {
let expected = read_expected(fixture);
let function = expected
.get("function")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("{} has no `function`", expected_path(fixture).display()))
.to_string();
let source = fs::read_to_string(fixture)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", fixture.display()));
let module_id = ModuleId::from("index.mq.md");
let analysis = marqdo_frontend::analyze_source(&module_id.0, &source);
assert!(
!analysis.has_errors(),
"runtime fixture `{}` must compile; diagnostics: {:?}",
fixture.display(),
analysis
.diagnostics
.iter()
.map(|diagnostic| (diagnostic.code.clone(), diagnostic.message.clone()))
.collect::<Vec<_>>()
);
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
project_root.clone(),
);
if let Some(stack_limit) = expected
.get("stack_limit")
.and_then(serde_json::Value::as_u64)
{
host.budget.stack_limit = stack_limit as usize;
}
let args_value = expected
.get("args")
.cloned()
.unwrap_or_else(|| serde_json::json!({}));
let args_object = args_value
.as_object()
.unwrap_or_else(|| panic!("`args` must be an object"));
let mut runtime_args = Vec::new();
for (name, wire) in args_object {
let value = marqdo_value::from_wire(wire).unwrap_or_else(|error| {
panic!(
"invalid wire argument `{name}` in {}: {error}",
expected_path(fixture).display()
)
});
runtime_args.push(EvaluatedArg::named(
name.clone(),
value,
marqdo_span::Span::default(),
));
}
let expected_codes = expected_codes(&expected, fixture);
match run(
&program,
&mut host,
&module_id,
&function,
runtime_args,
) {
Ok(outcome) => panic!(
"runtime fixture `{}` unexpectedly succeeded with {:?}; expected error {expected_codes:?}",
fixture.display(),
outcome.value
),
Err(error) => {
let codes = vec![error.code().to_string()];
assert_eq!(
codes,
expected_codes,
"runtime error-code mismatch for `{}`: expected {expected_codes:?}, actual {codes:?}",
fixture.display()
);
}
}
}
let _ = fs::remove_dir_all(&project_root);
}
+412
View File
@@ -0,0 +1,412 @@
//! Prose invariance property tests (blueprint section 14.2).
//!
//! For every base document the executable projection `ExecutableProjection(D)`
//! (the frontend IR) must be unchanged by pure narrative edits:
//!
//! * inserting a narration paragraph between top-level blocks/after headings,
//! * prepending/appending narration at the document boundaries,
//! * removing narration paragraphs that were already present.
//!
//! The comparison strips source spans (`span`, `heading_span`, `name_span`,
//! `condition_span`) because narration edits shift byte offsets. The test also
//! asserts that every variant still compiles without errors. The precondition
//! from the blueprint is respected: the transformations only touch `Text`
//! nodes and never add headings, lists, emphasis, links or code, so the
//! Markdown block structure — and therefore the executable structure — cannot
//! change.
use std::collections::BTreeMap;
/// A base program plus the narration fragments it contains.
struct Base {
name: &'static str,
source: &'static str,
/// Narration fragments safe to delete: removing them leaves the block
/// structure intact and only affects text payloads.
narration: &'static [&'static str],
}
const BASES: &[Base] = &[
Base {
name: "factorial",
source: r##"# 数学
## 阶乘
计算阶乘的叙述一。
1. `n <= 1`
递归终点叙述。
*1*
2. `n > 1`
递归步骤叙述。
**结果 = n * 阶乘(n=n-1)**
*结果*
"##,
narration: &["计算阶乘的叙述一。", "递归终点叙述。", "递归步骤叙述。"],
},
Base {
name: "explicit-signature",
source: r##"## 圆面积
`(r: Number)`
半径叙述。
*math.eval(ref("#公式"), {"r": r}, target="A")*
### 公式
$$
A = \pi r^2
$$
"##,
narration: &["半径叙述。"],
},
Base {
name: "countdown-loop",
source: r##"## 倒计时
循环叙述。
**n = 3**
- `n > 0`
循环体叙述。
> 打印(n)
**n = n - 1**
*n*
"##,
narration: &["循环叙述。", "循环体叙述。"],
},
Base {
name: "branch-classification",
source: r##"## 分类
背景叙述。
**结果 = 0**
1. `n < 0`
负数分支叙述。
**结果 = -1**
2. `n >= 0`
非负分支叙述。
**结果 = 1**
*结果*
"##,
narration: &["背景叙述。", "负数分支叙述。", "非负分支叙述。"],
},
Base {
name: "call-and-print",
source: r##"## 问候
说明为什么这样写。
> 打印("你好")
**问候 = "你好,Marqdo"**
再补充一句叙述。
*问候*
"##,
narration: &["说明为什么这样写。", "再补充一句叙述。"],
},
Base {
name: "inline-prose-in-executable-paragraph",
source: r##"## 加一
这是行内叙述 **结果 = 1 + 1** 后面继续叙述。
*结果*
"##,
narration: &["这是行内叙述 ", " 后面继续叙述。"],
},
Base {
name: "nested-control-flow",
source: r##"## 嵌套
说明嵌套结构。
**total = 0**
1. `n > 0`
**m = 3**
- `m > 0`
**total = total + m**
**m = m - 1**
2. `n <= 0`
**total = 0**
*total*
"##,
narration: &["说明嵌套结构。"],
},
Base {
name: "two-namespaces",
source: r##"# 数学
命名空间叙述。
## 平方
**结果 = n * n**
*结果*
# 文本
## 长度
*长度(s)*
"##,
narration: &["命名空间叙述。"],
},
];
const INSERTED_PROSE: &str = "这是一段与执行结构无关的纯叙述文字,它只改变 Markdown 文本节点。";
fn repo_root() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates/cli has a parent")
.parent()
.expect("crates has a parent")
.to_path_buf()
}
/// Strip source spans so narrative edits (which shift byte offsets) compare
/// equal. This mirrors the invariance definition in blueprint section 14.2.
fn without_spans(value: &serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => {
let mut out = serde_json::Map::new();
for (key, value) in map {
if matches!(
key.as_str(),
"span" | "heading_span" | "name_span" | "condition_span" | "key_span"
) {
continue;
}
out.insert(key.clone(), without_spans(value));
}
serde_json::Value::Object(out)
}
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.iter().map(without_spans).collect())
}
other => other.clone(),
}
}
/// Executable projection of one source: the function IR, span-free.
fn executable_projection(source: &str) -> serde_json::Value {
let analysis = marqdo_frontend::analyze_source("index.mq.md", source);
if analysis.has_errors() {
let diagnostics: Vec<String> = analysis
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.is_error())
.map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message))
.collect();
panic!("prose-invariance variant must compile without errors: {diagnostics:?}");
}
let json = serde_json::to_value(&analysis.module.functions)
.expect("function IR is always serializable");
without_spans(&json)
}
/// Whether a line is an ATX heading.
fn is_heading(line: &str) -> bool {
let mut chars = line.chars();
if chars.next() != Some('#') {
return false;
}
let mut hashes = 1;
for ch in chars {
if ch == '#' {
hashes += 1;
if hashes > 6 {
return false;
}
} else {
return ch == ' ';
}
}
false
}
/// Insert a narration paragraph after every heading. When the heading is
/// followed by an explicit signature paragraph, the narration goes *after* the
/// signature so the signature is still the first paragraph of the function.
fn insert_prose_after_headings(source: &str) -> String {
let lines: Vec<&str> = source.lines().collect();
let mut out: Vec<String> = Vec::new();
let mut index = 0usize;
while index < lines.len() {
let line = lines[index];
out.push(line.to_string());
if is_heading(line) {
let mut next = index + 1;
while next < lines.len() && lines[next].trim().is_empty() {
next += 1;
}
let signature = next < lines.len() && lines[next].trim_start().starts_with("`(");
if signature {
while index + 1 < lines.len() && lines[index + 1].trim().is_empty() {
index += 1;
out.push(lines[index].to_string());
}
index += 1;
out.push(lines[index].to_string());
out.push(String::new());
out.push(INSERTED_PROSE.to_string());
} else {
out.push(String::new());
out.push(INSERTED_PROSE.to_string());
}
}
index += 1;
}
let mut text = out.join("\n");
text.push('\n');
text
}
fn variants(base: &Base) -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
map.insert(
"prepend-narration".to_string(),
format!("{INSERTED_PROSE}\n\n{}", base.source),
);
map.insert(
"append-narration".to_string(),
format!("{}\n\n{INSERTED_PROSE}\n", base.source),
);
map.insert(
"insert-after-headings".to_string(),
insert_prose_after_headings(base.source),
);
// Remove each known narration fragment in turn.
for (position, fragment) in base.narration.iter().enumerate() {
map.insert(
format!("remove-narration-{position}"),
base.source.replace(fragment, ""),
);
}
map
}
#[test]
fn pure_prose_edits_do_not_change_executable_ir() {
// Keep the fixture root meaningful for the documented layout even though
// these tests are generated in code: assert the directory exists so a typo
// in the workspace layout is caught.
assert!(repo_root().join("tests").join("properties").is_dir());
let mut checked = 0usize;
for base in BASES {
let expected = executable_projection(base.source);
let generated = variants(base);
assert!(
generated.len() >= 4,
"base `{}` produced too few variants",
base.name
);
for (variant, source) in generated {
let actual = executable_projection(&source);
assert_eq!(
actual, expected,
"prose edit `{variant}` changed the executable IR of base `{}`",
base.name
);
checked += 1;
}
}
println!(
"prose invariance: checked {checked} variant(s) across {} base program(s)",
BASES.len()
);
}
/// Removing narration must also keep the program runnable: execute the
/// factorial base (and its narration-free form) with the same arguments and
/// compare values. This guards against prose accidentally becoming a
/// parameter or a statement.
#[test]
fn narration_removal_preserves_execution() {
use marqdo_host::{Capabilities, StdHost};
use marqdo_ir::ModuleId;
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
let base = &BASES[0];
let clean = base
.narration
.iter()
.fold(base.source.to_string(), |text, fragment| {
text.replace(fragment, "")
});
let project_root = std::env::temp_dir().join(format!(
"marqdo-conformance-properties-{}",
std::process::id()
));
std::fs::create_dir_all(&project_root).expect("scratch project root");
let module_id = ModuleId::from("index.mq.md");
let mut values = Vec::new();
for source in [base.source, clean.as_str()] {
let analysis = marqdo_frontend::analyze_source(&module_id.0, source);
assert!(!analysis.has_errors(), "{:?}", analysis.diagnostics);
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
project_root.clone(),
);
let outcome = run(
&program,
&mut host,
&module_id,
"阶乘",
vec![EvaluatedArg::named(
"n",
marqdo_value::Value::int(5),
marqdo_span::Span::default(),
)],
)
.expect("factorial runs");
values.push(outcome.value);
}
let _ = std::fs::remove_dir_all(&project_root);
assert_eq!(
values[0], values[1],
"removing narration changed execution result"
);
assert_eq!(values[0], marqdo_value::Value::int(120));
}