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

+1 -1
View File
@@ -42,7 +42,7 @@ marqdo-package = { path = "crates/marqdo-package" }
marqdo-sandbox = { path = "crates/marqdo-sandbox" }
comrak = { version = "=1.0.0", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_json = { version = "1", features = ["float_roundtrip"] }
serde_yaml = "0.9"
num-bigint = { version = "0.4", features = ["serde"] }
num-rational = { version = "0.4", features = ["serde"] }
+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));
}
+21 -21
View File
@@ -48,34 +48,34 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
// Explicit front matter imports. Nothing is inferred.
let mut imports: Vec<ImportDecl> = Vec::new();
if let Some(frontmatter) = document.frontmatter() {
if let Err(error) = &frontmatter.yaml {
diagnostics.push(
match &frontmatter.yaml {
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.yaml_span),
format!("invalid YAML front matter: {error}"),
)
.with_hint("front matter must be valid YAML between `---` delimiters"),
);
}
match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint("imports are an explicit mapping: `import: { alias: \"@module\" }`"),
),
Ok(_) => match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint("imports are an explicit mapping: `import: { alias: \"@module\" }`"),
),
},
}
}
+1 -1
View File
@@ -475,7 +475,7 @@ impl<'a> Mapper<'a> {
})
} else if url.starts_with("http://") || url.starts_with("https://") {
self.error_with_hint(
codes::MATH_UNSUPPORTED,
codes::REF_UNRESOLVED,
Some(span),
"external links cannot be called",
"link targets used as calls must resolve to a Marqdo function",
+5 -1
View File
@@ -8,7 +8,11 @@ use marqdo_value::{ErrorCategory, RuntimeError};
/// Default evaluation fuel for one run.
pub const DEFAULT_FUEL: u64 = 5_000_000;
/// Default call-stack depth.
pub const DEFAULT_STACK_LIMIT: usize = 256;
///
/// Kept conservative so that the cooperative budget triggers a structured
/// `resource.exhausted` error before a debug-build native Rust stack can
/// overflow; the CLI exposes `--stack` for callers that need deeper recursion.
pub const DEFAULT_STACK_LIMIT: usize = 128;
/// Default program output limit (bytes).
pub const DEFAULT_OUTPUT_BYTES: usize = 1 << 20;
+6 -2
View File
@@ -161,7 +161,9 @@ The call result is discarded by the statement form; use `strong` to bind it
* `*表达式*` used in a branch is a return from the whole function.
* A function that ends without a return evaluates to `Unit`. `None` is an
explicit empty value and is distinct from `Unit`.
* Return at module top level (outside any function) is an error.
* An `emph` node outside any function body is inert document content and emits
a `markdown.inert_executable` warning (ADR-0002); it is not executed and is
not a hard error. Inside a function body, every `emph` is a return.
## 6. Function signatures and parameter inference
@@ -238,5 +240,7 @@ The following are compile errors with source spans, never prose fallbacks:
* block quote that is not exactly one complete call;
* duplicate function names in a scope;
* empty heading names;
* return outside a function;
* `emph`/`strong`/control structures outside any function body are inert and
produce a `markdown.inert_executable` warning (see §4); they never return
from or execute anything at module level;
* executable node inside a lazy region being interpreted (must not happen).
+167
View File
@@ -0,0 +1,167 @@
# Marqdo conformance and integration test corpus
This directory holds the P0/P1 conformance corpus required by
`docs/DEVELOPMENT_BLUEPRINT.md` §13/§14. The Rust harnesses live in
`crates/cli/tests/` (they use the workspace libraries directly and the
`marqdo` binary via `CARGO_BIN_EXE_marqdo`); the fixtures are plain files here
so they can be rendered, diffed and reviewed like Markdown documents.
Everything here is data. Nothing in this directory modifies the repository, and
no test commits, copies or rewrites files outside a throw-away temp directory.
## Layout
```text
tests/
├── conformance/
│ ├── ast/ 150 × *.mq.md + sibling *.ast.json goldens
│ └── semantics/ 36 × *.mq.md + sibling *.expected.json goldens
├── negative/
│ ├── *.mq.md 48 × compile-time hard-error fixtures + *.expected.json
│ ├── warnings/ 6 × inert-executable warning fixtures + *.expected.json
│ └── runtime/ 10 × runtime-error fixtures + *.expected.json
└── README.md this file
```
Rust harnesses (all in `crates/cli/tests/`):
| Harness | What it proves |
|---|---|
| `conformance_ast.rs` | The frozen `marqdo.md.v1` profile parses each fixture into exactly the checked-in AST (node kinds, attributes, literals, byte spans, order). |
| `conformance_semantics.rs` | Each semantic fixture compiles through `marqdo_frontend`, is assembled into `marqdo_ir::Program` and executed with `marqdo_runtime` + `marqdo_host::StdHost`; returned wire value and program stdout match. |
| `negative.rs` | Invalid executable shapes are **hard errors** (never prose fallbacks), exact sorted diagnostic-code lists; warnings and runtime error codes are asserted in their own suites. |
| `properties.rs` | Blueprint §14.2 prose invariance: inserting/removing pure narration paragraphs never changes the executable function IR (modulo source spans) and diagnostics stay error-free. |
| `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. |
## Running
Use the workspace cargo cache/target as documented in `AGENTS.md`:
```bash
export PATH=/root/.cargo/bin:$PATH
export CARGO_HOME=/root/work/marqdo-cli/.cache/cargo
export CARGO_TARGET_DIR=/root/work/marqdo-cli/.cache/target
cargo test -p marqdo-cli # all conformance + integration harnesses
cargo test --workspace # whole workspace (includes crate unit tests)
```
Individual harnesses:
```bash
cargo test -p marqdo-cli --test conformance_ast
cargo test -p marqdo-cli --test conformance_semantics
cargo test -p marqdo-cli --test negative
cargo test -p marqdo-cli --test properties
cargo test -p marqdo-cli --test integration_cli
```
Fixture discovery is directory-based and sorted by file name, so the order is
deterministic on every platform. The AST and semantic suites fail loudly if the
corpus shrinks below 100 / 25 fixtures, and the negative suite fails below 30
compile-time hard-error fixtures.
## AST goldens and `UPDATE_GOLDENS`
`*.ast.json` files are the pretty-printed canonical AST view
(`marqdo_markdown::parse(source).root`), exactly as `marqdo inspect --ast --json`
would print it. They pin parser version, extension flags and span arithmetic.
Regenerate **only** for an intentional, ADR-backed profile change (the profile
is frozen in `spec/markdown-profile.md`):
```bash
UPDATE_GOLDENS=1 cargo test -p marqdo-cli --test conformance_ast
```
The update run rewrites every golden, prints how many it rewrote and **passes**.
Re-run without the variable to verify, and review the golden diff: a golden
change is a language change, not a bug fix.
A fixture without a golden is an error, and a golden without a fixture is an
error (stale corpus output), so add/remove both together.
## Semantic goldens
Each `*.expected.json` has the shape:
```json
{
"function": "<name passed to marqdo_runtime::run>",
"args": { "<name>": <wire value> },
"value": <wire value>,
"stdout": "..."
}
```
* `args` and `value` use the typed wire encoding from `marqdo_value::to_wire`
(`{"type":"int","decimal":"42"}`, `{"type":"text","value":"…"}`, …).
* `stdout` is the program output captured from the host (never diagnostics).
* Optional `"grants": ["foreign"]` enables `foreign.call`; that fixture is
skipped with a printed notice when `python3` is unavailable.
All values were produced by running the implementation and then checked by
hand against the fixture source. `UPDATE_SEMANTICS_GOLDENS=1` exists for
authoring convenience, but it must not be used blindly: rewriting a semantic
golden without verifying the value would defeat the purpose of the corpus.
## Negative fixtures
Compile-time (`tests/negative/*.mq.md`):
```json
{"codes": ["markdown.invalid_construct"]}
```
The expected list is the exact sorted multiset of **error** diagnostic codes
produced by `marqdo_frontend::analyze_source`. Warnings emitted by the same
document are ignored here. Every listed code is additionally asserted to have
`error` severity, and every fixture must produce at least one error — invalid
executable shapes never fall back to prose.
Warnings (`tests/negative/warnings/*.mq.md`):
```json
{"severity": "warning", "codes": ["markdown.inert_executable"]}
```
These documents must compile **without errors**; the sorted multiset of warning
codes must match exactly. `return`/`strong`/lists/block quotes outside a
function body are inert content (warning), not hard errors.
Runtime (`tests/negative/runtime/*.mq.md`):
```json
{"function": "main", "args": {}, "codes": ["runtime.division_by_zero"]}
```
These documents compile, then must fail at runtime with the expected stable
error code. Optional keys: `"grants": ["foreign"]` and `"stack_limit": 24`
(used for the recursion-depth fixture so the budget — not the host process
stack — is what fails).
## CLI integration notes
`integration_cli.rs` never leaves the repository dirty:
* temporary projects are created under `std::env::temp_dir()` and removed on
drop;
* the demo C plugin is built **in a temp copy** of `examples/plugin-demo`
(`cc -shared -fPIC -I <repo>/include`), and the `sha256` in the copied
`plugin.yaml` is refreshed there. The repo copy and its `.so` (gitignored) are
never touched;
* tests that need `python3` or `cc` print a skip notice and return when the tool
is unavailable.
## Notes discovered while authoring (all since fixed)
The fixtures initially pinned three observations that were reported and then
fixed in the implementation; the goldens below reflect the fixed behaviour:
* wire floats round-trip exactly (`serde_json/float_roundtrip` is enabled), so
Python `math.pi * 9` keeps `28.274333882308138`;
* the default interpreter stack budget is 128 frames so a deeply recursive
document returns a structured `resource.exhausted` instead of exhausting the
native debug-build stack (`--stack` can raise it deliberately);
* an external-link call form (`> [x](https://example.com)()`) is rejected with
`ref.unresolved`, the same code used for other unresolvable call targets.
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 14
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 0,
"end": 14
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 14
},
"literal": "一级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
# 一级标题
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "text",
"span": {
"start": 3,
"end": 15
},
"literal": "二级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
## 二级标题
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "heading",
"level": 3,
"setext": false,
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "text",
"span": {
"start": 4,
"end": 16
},
"literal": "三级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
### 三级标题
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 17
},
"children": [
{
"kind": "heading",
"level": 4,
"setext": false,
"span": {
"start": 0,
"end": 17
},
"children": [
{
"kind": "text",
"span": {
"start": 5,
"end": 17
},
"literal": "四级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
#### 四级标题
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 18
},
"children": [
{
"kind": "heading",
"level": 5,
"setext": false,
"span": {
"start": 0,
"end": 18
},
"children": [
{
"kind": "text",
"span": {
"start": 6,
"end": 18
},
"literal": "五级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
##### 五级标题
+28
View File
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 19
},
"children": [
{
"kind": "heading",
"level": 6,
"setext": false,
"span": {
"start": 0,
"end": 19
},
"children": [
{
"kind": "text",
"span": {
"start": 7,
"end": 19
},
"literal": "六级标题"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
###### 六级标题
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 12
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 0,
"end": 12
},
"children": [
{
"kind": "text",
"span": {
"start": 3,
"end": 9
},
"literal": "函数"
}
]
}
]
}
@@ -0,0 +1 @@
## 函数 ##
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": true,
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 12
},
"literal": "一级标题"
}
]
}
]
}
@@ -0,0 +1,2 @@
一级标题
========
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": true,
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 12
},
"literal": "函数标题"
}
]
}
]
}
@@ -0,0 +1,2 @@
函数标题
--------
@@ -0,0 +1,47 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 25
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 8
},
"literal": "数学"
}
]
},
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 10,
"end": 25
},
"children": [
{
"kind": "text",
"span": {
"start": 13,
"end": 25
},
"literal": "阶乘计算"
}
]
}
]
}
@@ -0,0 +1,3 @@
# 数学
## 阶乘计算
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 20
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 0,
"end": 20
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 20
},
"literal": "统计 📊 报告"
}
]
}
]
}
@@ -0,0 +1 @@
# 统计 📊 报告
@@ -0,0 +1,35 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 13
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 0,
"end": 5
}
},
{
"kind": "paragraph",
"span": {
"start": 7,
"end": 13
},
"children": [
{
"kind": "text",
"span": {
"start": 7,
"end": 13
},
"literal": "正文"
}
]
}
]
}
@@ -0,0 +1,3 @@
##
正文
@@ -0,0 +1,70 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 33
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 0,
"end": 33
},
"children": [
{
"kind": "strong",
"span": {
"start": 3,
"end": 13
},
"children": [
{
"kind": "text",
"span": {
"start": 5,
"end": 11
},
"literal": "加粗"
}
]
},
{
"kind": "text",
"span": {
"start": 13,
"end": 18
},
"literal": " 与 "
},
{
"kind": "emph",
"span": {
"start": 18,
"end": 26
},
"children": [
{
"kind": "text",
"span": {
"start": 19,
"end": 25
},
"literal": "斜体"
}
]
},
{
"kind": "text",
"span": {
"start": 26,
"end": 33
},
"literal": " 标题"
}
]
}
]
}
@@ -0,0 +1 @@
## **加粗** 与 *斜体* 标题
@@ -0,0 +1,37 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 22
},
"children": [
{
"kind": "block_quote",
"span": {
"start": 0,
"end": 22
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 2,
"end": 22
},
"children": [
{
"kind": "text",
"span": {
"start": 4,
"end": 22
},
"literal": "引用中的标题"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
> # 引用中的标题
@@ -0,0 +1,48 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 23
},
"children": [
{
"kind": "list",
"ordered": false,
"tight": true,
"span": {
"start": 0,
"end": 23
},
"children": [
{
"kind": "item",
"span": {
"start": 0,
"end": 23
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 2,
"end": 23
},
"children": [
{
"kind": "text",
"span": {
"start": 5,
"end": 23
},
"literal": "列表中的标题"
}
]
}
]
}
]
}
]
}
@@ -0,0 +1 @@
- ## 列表中的标题
@@ -0,0 +1,19 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 30
},
"children": [
{
"kind": "code_block",
"fenced": true,
"info": "markdown",
"span": {
"start": 0,
"end": 30
},
"literal": "# 不是标题\n"
}
]
}
@@ -0,0 +1,3 @@
```markdown
# 不是标题
```
@@ -0,0 +1,28 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 23
},
"children": [
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 0,
"end": 23
},
"children": [
{
"kind": "text",
"span": {
"start": 5,
"end": 21
},
"literal": "多个 空格"
}
]
}
]
}
@@ -0,0 +1 @@
## 多个 空格
@@ -0,0 +1,66 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 49
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 0,
"end": 14
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 14
},
"literal": "命名空间"
}
]
},
{
"kind": "heading",
"level": 3,
"setext": false,
"span": {
"start": 16,
"end": 38
},
"children": [
{
"kind": "text",
"span": {
"start": 20,
"end": 38
},
"literal": "直接跳到三级"
}
]
},
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 40,
"end": 49
},
"children": [
{
"kind": "text",
"span": {
"start": 43,
"end": 49
},
"literal": "函数"
}
]
}
]
}
@@ -0,0 +1,5 @@
# 命名空间
### 直接跳到三级
## 函数
@@ -0,0 +1,26 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 30
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 30
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 30
},
"literal": "一段普通的中文叙述。"
}
]
}
]
}
@@ -0,0 +1 @@
一段普通的中文叙述。
@@ -0,0 +1,56 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 47
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 47
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 15
},
"literal": "第一行叙述"
},
{
"kind": "soft_break",
"span": {
"start": 15,
"end": 16
}
},
{
"kind": "text",
"span": {
"start": 16,
"end": 31
},
"literal": "第二行叙述"
},
{
"kind": "soft_break",
"span": {
"start": 31,
"end": 32
}
},
{
"kind": "text",
"span": {
"start": 32,
"end": 47
},
"literal": "第三行叙述"
}
]
}
]
}
@@ -0,0 +1,3 @@
第一行叙述
第二行叙述
第三行叙述
@@ -0,0 +1,41 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 9
},
"literal": "第一行"
},
{
"kind": "line_break",
"span": {
"start": 9,
"end": 12
}
},
{
"kind": "text",
"span": {
"start": 12,
"end": 21
},
"literal": "第二行"
}
]
}
]
}
@@ -0,0 +1,2 @@
第一行
第二行
@@ -0,0 +1,41 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 20
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 20
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 9
},
"literal": "第一行"
},
{
"kind": "line_break",
"span": {
"start": 9,
"end": 11
}
},
{
"kind": "text",
"span": {
"start": 11,
"end": 20
},
"literal": "第二行"
}
]
}
]
}
@@ -0,0 +1,2 @@
第一行\
第二行
@@ -0,0 +1,7 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 0
}
}
Whitespace-only changes.
@@ -0,0 +1,7 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 5
}
}
@@ -0,0 +1,3 @@
@@ -0,0 +1,45 @@
{
"kind": "document",
"span": {
"start": 3,
"end": 30
},
"children": [
{
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"start": 3,
"end": 22
},
"children": [
{
"kind": "text",
"span": {
"start": 5,
"end": 22
},
"literal": "带 BOM 的文档"
}
]
},
{
"kind": "paragraph",
"span": {
"start": 24,
"end": 30
},
"children": [
{
"kind": "text",
"span": {
"start": 24,
"end": 30
},
"literal": "正文"
}
]
}
]
}
@@ -0,0 +1,3 @@
# 带 BOM 的文档
正文
@@ -0,0 +1,62 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 43
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 15
},
"literal": "引言段落。"
}
]
},
{
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"start": 17,
"end": 26
},
"children": [
{
"kind": "text",
"span": {
"start": 20,
"end": 26
},
"literal": "函数"
}
]
},
{
"kind": "paragraph",
"span": {
"start": 28,
"end": 43
},
"children": [
{
"kind": "text",
"span": {
"start": 28,
"end": 43
},
"literal": "正文段落。"
}
]
}
]
}
@@ -0,0 +1,5 @@
引言段落。
## 函数
正文段落。
@@ -0,0 +1,35 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "strong",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 8
},
"literal": "粗体"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
**粗体**
@@ -0,0 +1,35 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "strong",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 8
},
"literal": "粗体"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
__粗体__
@@ -0,0 +1,35 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "text",
"span": {
"start": 1,
"end": 7
},
"literal": "斜体"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
*斜体*
@@ -0,0 +1,35 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 8
},
"children": [
{
"kind": "text",
"span": {
"start": 1,
"end": 7
},
"literal": "斜体"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
_斜体_
@@ -0,0 +1,44 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "strong",
"span": {
"start": 1,
"end": 14
},
"children": [
{
"kind": "text",
"span": {
"start": 3,
"end": 12
},
"literal": "粗斜体"
}
]
}
]
}
]
}
]
}
@@ -0,0 +1 @@
***粗斜体***
@@ -0,0 +1,60 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "strong",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "text",
"span": {
"start": 2,
"end": 15
},
"literal": "粗体中的 "
},
{
"kind": "emph",
"span": {
"start": 15,
"end": 23
},
"children": [
{
"kind": "text",
"span": {
"start": 16,
"end": 22
},
"literal": "斜体"
}
]
},
{
"kind": "text",
"span": {
"start": 23,
"end": 30
},
"literal": " 文本"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
**粗体中的 *斜体* 文本**
@@ -0,0 +1,60 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 32
},
"children": [
{
"kind": "text",
"span": {
"start": 1,
"end": 14
},
"literal": "斜体中的 "
},
{
"kind": "strong",
"span": {
"start": 14,
"end": 24
},
"children": [
{
"kind": "text",
"span": {
"start": 16,
"end": 22
},
"literal": "粗体"
}
]
},
{
"kind": "text",
"span": {
"start": 24,
"end": 31
},
"literal": " 文本"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
*斜体中的 **粗体** 文本*
@@ -0,0 +1,26 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 28
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 28
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 28
},
"literal": "snake_case_name 不是强调"
}
]
}
]
}
@@ -0,0 +1 @@
snake_case_name 不是强调
@@ -0,0 +1,50 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 15
},
"children": [
{
"kind": "text",
"span": {
"start": 1,
"end": 7
},
"literal": "多行"
},
{
"kind": "soft_break",
"span": {
"start": 7,
"end": 8
}
},
{
"kind": "text",
"span": {
"start": 8,
"end": 14
},
"literal": "斜体"
}
]
}
]
}
]
}
@@ -0,0 +1,2 @@
*多行
斜体*
@@ -0,0 +1,76 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 36
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 36
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 6
},
"literal": "这是"
},
{
"kind": "strong",
"span": {
"start": 6,
"end": 16
},
"children": [
{
"kind": "text",
"span": {
"start": 8,
"end": 14
},
"literal": "加粗"
}
]
},
{
"kind": "text",
"span": {
"start": 16,
"end": 25
},
"literal": ",这是"
},
{
"kind": "emph",
"span": {
"start": 25,
"end": 33
},
"children": [
{
"kind": "text",
"span": {
"start": 26,
"end": 32
},
"literal": "斜体"
}
]
},
{
"kind": "text",
"span": {
"start": 33,
"end": 36
},
"literal": "。"
}
]
}
]
}
@@ -0,0 +1 @@
这是**加粗**,这是*斜体*。
@@ -0,0 +1,36 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 11
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 11
},
"children": [
{
"kind": "strong",
"span": {
"start": 0,
"end": 11
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 2,
"end": 9
},
"literal": "x = 1"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
**`x = 1`**
@@ -0,0 +1,36 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 9
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 9
},
"children": [
{
"kind": "emph",
"span": {
"start": 0,
"end": 9
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 1,
"end": 8
},
"literal": "n - 1"
}
]
}
]
}
]
}
@@ -0,0 +1 @@
*`n - 1`*
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 7
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 7
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 0,
"end": 7
},
"literal": "x = 1"
}
]
}
]
}
@@ -0,0 +1 @@
`x = 1`
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 7
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 7
},
"children": [
{
"kind": "code",
"ticks": 2,
"span": {
"start": 0,
"end": 7
},
"literal": "a`b"
}
]
}
]
}
@@ -0,0 +1 @@
``a`b``
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 10
},
"children": [
{
"kind": "code",
"ticks": 3,
"span": {
"start": 0,
"end": 10
},
"literal": "a``b"
}
]
}
]
}
@@ -0,0 +1 @@
```a``b```
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 0,
"end": 16
},
"literal": "保留空格"
}
]
}
]
}
@@ -0,0 +1 @@
` 保留空格 `
@@ -0,0 +1,26 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 2
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 2
},
"children": [
{
"kind": "text",
"span": {
"start": 0,
"end": 2
},
"literal": "``"
}
]
}
]
}
@@ -0,0 +1 @@
``
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 16
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 0,
"end": 16
},
"literal": "a * b / c ** d"
}
]
}
]
}
@@ -0,0 +1 @@
`a * b / c ** d`
@@ -0,0 +1,27 @@
{
"kind": "document",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "paragraph",
"span": {
"start": 0,
"end": 21
},
"children": [
{
"kind": "code",
"ticks": 1,
"span": {
"start": 0,
"end": 21
},
"literal": "第一行 第二行"
}
]
}
]
}
Loaded 100 of 511 files, more files were not shown because too many files have changed in this diff. Show more