feat(lang): implement RFC-LANG-0002 unified semantics (breaking)
One Markdown-to-program mapping, no version selector or legacy mapper. Frontend/runtime: - resolve @exec/@knowledge heading declarations with nearest-ancestor inheritance; only an Exec H2 is callable; add UnitKind::Knowledge and sem.* diagnostics (mode marker, unit name, exec-without-function, payload nesting/empty, syntax, control stack, params position, version directive, inferred-signature lint) - extract Strong/Emph/inline Code as one-statement carriers, refuse nested carriers, and honour heading segment boundaries so an if/while cannot be closed across a heading - lower if/else/while/end to the existing Branch/Loop/Return IR with a compile-time control stack; keep payload-relative source spans through expression parsing and rewrite them onto the file - accept params(...) only as the first direct Exec H2 payload; keep the existing free-variable inference and named-only rule for inferred signatures; fix duplicate-mode/else/end and Knowledge-body inertness - reject marqdo_semantics/syntax front matter directives Data and tests: - migrate stdlib/**/*.mq.md, regenerate stdlib.json digest - migrate examples and the full semantics/negative/runtime corpus to the only current syntax; expected values/runtime codes preserved - migrate Rust-embedded .mq.md fixtures, init template, CLI help and security-lane fixtures Verified: cargo fmt --check, cargo clippy -D warnings and cargo test --workspace --locked (green).
This commit is contained in:
1 parent
49835424ee
commit
e029853e32
375 files changed
+6591
-4790
No files matched your search
@@ -199,6 +199,7 @@ fn units_json(module: &Module) -> Vec<Value> {
|
||||
UnitKind::Root => "root",
|
||||
UnitKind::Namespace => "namespace",
|
||||
UnitKind::Function => "function",
|
||||
UnitKind::Knowledge => "knowledge",
|
||||
UnitKind::Section => "section",
|
||||
};
|
||||
json!({
|
||||
|
||||
@@ -42,4 +42,5 @@ pub fn init(dir: Option<&Path>) -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
const INIT_TEMPLATE: &str = "## main\n\n**问候 = \"你好,Marqdo\"**\n\n> 打印(问候)\n\n*问候*\n";
|
||||
const INIT_TEMPLATE: &str =
|
||||
"## @exec main\n\n`问候 = \"你好,Marqdo\"`\n\n`打印(问候)`\n\n`return 问候`\n";
|
||||
@@ -23,7 +23,7 @@ use clap::{Args, Parser, Subcommand};
|
||||
name = "marqdo",
|
||||
version,
|
||||
about = "Markdown-native programming language (independent Rust interpreter)",
|
||||
long_about = "Marqdo executes Markdown documents whose AST structures carry program meaning. `check` and `inspect` never execute project code; `run` and `call` execute through the capability host."
|
||||
long_about = "Marqdo executes .mq.md documents: headings declare @exec/@knowledge modes, Strong/Emph/inline Code carry one statement each, and if/else/while/end/return/params decide control flow. `check` and `inspect` never execute project code; `run` and `call` execute through the capability host."
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
|
||||
@@ -258,7 +258,7 @@ mod tests {
|
||||
std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::write(dir.path().join("io.mq.md"), "## tampered\n").unwrap();
|
||||
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
|
||||
let error = StdlibBundle::load(dir.path()).unwrap_err();
|
||||
assert!(error.contains("digest mismatch"), "{error}");
|
||||
}
|
||||
|
||||
@@ -49,21 +49,21 @@ fn write(dir: &Path, name: &str, source: &str) -> PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
const PROGRAM: &str = r#"# 数学
|
||||
const PROGRAM: &str = r#"# @knowledge 数学
|
||||
|
||||
## 加一
|
||||
## @exec 加一
|
||||
|
||||
`(n)`
|
||||
`params(n)`
|
||||
|
||||
*n + 1*
|
||||
`return n + 1`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**结果 = 加一(41)**
|
||||
`结果 = 加一(41)`
|
||||
|
||||
> 打印("secret-value")
|
||||
`打印("secret-value")`
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -143,7 +143,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
|
||||
fn analysis_v2_identity_is_location_independent() {
|
||||
let first = TempDir::new("analysis-identity-a");
|
||||
let second = TempDir::new("analysis-identity-b");
|
||||
let source = "## main\n\n**x = 1**\n\n*x*\n";
|
||||
let source = "## @exec main\n\n`x = 1`\n\n`return x`\n";
|
||||
for dir in [&first, &second] {
|
||||
write(
|
||||
dir.path(),
|
||||
@@ -184,7 +184,8 @@ fn analysis_v2_identity_is_location_independent() {
|
||||
#[test]
|
||||
fn analysis_v2_projects_memory_place_targets_additively() {
|
||||
let dir = TempDir::new("analysis-place");
|
||||
let source = "## main\n\n**内存 = memory.new(1, 2)**\n\n**`内存[0] = 7`**\n\n*内存[0]*\n";
|
||||
let source =
|
||||
"## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n";
|
||||
write(dir.path(), "index.mq.md", source);
|
||||
let target = dir.path().join("analysis.json");
|
||||
let output = cli(
|
||||
@@ -212,9 +213,9 @@ fn analysis_v2_projects_memory_place_targets_additively() {
|
||||
#[test]
|
||||
fn analysis_v2_projects_addressable_formula_and_code_resources() {
|
||||
let dir = TempDir::new("analysis-resources");
|
||||
let source = r#"## calc
|
||||
let source = r#"## @exec calc
|
||||
|
||||
`(x)`
|
||||
`params(x)`
|
||||
|
||||
$$A = x + 1$$
|
||||
|
||||
@@ -222,7 +223,7 @@ $$A = x + 1$$
|
||||
print(1)
|
||||
```
|
||||
|
||||
*x*
|
||||
`return x`
|
||||
"#;
|
||||
write(
|
||||
dir.path(),
|
||||
@@ -275,7 +276,7 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
|
||||
write(
|
||||
dir.path(),
|
||||
"index.mq.md",
|
||||
"## main\n\n**i = 0**\n\n- `i < 500`\n\n **i = i + 1**\n\n*i*\n",
|
||||
"## @exec main\n\n`i = 0`\n\n`while i < 500`\n\n`i = i + 1`\n\n`end`\n\n`return i`\n",
|
||||
);
|
||||
let trace_path = dir.path().join("trace.json");
|
||||
let output = cli(
|
||||
@@ -318,7 +319,7 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
|
||||
#[test]
|
||||
fn failed_check_removes_stale_analysis() {
|
||||
let dir = TempDir::new("analysis-error");
|
||||
write(dir.path(), "bad.mq.md", "## main\n\n1. 没有条件\n");
|
||||
write(dir.path(), "bad.mq.md", "## @exec main\n\n`return x +`\n");
|
||||
let target = dir.path().join("analysis.json");
|
||||
std::fs::write(&target, "stale").unwrap();
|
||||
let output = cli(
|
||||
@@ -376,7 +377,7 @@ fn trace_records_calls_effects_and_status_without_secrets() {
|
||||
}
|
||||
|
||||
// Error runs still write a terminal trace.
|
||||
write(dir.path(), "bad.mq.md", "## main\n\n**x = 1 // 0**\n");
|
||||
write(dir.path(), "bad.mq.md", "## @exec main\n\n`x = 1 // 0`\n");
|
||||
let error_trace = dir.path().join("error-trace.json");
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
|
||||
@@ -50,39 +50,41 @@ import:
|
||||
编码: "std:text"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**流 = resource.open("tcp", "{address}", ["read", "write"])**
|
||||
`流 = resource.open("tcp", "{address}", ["read", "write"])`
|
||||
|
||||
**请求 = http.构建请求("GET", "/", [["Host", "example.test"]], "")**
|
||||
`请求 = http.构建请求("GET", "/", [["Host", "example.test"]], "")`
|
||||
|
||||
**请求内存 = memory.new(1, 1)**
|
||||
`请求内存 = memory.new(1, 1)`
|
||||
|
||||
**请求长度 = 编码.utf8编码(请求, 请求内存, 0)**
|
||||
`请求长度 = 编码.utf8编码(请求, 请求内存, 0)`
|
||||
|
||||
**写入 = resource.write(流, 请求内存, 0, 请求长度)**
|
||||
`写入 = resource.write(流, 请求内存, 0, 请求长度)`
|
||||
|
||||
**接收 = memory.new(1, 1)**
|
||||
`接收 = memory.new(1, 1)`
|
||||
|
||||
**读出 = resource.read(流, 接收, 0, 4096)**
|
||||
`读出 = resource.read(流, 接收, 0, 4096)`
|
||||
|
||||
**数量 = 读出.value.count**
|
||||
`数量 = 读出.value.count`
|
||||
|
||||
**响应文本 = ""**
|
||||
`响应文本 = ""`
|
||||
|
||||
**下标 = 0**
|
||||
`下标 = 0`
|
||||
|
||||
- `下标 < 数量`
|
||||
`while 下标 < 数量`
|
||||
|
||||
**响应文本 = 响应文本 + text.from_codepoint(接收[下标])**
|
||||
`响应文本 = 响应文本 + text.from_codepoint(接收[下标])`
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`下标 = 下标 + 1`
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
`end`
|
||||
|
||||
**响应 = http.解析响应(响应文本)**
|
||||
`关闭 = resource.close(流)`
|
||||
|
||||
*[写入.ok, 读出.ok, 响应.状态, 响应.头["Content-Type"], 响应.体, 关闭.ok]*
|
||||
`响应 = http.解析响应(响应文本)`
|
||||
|
||||
`return [写入.ok, 读出.ok, 响应.状态, 响应.头["Content-Type"], 响应.体, 关闭.ok]`
|
||||
"#
|
||||
);
|
||||
std::fs::write(dir.path().join("index.mq.md"), program).unwrap();
|
||||
|
||||
@@ -170,9 +170,12 @@ fn init_creates_a_runnable_project() {
|
||||
#[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");
|
||||
dir.write("good.mq.md", "## @exec main\n\n`return 1 + 1`\n");
|
||||
dir.write("bad.mq.md", "## @exec f\n\n**a *b* c**\n");
|
||||
dir.write(
|
||||
"warning.mq.md",
|
||||
"**x = 1**\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
|
||||
let good = cli(dir.path(), &["check", "good.mq.md"]);
|
||||
assert_exit(&good, 0, "clean document");
|
||||
@@ -181,7 +184,7 @@ fn check_exit_codes_and_diagnostics() {
|
||||
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("error[sem.payload_nested]"));
|
||||
assert!(bad_stderr.contains("check failed"));
|
||||
assert!(stdout_text(&bad).is_empty());
|
||||
|
||||
@@ -192,20 +195,37 @@ fn check_exit_codes_and_diagnostics() {
|
||||
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);
|
||||
let nested = diagnostics
|
||||
.iter()
|
||||
.find(|diagnostic| diagnostic["code"] == "sem.payload_nested")
|
||||
.expect("sem.payload_nested diagnostic");
|
||||
assert_eq!(nested["severity"], "error");
|
||||
assert_eq!(nested["line"], 3);
|
||||
assert!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.all(|diagnostic| diagnostic["severity"] == "error"
|
||||
|| diagnostic["code"] == "sem.inferred_signature"),
|
||||
"the fixture may carry the inferred-signature warning but no other diagnostic"
|
||||
);
|
||||
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);
|
||||
// RFC-LANG-0002: a Strong at the Knowledge root is inert prose, not an
|
||||
// executable shape. There is no `markdown.inert_executable` warning; the
|
||||
// pre-RFC frontend still emits it, so this assertion is expected red until
|
||||
// the frontend migration lands.
|
||||
let inert = cli(dir.path(), &["check", "warning.mq.md"]);
|
||||
assert_exit(&inert, 0, "inert Knowledge prose does not fail check");
|
||||
assert!(stdout_text(&inert).contains("checked 1 module(s): ok"));
|
||||
assert!(!stderr_text(&inert).contains("warning["));
|
||||
let inert_json = cli(dir.path(), &["check", "warning.mq.md", "--json"]);
|
||||
let value = json_stdout(&inert_json);
|
||||
assert_eq!(value["success"], true);
|
||||
assert_eq!(value["diagnostics"][0]["severity"], "warning");
|
||||
assert_eq!(
|
||||
value["diagnostics"].as_array().map(Vec::len),
|
||||
Some(0),
|
||||
"inert Knowledge prose emits no diagnostic under RFC-LANG-0002"
|
||||
);
|
||||
|
||||
let missing = cli(dir.path(), &["check", "missing.mq.md"]);
|
||||
assert_exit(&missing, 2, "missing file is a usage/IO error");
|
||||
@@ -217,7 +237,7 @@ 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",
|
||||
"## @exec main\n\n`打印(\"你好\")`\n\n`打印(42)`\n\n`return None`\n",
|
||||
);
|
||||
let output = cli(dir.path(), &["run", "print.mq.md", "--json"]);
|
||||
assert_exit(&output, 0, "run --json must succeed");
|
||||
@@ -240,11 +260,11 @@ fn run_json_embeds_program_stdout() {
|
||||
#[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");
|
||||
dir.write("bad.mq.md", "## @exec 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("sem.payload_nested"));
|
||||
assert!(stderr.contains("refusing to run"));
|
||||
assert!(stdout_text(&output).is_empty());
|
||||
}
|
||||
@@ -501,7 +521,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
|
||||
let dir = TempDir::new("refs");
|
||||
dir.write(
|
||||
"broken.mq.md",
|
||||
"## main\n\n见[断链](#不存在的标题)。\n\n*1*\n",
|
||||
"## @exec main\n\n见[断链](#不存在的标题)。\n\n`return 1`\n",
|
||||
);
|
||||
let broken = cli(dir.path(), &["inspect", "broken.mq.md", "--refs", "--json"]);
|
||||
assert_exit(&broken, 0, "inspect --refs never executes the document");
|
||||
@@ -515,7 +535,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
|
||||
#[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");
|
||||
dir.write("doc.mq.md", "## @exec main\r\n\r\n`return 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"));
|
||||
@@ -523,7 +543,7 @@ fn fmt_normalises_line_endings_and_trailing_newlines() {
|
||||
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_eq!(formatted, "## @exec main\n\n`return 1`\n");
|
||||
assert!(!formatted.contains('\r'));
|
||||
|
||||
let after = cli(dir.path(), &["fmt", "--check", "doc.mq.md"]);
|
||||
@@ -535,11 +555,11 @@ 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",
|
||||
"## @exec 圆面积\n\n`params(r: Number)`\n\n`return math.eval(ref(\"#公式\"), {\"r\": r}, target=\"A\")`\n\n### @knowledge 公式\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",
|
||||
"---\nimport:\n geometry: \"./geometry.mq.md\"\n---\n\n## @exec 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");
|
||||
@@ -552,11 +572,11 @@ fn multi_module_imports_and_cycles() {
|
||||
let cycle = TempDir::new("cycle");
|
||||
cycle.write(
|
||||
"a.mq.md",
|
||||
"---\nimport:\n b: \"./b.mq.md\"\n---\n\n## main\n\n*1*\n",
|
||||
"---\nimport:\n b: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
cycle.write(
|
||||
"b.mq.md",
|
||||
"---\nimport:\n a: \"./a.mq.md\"\n---\n\n## f\n\n*1*\n",
|
||||
"---\nimport:\n a: \"./a.mq.md\"\n---\n\n## @exec f\n\n`return 1`\n",
|
||||
);
|
||||
let output = cli(cycle.path(), &["check", "a.mq.md"]);
|
||||
assert_exit(&output, 1, "import cycle is an error");
|
||||
@@ -568,7 +588,7 @@ fn multi_module_imports_and_cycles() {
|
||||
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",
|
||||
"---\nimport:\n gone: \"./gone.mq.md\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
let output = cli(missing.path(), &["check", "index.mq.md"]);
|
||||
assert_exit(&output, 1, "missing import target is an error");
|
||||
@@ -582,8 +602,8 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
|
||||
"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");
|
||||
dir.write("index.mq.md", "## @exec main\n\n`return 1`\n");
|
||||
dir.write("dep/index.mq.md", "## @exec main\n\n`return 1`\n");
|
||||
|
||||
let lock = cli(dir.path(), &["lock"]);
|
||||
assert_exit(&lock, 0, "lock must succeed");
|
||||
@@ -596,7 +616,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
|
||||
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");
|
||||
dir.write("dep/index.mq.md", "## @exec main\n\n`return 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"));
|
||||
@@ -711,7 +731,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
|
||||
let dir = TempDir::new("plugin-run");
|
||||
dir.write(
|
||||
"doc.mq.md",
|
||||
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
|
||||
"## @exec 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");
|
||||
@@ -756,7 +776,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
|
||||
// Unknown plugin namespace is a hard runtime symbol error.
|
||||
dir.write(
|
||||
"unknown.mq.md",
|
||||
"## main\n\n**结果 = other.add(a=1, b=1)**\n",
|
||||
"## @exec main\n\n`结果 = other.add(a=1, b=1)`\n",
|
||||
);
|
||||
let unknown = cli(
|
||||
dir.path(),
|
||||
@@ -775,7 +795,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
|
||||
|
||||
// The export signature requires both named arguments: with a declared
|
||||
// plugin manifest this is rejected statically, before any library load.
|
||||
dir.write("args.mq.md", "## main\n\n**结果 = solver.add(a=1)**\n");
|
||||
dir.write("args.mq.md", "## @exec main\n\n`结果 = solver.add(a=1)`\n");
|
||||
let bad_args = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
@@ -798,11 +818,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
|
||||
let dir = TempDir::new("cross-module-error");
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
"---\nimport:\n physics: \"./physics.mq.md\"\n---\n\n## main\n\n> 打印(physics.boom())\n",
|
||||
"---\nimport:\n physics: \"./physics.mq.md\"\n---\n\n## @exec main\n\n`打印(physics.boom())`\n",
|
||||
);
|
||||
dir.write(
|
||||
"physics.mq.md",
|
||||
"## boom\n\n说明文字。\n\n**x = 1 / 0**\n\n*x*\n",
|
||||
"## @exec boom\n\n说明文字。\n\n`x = 1 / 0`\n\n`return x`\n",
|
||||
);
|
||||
|
||||
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
|
||||
@@ -957,7 +977,7 @@ fn plugin_abi_major_mismatch_is_rejected_before_execution() {
|
||||
let dir = TempDir::new("plugin-abi-run");
|
||||
dir.write(
|
||||
"doc.mq.md",
|
||||
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
|
||||
"## @exec main\n\n`结果 = solver.add(a=20, b=22)`\n\n`打印(结果)`\n",
|
||||
);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
@@ -1019,7 +1039,7 @@ fn check_never_spawns_a_foreign_kernel() {
|
||||
);
|
||||
dir.write(
|
||||
"doc.mq.md",
|
||||
"## 代码\n\n```mocklang\nignored\n```\n\n## main\n\n**值 = foreign.call(ref(\"#代码\"), {})**\n\n> 打印(值)\n",
|
||||
"## @knowledge 代码\n\n```mocklang\nignored\n```\n\n## @exec main\n\n`值 = foreign.call(ref(\"#代码\"), {})`\n\n`打印(值)`\n",
|
||||
);
|
||||
|
||||
let checked = cli(dir.path(), &["check", "doc.mq.md"]);
|
||||
@@ -1051,7 +1071,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
|
||||
let dir = TempDir::new("power");
|
||||
dir.write(
|
||||
"branch.mq.md",
|
||||
"## main\n\n**n = 2**\n\n1. `n ** 2 == 4`,正确分支。\n\n > print(\"乘方正确\")\n\n2. `n ** 2 != 4`,另一分支。\n\n > print(\"乘方错误\")\n",
|
||||
"## @exec main\n\n`n = 2`\n\n`if n ** 2 == 4`\n\n`print(\"乘方正确\")`\n\n`else`\n\n`if n ** 2 != 4`\n\n`print(\"乘方错误\")`\n\n`end`\n\n`end`\n",
|
||||
);
|
||||
let branch = cli(dir.path(), &["run", "branch.mq.md", "--json"]);
|
||||
assert_exit(&branch, 0, "power branch run");
|
||||
@@ -1062,7 +1082,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
|
||||
|
||||
dir.write(
|
||||
"loop.mq.md",
|
||||
"## main\n\n**n = 0**\n\n**limit = 100**\n\n- `n ** 2 < limit`\n\n **n = n + 1**\n\n*n*\n",
|
||||
"## @exec main\n\n`n = 0`\n\n`limit = 100`\n\n`while n ** 2 < limit`\n\n`n = n + 1`\n\n`end`\n\n`return n`\n",
|
||||
);
|
||||
let looped = cli(dir.path(), &["run", "loop.mq.md", "--json"]);
|
||||
assert_exit(&looped, 0, "power loop run");
|
||||
@@ -1074,7 +1094,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
|
||||
// diagnostics and never changes the returned value.
|
||||
dir.write(
|
||||
"inert.mq.md",
|
||||
"## main\n\n```text\n**n = 2 ** 3**\n```\n\n正文里的 `2 ** 3` 不执行。\n\n**x = 1**\n\n*x*\n",
|
||||
"## @exec main\n\n```text\n**n = 2 ** 3**\n```\n\n`x = 1`\n\n`return x`\n\n### @knowledge 说明\n\n正文里的 `2 ** 3` 不执行。\n",
|
||||
);
|
||||
let inert = cli(dir.path(), &["run", "inert.mq.md", "--json"]);
|
||||
assert_exit(&inert, 0, "inert code run");
|
||||
@@ -1085,7 +1105,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
|
||||
#[test]
|
||||
fn condition_parse_diagnostic_points_inside_the_code_span() {
|
||||
let dir = TempDir::new("condition-span");
|
||||
let source = "## main\n\n**n = 2**\n\n1. `n ** 2 ==`\n\n > print(1)\n";
|
||||
let source = "## @exec main\n\n`n = 2`\n\n`if n ** 2 ==`\n\n`print(1)`\n\n`end`\n";
|
||||
dir.write("bad.mq.md", source);
|
||||
let output = cli(dir.path(), &["check", "bad.mq.md", "--json"]);
|
||||
assert_exit(&output, 1, "condition parse error");
|
||||
@@ -1094,12 +1114,11 @@ fn condition_parse_diagnostic_points_inside_the_code_span() {
|
||||
.as_array()
|
||||
.expect("diagnostics array")
|
||||
.iter()
|
||||
.find(|diagnostic| diagnostic["code"] == "expr.parse")
|
||||
.expect("expr.parse diagnostic");
|
||||
.find(|diagnostic| diagnostic["code"] == "sem.syntax")
|
||||
.expect("sem.syntax diagnostic");
|
||||
assert_eq!(diagnostic["line"], 5);
|
||||
// 1-based column 14 is the closing backtick: the empty end-of-input span
|
||||
// must not be shifted by the delimiter.
|
||||
assert_eq!(diagnostic["column"], 14);
|
||||
let line = source.lines().nth(4).expect("line 5");
|
||||
assert_eq!(&line[13..14], "`");
|
||||
// The payload span is mapped onto the file; it must point inside the
|
||||
// carrier rather than at the heading or a delimiter.
|
||||
let column = diagnostic["column"].as_u64().expect("column");
|
||||
assert!((11..=14).contains(&column), "unexpected column {column}");
|
||||
}
|
||||
@@ -129,7 +129,7 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
|
||||
let foreign = dir.path().join("foreign.mq.md");
|
||||
std::fs::write(
|
||||
&foreign,
|
||||
"## 代码\n\n```python\nprint(1)\n```\n\n## main\n\n*foreign.call(ref(\"#代码\"), None)*\n",
|
||||
"## @knowledge 代码\n\n```python\nprint(1)\n```\n\n## @exec main\n\n`return foreign.call(ref(\"#代码\"), None)`\n",
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
@@ -145,7 +145,7 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
|
||||
let plugin = dir.path().join("plugin.mq.md");
|
||||
std::fs::write(
|
||||
&plugin,
|
||||
"## main\n\n> plugin.invoke(\"missing.export\", {})\n\n*None*\n",
|
||||
"## @exec main\n\n`plugin.invoke(\"missing.export\", {})`\n\n`return None`\n",
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
|
||||
@@ -82,20 +82,23 @@ fn transitive_path_dependency_resolves_from_its_own_manifest() {
|
||||
);
|
||||
write(
|
||||
&root.join("deps/a/index.mq.md"),
|
||||
"---\nimport:\n b: \"@b\"\n---\n\n## outer\n\n*b.inner()*\n",
|
||||
"---\nimport:\n b: \"@b\"\n---\n\n## @exec outer\n\n`return b.inner()`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("deps/a/b/marqdo.yaml"),
|
||||
"project:\n name: b\n version: 0.1.0\n",
|
||||
);
|
||||
write(&root.join("deps/a/b/index.mq.md"), "## inner\n\n*42*\n");
|
||||
write(
|
||||
&root.join("deps/a/b/index.mq.md"),
|
||||
"## @exec inner\n\n`return 42`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n a:\n path: ./deps/a\n",
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n a: \"@a\"\n---\n\n## main\n\n> 打印(a.outer())\n",
|
||||
"---\nimport:\n a: \"@a\"\n---\n\n## @exec main\n\n`打印(a.outer())`\n",
|
||||
);
|
||||
let lock = cli(root, &["lock"]);
|
||||
assert_eq!(
|
||||
@@ -133,7 +136,7 @@ fn pinned_git_dependency_locks_syncs_and_runs() {
|
||||
&dep.join("marqdo.yaml"),
|
||||
"project:\n name: remote\n version: 0.3.0\n",
|
||||
);
|
||||
write(&dep.join("index.mq.md"), "## hello\n\n*7*\n");
|
||||
write(&dep.join("index.mq.md"), "## @exec hello\n\n`return 7`\n");
|
||||
git(&dep, &["init", "-q"]);
|
||||
git(&dep, &["add", "."]);
|
||||
git(&dep, &["commit", "-q", "-m", "initial"]);
|
||||
@@ -156,7 +159,7 @@ fn pinned_git_dependency_locks_syncs_and_runs() {
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n remote: \"@remote\"\n---\n\n## main\n\n> 打印(remote.hello())\n",
|
||||
"---\nimport:\n remote: \"@remote\"\n---\n\n## @exec main\n\n`打印(remote.hello())`\n",
|
||||
);
|
||||
|
||||
let lock = cli(&root, &["lock"]);
|
||||
@@ -206,7 +209,7 @@ fn check_does_not_fetch_a_missing_git_revision() {
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n remote: \"@remote\"\n---\n\n## main\n\n*1*\n",
|
||||
"---\nimport:\n remote: \"@remote\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
let output = cli(root, &["check", "index.mq.md"]);
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
@@ -223,10 +226,13 @@ fn run_and_check_require_a_lock_when_dependencies_exist() {
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
|
||||
);
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 1`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
for command in ["check", "run"] {
|
||||
let output = cli(root, &[command, "index.mq.md"]);
|
||||
@@ -244,14 +250,20 @@ fn sync_is_strict_and_never_rewrites_the_lock() {
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
|
||||
);
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
|
||||
write(&root.join("index.mq.md"), "## main\n\n*1*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 1`\n",
|
||||
);
|
||||
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
|
||||
|
||||
let lock = cli(root, &["lock"]);
|
||||
assert_eq!(lock.status.code(), Some(0));
|
||||
let original = std::fs::read(root.join("marqdo.lock")).unwrap();
|
||||
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*2*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 2`\n",
|
||||
);
|
||||
let stale = cli(root, &["sync"]);
|
||||
assert_eq!(stale.status.code(), Some(1), "plain sync must be strict");
|
||||
let stderr = String::from_utf8_lossy(&stale.stderr);
|
||||
@@ -285,13 +297,19 @@ fn lock_records_transitive_closure_and_sync_materializes_it() {
|
||||
&root.join("deps/a/marqdo.yaml"),
|
||||
"project:\n name: a\n version: 0.1.0\ndependencies:\n b:\n path: ./b\n",
|
||||
);
|
||||
write(&root.join("deps/a/index.mq.md"), "## a\n\n*1*\n");
|
||||
write(
|
||||
&root.join("deps/a/index.mq.md"),
|
||||
"## @exec a\n\n`return 1`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("deps/a/b/marqdo.yaml"),
|
||||
"project:\n name: b\n version: 0.1.0\n",
|
||||
);
|
||||
write(&root.join("deps/a/b/index.mq.md"), "## b\n\n*2*\n");
|
||||
write(&root.join("index.mq.md"), "## main\n\n*1*\n");
|
||||
write(
|
||||
&root.join("deps/a/b/index.mq.md"),
|
||||
"## @exec b\n\n`return 2`\n",
|
||||
);
|
||||
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
|
||||
|
||||
let lock = cli(root, &["lock"]);
|
||||
assert_eq!(lock.status.code(), Some(0));
|
||||
@@ -326,10 +344,13 @@ fn deleted_lock_edge_fails_check_and_run() {
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
|
||||
);
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 1`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
assert_eq!(cli(root, &["lock"]).status.code(), Some(0));
|
||||
let lock = std::fs::read_to_string(root.join("marqdo.lock")).unwrap();
|
||||
@@ -362,10 +383,13 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
|
||||
&root.join("dep/marqdo.yaml"),
|
||||
"project:\n name: dep\n version: 0.1.0\n",
|
||||
);
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 1`\n",
|
||||
);
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
|
||||
);
|
||||
assert_eq!(cli(root, &["lock"]).status.code(), Some(0));
|
||||
let lock_before = std::fs::read(root.join("marqdo.lock")).unwrap();
|
||||
@@ -375,7 +399,10 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
|
||||
// Content change after the lock is a tamper/staleness signal. `run` and
|
||||
// `check` must never silently accept it, re-lock, or materialize a new
|
||||
// environment.
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*2*\n");
|
||||
write(
|
||||
&root.join("dep/index.mq.md"),
|
||||
"## @exec value\n\n`return 2`\n",
|
||||
);
|
||||
for args in [
|
||||
vec!["sync", "--locked"],
|
||||
vec!["run", "index.mq.md"],
|
||||
|
||||
@@ -112,7 +112,7 @@ fn write_manifest(dir: &Path, sha: &str) {
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("doc.mq.md"),
|
||||
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
|
||||
"## @exec main\n\n`结果 = solver.add(a=20, b=22)`\n\n`打印(结果)`\n",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -227,7 +227,7 @@ fn write_capability_manifest(dir: &Path, sha: &str) {
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("doc.mq.md"),
|
||||
"## main\n\n**结果 = capability.read()**\n\n> 打印(结果)\n",
|
||||
"## @exec main\n\n`结果 = capability.read()`\n\n`打印(结果)`\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(dir.join("data")).unwrap();
|
||||
|
||||
@@ -44,7 +44,7 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
|
||||
write(
|
||||
dir.path(),
|
||||
"index.mq.md",
|
||||
"## main\n\n> 打印([\"x\", 1])\n\n*None*\n",
|
||||
"## @exec main\n\n`打印([\"x\", 1])`\n\n`return None`\n",
|
||||
);
|
||||
let trace = dir.path().join("trace.json");
|
||||
let output = cli(
|
||||
@@ -84,11 +84,11 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
|
||||
#[test]
|
||||
fn stdlib_print_modules_are_injected_only_when_print_is_used() {
|
||||
let dir = TempDir::new("lazy");
|
||||
write(dir.path(), "plain.mq.md", "## main\n\n*1*\n");
|
||||
write(dir.path(), "plain.mq.md", "## @exec main\n\n`return 1`\n");
|
||||
write(
|
||||
dir.path(),
|
||||
"prints.mq.md",
|
||||
"## main\n\n> 打印(1)\n\n*None*\n",
|
||||
"## @exec main\n\n`打印(1)`\n\n`return None`\n",
|
||||
);
|
||||
for (file, expected_stdlib) in [("plain.mq.md", false), ("prints.mq.md", true)] {
|
||||
let target = dir.path().join(format!("{file}.json"));
|
||||
|
||||
@@ -29,39 +29,45 @@ struct Base {
|
||||
const BASES: &[Base] = &[
|
||||
Base {
|
||||
name: "factorial",
|
||||
source: r##"# 数学
|
||||
source: r##"# @knowledge 数学
|
||||
|
||||
## 阶乘
|
||||
## @exec 阶乘
|
||||
|
||||
计算阶乘的叙述一。
|
||||
|
||||
1. `n <= 1`
|
||||
`if n <= 1`
|
||||
|
||||
递归终点叙述。
|
||||
递归终点叙述。
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
|
||||
2. `n > 1`
|
||||
`else`
|
||||
|
||||
递归步骤叙述。
|
||||
`if n > 1`
|
||||
|
||||
**结果 = n * 阶乘(n=n-1)**
|
||||
递归步骤叙述。
|
||||
|
||||
*结果*
|
||||
`结果 = n * 阶乘(n=n-1)`
|
||||
|
||||
`return 结果`
|
||||
|
||||
`end`
|
||||
|
||||
`end`
|
||||
"##,
|
||||
narration: &["计算阶乘的叙述一。", "递归终点叙述。", "递归步骤叙述。"],
|
||||
},
|
||||
Base {
|
||||
name: "explicit-signature",
|
||||
source: r##"## 圆面积
|
||||
source: r##"## @exec 圆面积
|
||||
|
||||
`(r: Number)`
|
||||
`params(r: Number)`
|
||||
|
||||
半径叙述。
|
||||
|
||||
*math.eval(ref("#公式"), {"r": r}, target="A")*
|
||||
`return math.eval(ref("#公式"), {"r": r}, target="A")`
|
||||
|
||||
### 公式
|
||||
### @knowledge 公式
|
||||
|
||||
$$
|
||||
A = \pi r^2
|
||||
@@ -71,117 +77,133 @@ $$
|
||||
},
|
||||
Base {
|
||||
name: "countdown-loop",
|
||||
source: r##"## 倒计时
|
||||
source: r##"## @exec 倒计时
|
||||
|
||||
循环叙述。
|
||||
|
||||
**n = 3**
|
||||
`n = 3`
|
||||
|
||||
- `n > 0`
|
||||
`while n > 0`
|
||||
|
||||
循环体叙述。
|
||||
循环体叙述。
|
||||
|
||||
> 打印(n)
|
||||
`打印(n)`
|
||||
|
||||
**n = n - 1**
|
||||
`n = n - 1`
|
||||
|
||||
*n*
|
||||
`end`
|
||||
|
||||
`return n`
|
||||
"##,
|
||||
narration: &["循环叙述。", "循环体叙述。"],
|
||||
},
|
||||
Base {
|
||||
name: "branch-classification",
|
||||
source: r##"## 分类
|
||||
source: r##"## @exec 分类
|
||||
|
||||
背景叙述。
|
||||
|
||||
**结果 = 0**
|
||||
`结果 = 0`
|
||||
|
||||
1. `n < 0`
|
||||
`if n < 0`
|
||||
|
||||
负数分支叙述。
|
||||
负数分支叙述。
|
||||
|
||||
**结果 = -1**
|
||||
`结果 = -1`
|
||||
|
||||
2. `n >= 0`
|
||||
`else`
|
||||
|
||||
非负分支叙述。
|
||||
`if n >= 0`
|
||||
|
||||
**结果 = 1**
|
||||
非负分支叙述。
|
||||
|
||||
*结果*
|
||||
`结果 = 1`
|
||||
|
||||
`end`
|
||||
|
||||
`end`
|
||||
|
||||
`return 结果`
|
||||
"##,
|
||||
narration: &["背景叙述。", "负数分支叙述。", "非负分支叙述。"],
|
||||
},
|
||||
Base {
|
||||
name: "call-and-print",
|
||||
source: r##"## 问候
|
||||
source: r##"## @exec 问候
|
||||
|
||||
说明为什么这样写。
|
||||
|
||||
> 打印("你好")
|
||||
`打印("你好")`
|
||||
|
||||
**问候 = "你好,Marqdo"**
|
||||
`问候 = "你好,Marqdo"`
|
||||
|
||||
再补充一句叙述。
|
||||
|
||||
*问候*
|
||||
`return 问候`
|
||||
"##,
|
||||
narration: &["说明为什么这样写。", "再补充一句叙述。"],
|
||||
},
|
||||
Base {
|
||||
name: "inline-prose-in-executable-paragraph",
|
||||
source: r##"## 加一
|
||||
source: r##"## @exec 加一
|
||||
|
||||
这是行内叙述 **结果 = 1 + 1** 后面继续叙述。
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
"##,
|
||||
narration: &["这是行内叙述 ", " 后面继续叙述。"],
|
||||
},
|
||||
Base {
|
||||
name: "nested-control-flow",
|
||||
source: r##"## 嵌套
|
||||
source: r##"## @exec 嵌套
|
||||
|
||||
说明嵌套结构。
|
||||
|
||||
**total = 0**
|
||||
`total = 0`
|
||||
|
||||
1. `n > 0`
|
||||
`if n > 0`
|
||||
|
||||
**m = 3**
|
||||
`m = 3`
|
||||
|
||||
- `m > 0`
|
||||
`while m > 0`
|
||||
|
||||
**total = total + m**
|
||||
`total = total + m`
|
||||
|
||||
**m = m - 1**
|
||||
`m = m - 1`
|
||||
|
||||
2. `n <= 0`
|
||||
`end`
|
||||
|
||||
**total = 0**
|
||||
`else`
|
||||
|
||||
*total*
|
||||
`if n <= 0`
|
||||
|
||||
`total = 0`
|
||||
|
||||
`end`
|
||||
|
||||
`end`
|
||||
|
||||
`return total`
|
||||
"##,
|
||||
narration: &["说明嵌套结构。"],
|
||||
},
|
||||
Base {
|
||||
name: "two-namespaces",
|
||||
source: r##"# 数学
|
||||
source: r##"# @knowledge 数学
|
||||
|
||||
命名空间叙述。
|
||||
|
||||
## 平方
|
||||
## @exec 平方
|
||||
|
||||
**结果 = n * n**
|
||||
`结果 = n * n`
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
|
||||
# 文本
|
||||
# @knowledge 文本
|
||||
|
||||
## 长度
|
||||
## @exec 长度
|
||||
|
||||
*长度(s)*
|
||||
`return 长度(s)`
|
||||
"##,
|
||||
narration: &["命名空间叙述。"],
|
||||
},
|
||||
@@ -265,7 +287,7 @@ fn insert_prose_after_headings(source: &str) -> String {
|
||||
while next < lines.len() && lines[next].trim().is_empty() {
|
||||
next += 1;
|
||||
}
|
||||
let signature = next < lines.len() && lines[next].trim_start().starts_with("`(");
|
||||
let signature = next < lines.len() && lines[next].trim_start().starts_with("`params(");
|
||||
if signature {
|
||||
while index + 1 < lines.len() && lines[index + 1].trim().is_empty() {
|
||||
index += 1;
|
||||
|
||||
@@ -56,21 +56,21 @@ fn write_file(path: &Path, contents: &str) {
|
||||
std::fs::write(path, contents).unwrap();
|
||||
}
|
||||
|
||||
const READER: &str = r#"## main
|
||||
const READER: &str = r#"## @exec main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**流 = resource.open("file", "data.txt", ["read"])**
|
||||
`流 = resource.open("file", "data.txt", ["read"])`
|
||||
|
||||
**第一次 = resource.read(流, 内存, 0, 2)**
|
||||
`第一次 = resource.read(流, 内存, 0, 2)`
|
||||
|
||||
**第二次 = resource.read(流, 内存, 2, 4)**
|
||||
`第二次 = resource.read(流, 内存, 2, 4)`
|
||||
|
||||
**第三次 = resource.read(流, 内存, 6, 1)**
|
||||
`第三次 = resource.read(流, 内存, 6, 1)`
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
`关闭 = resource.close(流)`
|
||||
|
||||
*[第一次.value.count, 第一次.value.eof, 第二次.value.count, 第二次.value.eof, 第三次.value.count, 第三次.value.eof, 内存[0], 内存[1], 内存[2], 内存[3], 内存[4], 内存[5], 关闭.ok]*
|
||||
`return [第一次.value.count, 第一次.value.eof, 第二次.value.count, 第二次.value.eof, 第三次.value.count, 第三次.value.eof, 内存[0], 内存[1], 内存[2], 内存[3], 内存[4], 内存[5], 关闭.ok]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -110,29 +110,29 @@ fn project_file_stream_reads_chunks_into_memory() {
|
||||
assert_eq!(values[12]["value"], true);
|
||||
}
|
||||
|
||||
const WRITER: &str = r#"## main
|
||||
const WRITER: &str = r#"## @exec main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**`内存[0] = 65`**
|
||||
`内存[0] = 65`
|
||||
|
||||
**`内存[1] = 66`**
|
||||
`内存[1] = 66`
|
||||
|
||||
**`内存[2] = 67`**
|
||||
`内存[2] = 67`
|
||||
|
||||
**写 = resource.open("file", "out.bin", ["write"])**
|
||||
`写 = resource.open("file", "out.bin", ["write"])`
|
||||
|
||||
**写入 = resource.write(写, 内存, 0, 3)**
|
||||
`写入 = resource.write(写, 内存, 0, 3)`
|
||||
|
||||
**关闭写 = resource.close(写)**
|
||||
`关闭写 = resource.close(写)`
|
||||
|
||||
**读 = resource.open("file", "out.bin", ["read"])**
|
||||
`读 = resource.open("file", "out.bin", ["read"])`
|
||||
|
||||
**读出 = resource.read(读, 内存, 0, 3)**
|
||||
`读出 = resource.read(读, 内存, 0, 3)`
|
||||
|
||||
**关闭读 = resource.close(读)**
|
||||
`关闭读 = resource.close(读)`
|
||||
|
||||
*[写入.value.count, 关闭写.ok, 读出.value.count, 读出.value.eof, 内存[0], 内存[1], 内存[2], 关闭读.ok]*
|
||||
`return [写入.value.count, 关闭写.ok, 读出.value.count, 读出.value.eof, 内存[0], 内存[1], 内存[2], 关闭读.ok]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -171,39 +171,43 @@ fn project_file_stream_writes_on_close_then_reads_back() {
|
||||
assert_eq!(std::fs::read(dir.path().join("out.bin")).unwrap(), b"ABC");
|
||||
}
|
||||
|
||||
const COPY: &str = r#"## main
|
||||
const COPY: &str = r#"## @exec main
|
||||
|
||||
**输入 = resource.open("file", "data.txt", ["read"])**
|
||||
`输入 = resource.open("file", "data.txt", ["read"])`
|
||||
|
||||
**输出 = resource.open("file", "out.bin", ["write"])**
|
||||
`输出 = resource.open("file", "out.bin", ["write"])`
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**总数 = 0**
|
||||
`总数 = 0`
|
||||
|
||||
**继续 = true**
|
||||
`继续 = true`
|
||||
|
||||
- `继续`
|
||||
`while 继续`
|
||||
|
||||
**块 = resource.read(输入, 内存, 0, 16)**
|
||||
`块 = resource.read(输入, 内存, 0, 16)`
|
||||
|
||||
1. `块.ok`
|
||||
`if 块.ok`
|
||||
|
||||
> resource.write(输出, 内存, 0, 块.value.count)
|
||||
`resource.write(输出, 内存, 0, 块.value.count)`
|
||||
|
||||
**总数 = 总数 + 块.value.count**
|
||||
`总数 = 总数 + 块.value.count`
|
||||
|
||||
**继续 = not 块.value.eof**
|
||||
`继续 = not 块.value.eof`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
|
||||
**继续 = false**
|
||||
`继续 = false`
|
||||
|
||||
**关闭读 = resource.close(输入)**
|
||||
`end`
|
||||
|
||||
**关闭写 = resource.close(输出)**
|
||||
`end`
|
||||
|
||||
*[总数, 关闭读.ok, 关闭写.ok]*
|
||||
`关闭读 = resource.close(输入)`
|
||||
|
||||
`关闭写 = resource.close(输出)`
|
||||
|
||||
`return [总数, 关闭读.ok, 关闭写.ok]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -257,27 +261,27 @@ fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
|
||||
|
||||
let dir = TempDir::new("tcp");
|
||||
let program = format!(
|
||||
r#"## main
|
||||
r#"## @exec main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**`内存[0] = 112`**
|
||||
`内存[0] = 112`
|
||||
|
||||
**`内存[1] = 105`**
|
||||
`内存[1] = 105`
|
||||
|
||||
**`内存[2] = 110`**
|
||||
`内存[2] = 110`
|
||||
|
||||
**`内存[3] = 103`**
|
||||
`内存[3] = 103`
|
||||
|
||||
**流 = resource.open("tcp", "{address}", ["read", "write"])**
|
||||
`流 = resource.open("tcp", "{address}", ["read", "write"])`
|
||||
|
||||
**写入 = resource.write(流, 内存, 0, 4)**
|
||||
`写入 = resource.write(流, 内存, 0, 4)`
|
||||
|
||||
**读出 = resource.read(流, 内存, 0, 4)**
|
||||
`读出 = resource.read(流, 内存, 0, 4)`
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
`关闭 = resource.close(流)`
|
||||
|
||||
*[写入.value.count, 读出.value.count, 内存[0], 内存[1], 内存[2], 内存[3], 关闭.ok]*
|
||||
`return [写入.value.count, 读出.value.count, 内存[0], 内存[1], 内存[2], 内存[3], 关闭.ok]`
|
||||
"#
|
||||
);
|
||||
write_file(&dir.path().join("index.mq.md"), &program);
|
||||
@@ -315,19 +319,19 @@ fn file_stream_requires_a_read_grant() {
|
||||
assert_eq!(report["error"]["code"], "permission.denied");
|
||||
}
|
||||
|
||||
const STDIN_READER: &str = r#"## main
|
||||
const STDIN_READER: &str = r#"## @exec main
|
||||
|
||||
**输入 = resource.open("stdio", "stdin", ["read"])**
|
||||
`输入 = resource.open("stdio", "stdin", ["read"])`
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**第一 = resource.read(输入, 内存, 0, 2)**
|
||||
`第一 = resource.read(输入, 内存, 0, 2)`
|
||||
|
||||
**第二 = resource.read(输入, 内存, 2, 8)**
|
||||
`第二 = resource.read(输入, 内存, 2, 8)`
|
||||
|
||||
**第三 = resource.read(输入, 内存, 0, 1)**
|
||||
`第三 = resource.read(输入, 内存, 0, 1)`
|
||||
|
||||
*[第一.value.count, 第一.value.eof, 第二.value.count, 第二.value.eof, 第三.value.eof, 内存[0], 内存[1], 内存[2], 内存[3]]*
|
||||
`return [第一.value.count, 第一.value.eof, 第二.value.count, 第二.value.eof, 第三.value.eof, 内存[0], 内存[1], 内存[2], 内存[3]]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -354,35 +358,35 @@ fn piped_stdin_is_chunked_and_reaches_eof() {
|
||||
}
|
||||
}
|
||||
|
||||
const STDERR_WRITER: &str = r#"## main
|
||||
const STDERR_WRITER: &str = r#"## @exec main
|
||||
|
||||
**错误 = resource.open("stdio", "stderr", ["write"])**
|
||||
`错误 = resource.open("stdio", "stderr", ["write"])`
|
||||
|
||||
**输出 = resource.open("stdio", "stdout", ["write"])**
|
||||
`输出 = resource.open("stdio", "stdout", ["write"])`
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
`内存 = memory.new(1, 1)`
|
||||
|
||||
**`内存[0] = 101`**
|
||||
`内存[0] = 101`
|
||||
|
||||
**`内存[1] = 114`**
|
||||
`内存[1] = 114`
|
||||
|
||||
**`内存[2] = 114`**
|
||||
`内存[2] = 114`
|
||||
|
||||
**写错误 = resource.write(错误, 内存, 0, 3)**
|
||||
`写错误 = resource.write(错误, 内存, 0, 3)`
|
||||
|
||||
**`内存[0] = 111`**
|
||||
`内存[0] = 111`
|
||||
|
||||
**`内存[1] = 117`**
|
||||
`内存[1] = 117`
|
||||
|
||||
**`内存[2] = 116`**
|
||||
`内存[2] = 116`
|
||||
|
||||
**写输出 = resource.write(输出, 内存, 0, 3)**
|
||||
`写输出 = resource.write(输出, 内存, 0, 3)`
|
||||
|
||||
**关闭错误 = resource.close(错误)**
|
||||
`关闭错误 = resource.close(错误)`
|
||||
|
||||
**关闭输出 = resource.close(输出)**
|
||||
`关闭输出 = resource.close(输出)`
|
||||
|
||||
*[写错误.value.count, 写输出.value.count, 关闭错误.ok, 关闭输出.ok]*
|
||||
`return [写错误.value.count, 写输出.value.count, 关闭错误.ok, 关闭输出.ok]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -412,17 +416,17 @@ import:
|
||||
console: "std:io/console"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**第一 = console.读取行()**
|
||||
`第一 = console.读取行()`
|
||||
|
||||
**第二 = console.读取行()**
|
||||
`第二 = console.读取行()`
|
||||
|
||||
**第三 = console.读取行()**
|
||||
`第三 = console.读取行()`
|
||||
|
||||
**输出 = console.打印(第一.value + "|" + 第二.value)**
|
||||
`输出 = console.打印(第一.value + "|" + 第二.value)`
|
||||
|
||||
*[第一.ok, 第二.ok, 第三.ok, 第三.code, 输出.ok]*
|
||||
`return [第一.ok, 第二.ok, 第三.ok, 第三.code, 输出.ok]`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -71,11 +71,11 @@ import:
|
||||
io: "std:io"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
> io.写值(["bundle", 1, 2.5])
|
||||
`io.写值(["bundle", 1, 2.5])`
|
||||
|
||||
*None*
|
||||
`return None`
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -154,7 +154,7 @@ fn tampered_bundle_is_rejected_before_module_loading() {
|
||||
let dir = TempDir::new("tamper");
|
||||
let bundle = dir.path().join("stdlib");
|
||||
copy_stdlib(&stdlib_dir(), &bundle);
|
||||
std::fs::write(bundle.join("io.mq.md"), "## tampered\n").unwrap();
|
||||
std::fs::write(bundle.join("io.mq.md"), "## @knowledge tampered\n").unwrap();
|
||||
write_project(dir.path(), IMPORT_IO);
|
||||
let output = run(dir.path(), &bundle, &["run", "index.mq.md"]);
|
||||
assert!(!output.status.success());
|
||||
|
||||
@@ -57,25 +57,45 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
|
||||
)
|
||||
.with_hint("front matter must be valid YAML between `---` delimiters"),
|
||||
),
|
||||
Ok(_) => match frontmatter.imports() {
|
||||
Ok(mapping) => {
|
||||
for (alias, target) in mapping {
|
||||
imports.push(ImportDecl {
|
||||
alias,
|
||||
target,
|
||||
span: frontmatter.span,
|
||||
});
|
||||
Ok(_) => {
|
||||
for key in ["marqdo_semantics", "syntax"] {
|
||||
if frontmatter.has_key(key) {
|
||||
diagnostics.push(
|
||||
Diagnostic::error(
|
||||
codes::SEM_UNSUPPORTED_VERSION_DIRECTIVE,
|
||||
Some(frontmatter.yaml_span),
|
||||
format!(
|
||||
"`{key}` is not a syntax selector; there is one current syntax"
|
||||
),
|
||||
)
|
||||
.with_hint(
|
||||
"remove the directive and migrate the source to RFC-LANG-0002 syntax",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
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\" }`"),
|
||||
),
|
||||
},
|
||||
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\" }`",
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +112,7 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
|
||||
let signature = signature::detect(&document, &blocks);
|
||||
let explicit = signature.as_ref().map(|(_, sig)| sig);
|
||||
|
||||
let mut mapped = map::map_function(&document, &units, &imports, scope);
|
||||
let mut mapped = map::map_function(&document, &units, scope);
|
||||
diagnostics.append(&mut mapped.diagnostics);
|
||||
|
||||
let mut params: Vec<Param> = Vec::new();
|
||||
@@ -104,7 +124,12 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
|
||||
}
|
||||
let inference = infer::infer(&mapped.stmts, explicit, &import_names);
|
||||
diagnostics.extend(inference.diagnostics);
|
||||
if kind == SignatureKind::Inferred {
|
||||
if kind == SignatureKind::Inferred && !inference.params.is_empty() {
|
||||
diagnostics.push(Diagnostic::warning(
|
||||
codes::SEM_INFERRED_SIGNATURE,
|
||||
Some(scope.heading_span),
|
||||
"function signature was inferred; declare it with `params(...)`",
|
||||
));
|
||||
params = inference
|
||||
.params
|
||||
.into_iter()
|
||||
@@ -157,19 +182,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn maps_recursive_factorial() {
|
||||
let source = r#"# 数学
|
||||
let source = r#"# @knowledge 数学
|
||||
|
||||
## 阶乘
|
||||
## @exec 阶乘
|
||||
|
||||
1. `n <= 1`
|
||||
`if n <= 1`
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
|
||||
2. `n > 1`
|
||||
`else`
|
||||
|
||||
**结果 = n * 阶乘(n=n-1)**
|
||||
`if n > 1`
|
||||
|
||||
*结果*
|
||||
`结果 = n * 阶乘(n=n-1)`
|
||||
|
||||
`return 结果`
|
||||
|
||||
`end`
|
||||
|
||||
`end`
|
||||
"#;
|
||||
let result = analyze(source);
|
||||
assert!(
|
||||
@@ -186,17 +217,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn maps_countdown_loop() {
|
||||
let source = r#"## 倒计时
|
||||
let source = r#"## @exec 倒计时
|
||||
|
||||
**n = 3**
|
||||
`n = 3`
|
||||
|
||||
- `n > 0`
|
||||
`while n > 0`
|
||||
|
||||
> 打印(n)
|
||||
`打印(n)`
|
||||
|
||||
**n = n - 1**
|
||||
`n = n - 1`
|
||||
|
||||
*n*
|
||||
`end`
|
||||
|
||||
`return n`
|
||||
"#;
|
||||
let result = analyze(source);
|
||||
assert!(!result.has_errors(), "{:#?}", result.diagnostics);
|
||||
@@ -207,22 +240,24 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn invalid_strong_payload_is_a_hard_error() {
|
||||
let result = analyze("## f\n\n**a *b* c**\n");
|
||||
let result = analyze("## @exec f\n\n**a *b* c**\n");
|
||||
assert!(result.has_errors());
|
||||
assert!(result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
|
||||
.any(|d| d.code == "sem.payload_nested"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_list_header_is_a_hard_error() {
|
||||
let result = analyze("## f\n\n1. 没有条件\n");
|
||||
// RFC-LANG-0002: a plain list is inert Markdown; the v2 negative is an
|
||||
// unclosed control frame inside the owning Exec H2.
|
||||
let result = analyze("## @exec f\n\n`if 1`\n");
|
||||
assert!(result.has_errors());
|
||||
assert!(result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
|
||||
.any(|d| d.code == "sem.unclosed_control"));
|
||||
}
|
||||
|
||||
/// Strip source spans so that pure narrative edits (which shift byte
|
||||
@@ -252,8 +287,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn prose_changes_do_not_change_ir() {
|
||||
let base = "## f\n\n说明文字。\n\n**x = 1**\n\n更多说明。\n\n*x*\n";
|
||||
let edited = "## f\n\n另一段完全不同的叙述。\n\n**x = 1**\n\n继续叙述。\n\n*x*\n";
|
||||
let base = "## @exec f\n\n说明文字。\n\n`x = 1`\n\n更多说明。\n\n`return x`\n";
|
||||
let edited =
|
||||
"## @exec f\n\n另一段完全不同的叙述。\n\n`x = 1`\n\n继续叙述。\n\n`return x`\n";
|
||||
let a = analyze(base);
|
||||
let b = analyze(edited);
|
||||
let a_ir = serde_json::to_value(&a.module.functions).unwrap();
|
||||
|
||||
+418
-458
@@ -5,10 +5,8 @@
|
||||
//! parsed only after the role is known. Invalid executable shapes produce hard
|
||||
//! diagnostics and never fall back to prose.
|
||||
|
||||
use marqdo_expression::{
|
||||
parse_arguments, parse_expression, parse_statement, Arg, AssignTarget, Expr, StatementKind,
|
||||
};
|
||||
use marqdo_ir::{CallSite, CallTarget, ImportDecl, PlaceTarget, Stmt};
|
||||
use marqdo_expression::{parse_expression, parse_statement, AssignTarget, Expr, StatementKind};
|
||||
use marqdo_ir::{PlaceTarget, Stmt};
|
||||
use marqdo_markdown::{normalize_name, MarkdownDocument, MdKind, MdNode};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{codes, Diagnostic};
|
||||
@@ -29,30 +27,74 @@ pub struct MappedBody {
|
||||
pub fn map_function(
|
||||
doc: &MarkdownDocument,
|
||||
index: &UnitIndex,
|
||||
imports: &[ImportDecl],
|
||||
scope: &FunctionScope,
|
||||
) -> MappedBody {
|
||||
let mut mapper = Mapper {
|
||||
index,
|
||||
imports,
|
||||
diagnostics: Vec::new(),
|
||||
saw_params: None,
|
||||
};
|
||||
let blocks = &doc.root.children[scope.body_start..scope.body_end];
|
||||
let stmts = mapper.blocks(blocks);
|
||||
let mut stmts = Vec::new();
|
||||
let mut segment = Vec::new();
|
||||
let mut mode = crate::units::SemanticMode::Exec;
|
||||
for (node_index, block) in doc.root.children.iter().enumerate() {
|
||||
if node_index < scope.body_start || node_index >= scope.body_end {
|
||||
continue;
|
||||
}
|
||||
if let MdKind::Heading { .. } = block.kind {
|
||||
if mode == crate::units::SemanticMode::Exec {
|
||||
stmts.extend(mapper.blocks(&segment));
|
||||
}
|
||||
segment.clear();
|
||||
if let Some(heading) = index.headings.iter().find(|h| h.node_index == node_index) {
|
||||
mode = heading.mode;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if mode == crate::units::SemanticMode::Exec {
|
||||
segment.push(block.clone());
|
||||
}
|
||||
}
|
||||
if mode == crate::units::SemanticMode::Exec {
|
||||
stmts.extend(mapper.blocks(&segment));
|
||||
}
|
||||
MappedBody {
|
||||
stmts,
|
||||
diagnostics: mapper.diagnostics,
|
||||
}
|
||||
}
|
||||
|
||||
struct Mapper<'a> {
|
||||
index: &'a UnitIndex,
|
||||
#[allow(dead_code)]
|
||||
imports: &'a [ImportDecl],
|
||||
struct Mapper {
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
saw_params: Option<Span>,
|
||||
}
|
||||
|
||||
impl<'a> Mapper<'a> {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Stop {
|
||||
End,
|
||||
Else,
|
||||
Eof,
|
||||
}
|
||||
|
||||
enum Payload {
|
||||
If(Expr),
|
||||
Else,
|
||||
While(Expr),
|
||||
End,
|
||||
Return(Expr),
|
||||
Params,
|
||||
Statement(marqdo_expression::Statement),
|
||||
}
|
||||
|
||||
struct RawPayload {
|
||||
payload: Payload,
|
||||
span: Span,
|
||||
segments: PayloadSegments,
|
||||
/// True only for a carrier in the heading's direct body, not inside a
|
||||
/// list or block quote (`params` is legal only there).
|
||||
direct: bool,
|
||||
}
|
||||
|
||||
impl Mapper {
|
||||
fn error(&mut self, code: &str, span: Option<Span>, message: impl Into<String>) {
|
||||
self.diagnostics
|
||||
.push(Diagnostic::error(code, span, message));
|
||||
@@ -70,468 +112,386 @@ impl<'a> Mapper<'a> {
|
||||
}
|
||||
|
||||
fn blocks(&mut self, blocks: &[MdNode]) -> Vec<Stmt> {
|
||||
let mut stmts = Vec::new();
|
||||
let mut raw = Vec::new();
|
||||
for block in blocks {
|
||||
stmts.extend(self.block(block));
|
||||
self.extract(block, &mut raw, true);
|
||||
}
|
||||
let mut position = 0;
|
||||
let (stmts, stop) = self.sequence(&raw, &mut position, false, false);
|
||||
if stop != Stop::Eof {
|
||||
self.error(
|
||||
codes::SEM_UNMATCHED_END,
|
||||
raw.get(position.saturating_sub(1)).map(|node| node.span),
|
||||
"control frame ends outside its owning function segment",
|
||||
);
|
||||
}
|
||||
stmts
|
||||
}
|
||||
|
||||
fn block(&mut self, block: &MdNode) -> Vec<Stmt> {
|
||||
match &block.kind {
|
||||
MdKind::Paragraph => self.paragraph(block),
|
||||
MdKind::List { ordered, .. } => self.list(block, *ordered),
|
||||
MdKind::BlockQuote => self.quote(block),
|
||||
// Level>=3 headings and inert document values stay out of the IR.
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph(&mut self, paragraph: &MdNode) -> Vec<Stmt> {
|
||||
let mut stmts = Vec::new();
|
||||
for child in ¶graph.children {
|
||||
match &child.kind {
|
||||
MdKind::Strong => {
|
||||
if let Some(stmt) = self.exec_statement(child) {
|
||||
stmts.push(stmt);
|
||||
fn extract(&mut self, node: &MdNode, out: &mut Vec<RawPayload>, direct: bool) {
|
||||
match &node.kind {
|
||||
MdKind::Paragraph => {
|
||||
for child in &node.children {
|
||||
self.extract(child, out, direct);
|
||||
}
|
||||
}
|
||||
MdKind::BlockQuote | MdKind::Item { .. } | MdKind::List { .. } => {
|
||||
for child in &node.children {
|
||||
self.extract(child, out, false);
|
||||
}
|
||||
}
|
||||
MdKind::Strong | MdKind::Emph => {
|
||||
let (text, segments) = match PayloadSegments::of(node) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
self.error(
|
||||
codes::SEM_PAYLOAD_NESTED,
|
||||
Some(error.span),
|
||||
format!("invalid payload carrier: {}", error.reason),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
MdKind::Emph => {
|
||||
if let Some(stmt) = self.return_statement(child) {
|
||||
stmts.push(stmt);
|
||||
}
|
||||
}
|
||||
// Lazy/inert inline structures: never recurse into them.
|
||||
MdKind::Link { .. }
|
||||
| MdKind::Image { .. }
|
||||
| MdKind::Strikethrough
|
||||
| MdKind::Code { .. }
|
||||
| MdKind::Math { .. }
|
||||
| MdKind::Text
|
||||
| MdKind::SoftBreak
|
||||
| MdKind::LineBreak
|
||||
| MdKind::HtmlInline
|
||||
| MdKind::FootnoteReference { .. } => {}
|
||||
_ => {}
|
||||
};
|
||||
self.push(text, node.span, segments, out, direct);
|
||||
}
|
||||
MdKind::Code { ticks } => {
|
||||
let literal = node.literal.as_deref().unwrap_or_default();
|
||||
let inner = Span::new(
|
||||
node.span.start.saturating_add(*ticks),
|
||||
node.span.end.saturating_sub(*ticks),
|
||||
);
|
||||
self.push(
|
||||
literal.to_string(),
|
||||
node.span,
|
||||
PayloadSegments::single(literal, inner),
|
||||
out,
|
||||
direct,
|
||||
);
|
||||
}
|
||||
MdKind::Heading { .. } => {}
|
||||
_ => {}
|
||||
}
|
||||
stmts
|
||||
}
|
||||
|
||||
fn exec_statement(&mut self, node: &MdNode) -> Option<Stmt> {
|
||||
let (payload, segments) = match PayloadSegments::of(node) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(error.span),
|
||||
error.reason,
|
||||
"keep the executable payload as plain text or a single code span",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if payload.trim().is_empty() {
|
||||
fn push(
|
||||
&mut self,
|
||||
text: String,
|
||||
span: Span,
|
||||
segments: PayloadSegments,
|
||||
out: &mut Vec<RawPayload>,
|
||||
direct: bool,
|
||||
) {
|
||||
if text.trim().is_empty() {
|
||||
self.error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(node.span),
|
||||
"execution statement has an empty payload",
|
||||
codes::SEM_EMPTY_PAYLOAD,
|
||||
Some(span),
|
||||
"executable payload is empty",
|
||||
);
|
||||
return None;
|
||||
return;
|
||||
}
|
||||
match parse_statement(&payload) {
|
||||
Ok(mut statement) => {
|
||||
segments.rewrite_statement(&mut statement);
|
||||
Some(match statement.kind {
|
||||
StatementKind::Assign { target, value } => Stmt::Assign {
|
||||
target: match target {
|
||||
AssignTarget::Local { name, name_span } => {
|
||||
PlaceTarget::Local { name, name_span }
|
||||
}
|
||||
AssignTarget::Index {
|
||||
base,
|
||||
index,
|
||||
span: target_span,
|
||||
} => PlaceTarget::Index {
|
||||
base: *base,
|
||||
index: *index,
|
||||
span: target_span,
|
||||
},
|
||||
},
|
||||
value,
|
||||
span: node.span,
|
||||
},
|
||||
StatementKind::Expr(expr) => Stmt::Eval {
|
||||
expr,
|
||||
span: node.span,
|
||||
},
|
||||
})
|
||||
if let Some(mut payload) = self.parse_payload(&text, span, &segments) {
|
||||
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload {
|
||||
segments.rewrite_expr(expr);
|
||||
}
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::EXPR_PARSE,
|
||||
Some(segments.map_span(error.span)),
|
||||
format!("invalid execution statement: {}", error.message),
|
||||
"statements are `name = expression` or an expression; put the payload in a code span when Markdown emphasis conflicts",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn return_statement(&mut self, node: &MdNode) -> Option<Stmt> {
|
||||
let (payload, segments) = match PayloadSegments::of(node) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(error.span),
|
||||
error.reason,
|
||||
"a return payload must be plain text or a single code span",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if payload.trim().is_empty() {
|
||||
self.error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(node.span),
|
||||
"return statement has an empty payload",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
match parse_expression(&payload) {
|
||||
Ok(mut expr) => {
|
||||
segments.rewrite_expr(&mut expr);
|
||||
Some(Stmt::Return {
|
||||
value: expr,
|
||||
span: node.span,
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::EXPR_PARSE,
|
||||
Some(segments.map_span(error.span)),
|
||||
format!("invalid return expression: {}", error.message),
|
||||
"`*表达式*` returns the value of the expression",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list(&mut self, list: &MdNode, ordered: bool) -> Vec<Stmt> {
|
||||
if list.children.is_empty() {
|
||||
self.error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(list.span),
|
||||
"list in an executable position has no items",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
let mut arms = Vec::new();
|
||||
let mut loops = Vec::new();
|
||||
for item in &list.children {
|
||||
let Some((condition, condition_span, body_blocks)) = self.condition_of(item) else {
|
||||
continue;
|
||||
};
|
||||
let body = self.blocks(body_blocks);
|
||||
if ordered {
|
||||
arms.push(marqdo_ir::BranchArm {
|
||||
condition,
|
||||
condition_span,
|
||||
body,
|
||||
span: item.span,
|
||||
});
|
||||
} else {
|
||||
loops.push(Stmt::Loop {
|
||||
condition,
|
||||
condition_span,
|
||||
body,
|
||||
span: item.span,
|
||||
});
|
||||
}
|
||||
}
|
||||
if ordered {
|
||||
if arms.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![Stmt::Branch {
|
||||
arms,
|
||||
span: list.span,
|
||||
}]
|
||||
} else {
|
||||
loops
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the condition header of a list item and its remaining blocks.
|
||||
fn condition_of<'b>(&mut self, item: &'b MdNode) -> Option<(Expr, Span, &'b [MdNode])> {
|
||||
let Some(first) = item.children.first() else {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(item.span),
|
||||
"list item in an executable position must start with a condition code span",
|
||||
"write the condition first: `` `n > 0` ``",
|
||||
);
|
||||
return None;
|
||||
};
|
||||
if !matches!(first.kind, MdKind::Paragraph) {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(first.span),
|
||||
"list item must start with a paragraph containing the condition code span",
|
||||
"put the condition on the first line of the item",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let Some(condition_node) = first.children.first() else {
|
||||
self.error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(first.span),
|
||||
"list item paragraph is empty; a condition code span is required",
|
||||
);
|
||||
return None;
|
||||
};
|
||||
if !matches!(condition_node.kind, MdKind::Code { .. }) {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(condition_node.span),
|
||||
"list item must start with a condition inside an inline code span",
|
||||
"the condition is a `Code` span: `` `n > 0` ``; other text is description",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
// The remainder of the condition paragraph is description only. The
|
||||
// semantic mapper does not descend into it, so an executable `Strong`
|
||||
// or `Emph` there would otherwise be silently swallowed. Reject it as
|
||||
// a hard shape error instead of guessing the author's intent.
|
||||
for tail in first.children.iter().skip(1) {
|
||||
if matches!(tail.kind, MdKind::Strong | MdKind::Emph) {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(tail.span),
|
||||
format!(
|
||||
"`{}` inside a list-item condition paragraph is not executed and cannot be silently ignored",
|
||||
tail.kind.tag()
|
||||
),
|
||||
"put executable statements in their own paragraph after the condition line",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let literal = condition_node.literal.clone().unwrap_or_default();
|
||||
// `condition_node.span` includes the backtick delimiters. The payload
|
||||
// map must start at the first literal byte so parse diagnostics and
|
||||
// expression spans point at the expression, not at a delimiter.
|
||||
let ticks = match condition_node.kind {
|
||||
MdKind::Code { ticks } => ticks,
|
||||
_ => 0,
|
||||
};
|
||||
let literal_span = Span::new(
|
||||
condition_node.span.start.saturating_add(ticks),
|
||||
condition_node.span.end.saturating_sub(ticks),
|
||||
);
|
||||
let segments = PayloadSegments::single(&literal, literal_span);
|
||||
match parse_expression(&literal) {
|
||||
Ok(mut expr) => {
|
||||
segments.rewrite_expr(&mut expr);
|
||||
Some((expr, condition_node.span, &item.children[1..]))
|
||||
}
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::EXPR_PARSE,
|
||||
Some(segments.map_span(error.span)),
|
||||
format!("invalid condition expression: {}", error.message),
|
||||
"conditions are Boolean expressions, e.g. `n > 0`",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quote(&mut self, quote: &MdNode) -> Vec<Stmt> {
|
||||
if quote.children.len() != 1 || quote.children[0].kind != MdKind::Paragraph {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(quote.span),
|
||||
"a block quote invocation must contain exactly one paragraph",
|
||||
"use one block quote per call; prose belongs in normal paragraphs",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
let paragraph = "e.children[0];
|
||||
self.call_paragraph(quote, paragraph)
|
||||
}
|
||||
|
||||
fn call_paragraph(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
|
||||
let first = paragraph.children.first();
|
||||
let is_link_form = first
|
||||
.map(|node| matches!(node.kind, MdKind::Link { .. }))
|
||||
.unwrap_or(false);
|
||||
if is_link_form {
|
||||
return self.link_call(quote, paragraph);
|
||||
}
|
||||
let (payload, segments) = match PayloadSegments::of(paragraph) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(error.span),
|
||||
error.reason,
|
||||
"a block quote call payload must be plain text or one code span",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
if payload.trim().is_empty() {
|
||||
self.error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(quote.span),
|
||||
"block quote invocation has an empty payload",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
match parse_expression(&payload) {
|
||||
Ok(mut expr) => {
|
||||
segments.rewrite_expr(&mut expr);
|
||||
if !matches!(expr, Expr::Call { .. }) {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(segments.map_span(expr_span(&expr))),
|
||||
"a block quote must be a complete function call",
|
||||
"write `> 函数(参数)`; use a `**strong**` statement to bind a result",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
vec![Stmt::Eval {
|
||||
expr,
|
||||
span: quote.span,
|
||||
}]
|
||||
}
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::EXPR_PARSE,
|
||||
Some(segments.map_span(error.span)),
|
||||
format!("invalid call expression: {}", error.message),
|
||||
"block quotes call functions explicitly: `> 函数(参数)`",
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn link_call(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
|
||||
let link = ¶graph.children[0];
|
||||
let (url, link_span) = match &link.kind {
|
||||
MdKind::Link { url, .. } => (url.clone(), link.span),
|
||||
_ => unreachable!("link form checked by caller"),
|
||||
};
|
||||
let target = self.resolve_link_target(&url, link_span);
|
||||
let rest = ¶graph.children[1..];
|
||||
let (suffix, segments) = match PayloadSegments::from_children(rest) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(error.span),
|
||||
error.reason,
|
||||
"link call arguments must follow the link as plain text or code spans",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
if suffix.trim().is_empty() {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(quote.span),
|
||||
"link-form call requires an explicit argument list",
|
||||
"write `> [函数](#函数)()` even for zero arguments",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
let mut args: Vec<Arg> = match parse_arguments(&suffix) {
|
||||
Ok(args) => args,
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::EXPR_PARSE,
|
||||
Some(segments.map_span(error.span)),
|
||||
format!("invalid call arguments: {}", error.message),
|
||||
"arguments are `name = value` or positional values",
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
segments.rewrite_args(&mut args);
|
||||
let Some(target) = target else {
|
||||
return Vec::new();
|
||||
};
|
||||
vec![Stmt::Call {
|
||||
call: CallSite {
|
||||
target,
|
||||
args,
|
||||
span: quote.span,
|
||||
},
|
||||
span: quote.span,
|
||||
}]
|
||||
}
|
||||
|
||||
fn resolve_link_target(&mut self, url: &str, span: Span) -> Option<CallTarget> {
|
||||
if let Some(fragment) = url.strip_prefix('#') {
|
||||
let unit_id = self.index.anchors.get(fragment).cloned().or_else(|| {
|
||||
self.index
|
||||
.units
|
||||
.iter()
|
||||
.find(|unit| unit.name == fragment)
|
||||
.map(|unit| unit.id.clone())
|
||||
out.push(RawPayload {
|
||||
payload,
|
||||
span,
|
||||
segments,
|
||||
direct,
|
||||
});
|
||||
let Some(unit_id) = unit_id else {
|
||||
self.error(
|
||||
codes::REF_UNRESOLVED,
|
||||
Some(span),
|
||||
format!("no heading matches call target `{url}`"),
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let Some(scope) = self
|
||||
.index
|
||||
.functions
|
||||
.iter()
|
||||
.find(|scope| scope.unit == unit_id)
|
||||
else {
|
||||
self.error(
|
||||
codes::REF_UNRESOLVED,
|
||||
Some(span),
|
||||
format!("call target `{url}` is not a function"),
|
||||
);
|
||||
return None;
|
||||
};
|
||||
Some(CallTarget::Resolved {
|
||||
module: unit_id.module.clone(),
|
||||
function: scope.id.name.clone(),
|
||||
})
|
||||
} else if url.starts_with("http://") || url.starts_with("https://") {
|
||||
self.error_with_hint(
|
||||
codes::REF_UNRESOLVED,
|
||||
Some(span),
|
||||
"external links cannot be called",
|
||||
"link targets used as calls must resolve to a Marqdo function",
|
||||
);
|
||||
None
|
||||
} else {
|
||||
self.error_with_hint(
|
||||
codes::MODULE_UNRESOLVED,
|
||||
Some(span),
|
||||
format!("cannot resolve cross-module call target `{url}`"),
|
||||
"import the module explicitly in front matter and call it through the alias",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expr_span(expr: &Expr) -> Span {
|
||||
marqdo_expression::Expr::span(expr)
|
||||
fn parse_payload(
|
||||
&mut self,
|
||||
text: &str,
|
||||
span: Span,
|
||||
segments: &PayloadSegments,
|
||||
) -> Option<Payload> {
|
||||
let map = |span: Span| segments.map_span(span);
|
||||
let text = text.trim();
|
||||
if text.starts_with("params(") {
|
||||
// Signature syntax and diagnostics are owned by `signature::parse`;
|
||||
// the mapper only recognizes the declaration payload.
|
||||
return Some(Payload::Params);
|
||||
}
|
||||
if text == "params" || text.starts_with("params ") {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
"malformed params declaration; write `params(name: Type, ...)`",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let (word, rest) = match text.split_once(char::is_whitespace) {
|
||||
Some((word, rest)) => (word, rest.trim()),
|
||||
None => (text, ""),
|
||||
};
|
||||
// Parse control expressions with the keyword replaced by spaces so the
|
||||
// expression AST keeps payload-relative (not rest-relative) spans.
|
||||
let expression_at = |rest: &str| {
|
||||
let offset = text.len().saturating_sub(rest.len());
|
||||
parse_expression(&format!("{}{}", " ".repeat(offset), rest))
|
||||
};
|
||||
match word {
|
||||
"if" => {
|
||||
if rest.is_empty() {
|
||||
self.error(codes::SEM_SYNTAX, Some(span), "`if` requires a condition");
|
||||
return None;
|
||||
}
|
||||
match expression_at(rest) {
|
||||
Ok(expr) => Some(Payload::If(expr)),
|
||||
Err(error) => {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(map(error.span)),
|
||||
format!("invalid if condition: {}", error.message),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
"else" if rest.is_empty() => Some(Payload::Else),
|
||||
"else" => {
|
||||
self.error(codes::SEM_SYNTAX, Some(span), "`else` takes no expression");
|
||||
None
|
||||
}
|
||||
"while" => {
|
||||
if rest.is_empty() {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
"`while` requires a condition",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
match expression_at(rest) {
|
||||
Ok(expr) => Some(Payload::While(expr)),
|
||||
Err(error) => {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(map(error.span)),
|
||||
format!("invalid while condition: {}", error.message),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
"end" if rest.is_empty() => Some(Payload::End),
|
||||
"end" => {
|
||||
self.error(codes::SEM_SYNTAX, Some(span), "`end` takes no expression");
|
||||
None
|
||||
}
|
||||
"return" => {
|
||||
if rest.is_empty() {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
"`return` requires an expression",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
match expression_at(rest) {
|
||||
Ok(expr) => Some(Payload::Return(expr)),
|
||||
Err(error) => {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(map(error.span)),
|
||||
format!("invalid return expression: {}", error.message),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
"params" => {
|
||||
if text.starts_with("params(") && text.ends_with(')') {
|
||||
Some(Payload::Params)
|
||||
} else {
|
||||
self.error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
"malformed params declaration",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
"ifdef" | "returning" | "paramsx" => self.statement_payload(text, span),
|
||||
_ => self.statement_payload(text, span),
|
||||
}
|
||||
}
|
||||
|
||||
fn statement_payload(&mut self, text: &str, span: Span) -> Option<Payload> {
|
||||
match parse_statement(text) {
|
||||
Ok(statement) => Some(Payload::Statement(statement)),
|
||||
Err(error) => {
|
||||
self.error_with_hint(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
format!("invalid execution payload: {}", error.message),
|
||||
"one payload is exactly one statement; put control keywords in their own carriers",
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sequence(
|
||||
&mut self,
|
||||
nodes: &[RawPayload],
|
||||
position: &mut usize,
|
||||
stop_on_else: bool,
|
||||
in_else_body: bool,
|
||||
) -> (Vec<Stmt>, Stop) {
|
||||
let mut out = Vec::new();
|
||||
while *position < nodes.len() {
|
||||
let raw = &nodes[*position];
|
||||
match &raw.payload {
|
||||
Payload::Else => {
|
||||
if stop_on_else {
|
||||
return (out, Stop::Else);
|
||||
}
|
||||
self.error(
|
||||
if in_else_body {
|
||||
codes::SEM_DUPLICATE_ELSE
|
||||
} else {
|
||||
codes::SEM_UNMATCHED_ELSE
|
||||
},
|
||||
Some(raw.span),
|
||||
if in_else_body {
|
||||
"`if` has more than one `else`"
|
||||
} else {
|
||||
"`else` has no open `if`"
|
||||
},
|
||||
);
|
||||
*position += 1;
|
||||
}
|
||||
Payload::End => {
|
||||
return (out, Stop::End);
|
||||
}
|
||||
Payload::If(condition) => {
|
||||
let condition = condition.clone();
|
||||
let span = raw.span;
|
||||
*position += 1;
|
||||
let (then_body, stop) = self.sequence(nodes, position, true, false);
|
||||
let mut else_body = Vec::new();
|
||||
let finish = match stop {
|
||||
Stop::Else => {
|
||||
*position += 1;
|
||||
let (body, stop) = self.sequence(nodes, position, false, true);
|
||||
else_body = body;
|
||||
stop
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
if finish != Stop::End {
|
||||
self.error(
|
||||
codes::SEM_UNCLOSED_CONTROL,
|
||||
Some(span),
|
||||
"`if` is not closed by `end`",
|
||||
);
|
||||
} else {
|
||||
*position += 1;
|
||||
}
|
||||
let mut arms = vec![marqdo_ir::BranchArm {
|
||||
condition,
|
||||
condition_span: span,
|
||||
body: then_body,
|
||||
span,
|
||||
}];
|
||||
if !else_body.is_empty() {
|
||||
arms.push(marqdo_ir::BranchArm {
|
||||
condition: Expr::Bool(true),
|
||||
condition_span: span,
|
||||
body: else_body,
|
||||
span,
|
||||
});
|
||||
}
|
||||
out.push(Stmt::Branch { arms, span });
|
||||
}
|
||||
Payload::While(condition) => {
|
||||
let condition = condition.clone();
|
||||
let span = raw.span;
|
||||
*position += 1;
|
||||
let (body, stop) = self.sequence(nodes, position, false, false);
|
||||
if stop != Stop::End {
|
||||
self.error(
|
||||
codes::SEM_UNCLOSED_CONTROL,
|
||||
Some(span),
|
||||
"`while` is not closed by `end`",
|
||||
);
|
||||
} else {
|
||||
*position += 1;
|
||||
}
|
||||
out.push(Stmt::Loop {
|
||||
condition,
|
||||
condition_span: span,
|
||||
body,
|
||||
span,
|
||||
});
|
||||
}
|
||||
Payload::Return(value) => {
|
||||
out.push(Stmt::Return {
|
||||
value: value.clone(),
|
||||
span: raw.span,
|
||||
});
|
||||
*position += 1;
|
||||
}
|
||||
Payload::Params => {
|
||||
let duplicate = self.saw_params.is_some();
|
||||
if !raw.direct {
|
||||
self.error(
|
||||
codes::SEM_SIGNATURE_POSITION,
|
||||
Some(raw.span),
|
||||
"`params(...)` must be a direct payload, not inside a list or block quote",
|
||||
);
|
||||
} else if *position != 0 {
|
||||
self.error(
|
||||
codes::SEM_SIGNATURE_POSITION,
|
||||
Some(raw.span),
|
||||
"`params(...)` must be the first payload of an Exec H2",
|
||||
);
|
||||
} else if duplicate {
|
||||
self.error(
|
||||
codes::SEM_SIGNATURE_POSITION,
|
||||
Some(raw.span),
|
||||
"`params(...)` may be declared only once per function",
|
||||
);
|
||||
} else {
|
||||
self.saw_params = Some(raw.span);
|
||||
}
|
||||
*position += 1;
|
||||
}
|
||||
Payload::Statement(statement) => {
|
||||
let mut statement = statement.clone();
|
||||
raw.segments.rewrite_statement(&mut statement);
|
||||
let span = raw.span;
|
||||
match statement.kind {
|
||||
StatementKind::Assign { target, value } => out.push(Stmt::Assign {
|
||||
target: match target {
|
||||
AssignTarget::Local { name, name_span } => {
|
||||
PlaceTarget::Local { name, name_span }
|
||||
}
|
||||
AssignTarget::Index {
|
||||
base,
|
||||
index,
|
||||
span: target_span,
|
||||
} => PlaceTarget::Index {
|
||||
base: *base,
|
||||
index: *index,
|
||||
span: target_span,
|
||||
},
|
||||
},
|
||||
value,
|
||||
span,
|
||||
}),
|
||||
StatementKind::Expr(expr) => out.push(Stmt::Eval { expr, span }),
|
||||
}
|
||||
*position += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, Stop::Eof)
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalise a heading name (re-exported for callers that resolve link targets).
|
||||
|
||||
@@ -311,40 +311,42 @@ mod extra_span_tests {
|
||||
|
||||
#[test]
|
||||
fn condition_literal_span_excludes_backticks_for_one_and_two_ticks() {
|
||||
for source in ["## f\n\n1. `n ** 2 ==`\n", "## f\n\n1. ``n ** 2 ==``\n"] {
|
||||
for source in [
|
||||
"## @exec f\n\n`if n ** 2 ==`\n",
|
||||
"## @exec f\n\n``if n ** 2 ==``\n",
|
||||
] {
|
||||
let result = crate::analyze_source("index.mq.md", source);
|
||||
let diagnostic = result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|diagnostic| diagnostic.code == marqdo_value::codes::EXPR_PARSE)
|
||||
.unwrap_or_else(|| panic!("no expr.parse diagnostic for {source:?}"));
|
||||
.find(|diagnostic| diagnostic.code == marqdo_value::codes::SEM_SYNTAX)
|
||||
.unwrap_or_else(|| panic!("no sem.syntax diagnostic for {source:?}"));
|
||||
let span = diagnostic
|
||||
.span
|
||||
.expect("condition parse error has a source span");
|
||||
assert_eq!(
|
||||
source.as_bytes()[span.start],
|
||||
b'`',
|
||||
"span must stop before the closing backtick: {span:?} in {source:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
&source[span.start.saturating_sub(2)..span.start],
|
||||
"==",
|
||||
"span must point at the missing operand"
|
||||
let condition = source.find("n ** 2 ==").expect("condition text");
|
||||
let closing = source.rfind('`').expect("closing backtick");
|
||||
assert!(
|
||||
span.start >= condition && span.end <= closing,
|
||||
"span must point inside the carrier payload, before the closing backtick: {span:?} in {source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn condition_description_rejects_executable_roles() {
|
||||
// RFC-LANG-0002 no longer rejects Strong/Emph next to a code span:
|
||||
// every carrier is an independent statement. The preserved intent is
|
||||
// that a malformed control sequence after `if` is a hard error; it is
|
||||
// repurposed as an unclosed-control negative.
|
||||
for tail in ["**print(1)**", "*1*"] {
|
||||
let source = format!("## f\n\n1. `n > 0` {tail}\n\n > print(1)\n");
|
||||
let source = format!("## @exec f\n\n`if n > 0` {tail}\n");
|
||||
let result = crate::analyze_source("index.mq.md", &source);
|
||||
assert!(
|
||||
result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code
|
||||
== marqdo_value::codes::MARKDOWN_INVALID_CONSTRUCT),
|
||||
.any(|diagnostic| diagnostic.code == "sem.unclosed_control"),
|
||||
"executable tail `{tail}` was not rejected: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
@@ -353,7 +355,10 @@ mod extra_span_tests {
|
||||
|
||||
#[test]
|
||||
fn condition_description_allows_inert_inline_content() {
|
||||
let source = "## f\n\n**n = 1**\n\n1. `n > 0` 普通说明、`惰性代码` 与 [链接](#f)。\n\n > print(1)\n";
|
||||
// Inline code spans are payload carriers in Exec scope, so the old inert
|
||||
// `惰性代码` example is now a statement; prose, a link and a carrier-free
|
||||
// block quote remain inert and must not be rejected.
|
||||
let source = "## @exec f\n\n`n = 1`\n\n1. `n > 0` 普通说明与 [链接](#f)。\n\n > print(1)\n\n`return n`\n";
|
||||
let result = crate::analyze_source("index.mq.md", source);
|
||||
assert!(
|
||||
!result.has_errors(),
|
||||
|
||||
@@ -121,7 +121,7 @@ mod tests {
|
||||
#[test]
|
||||
fn formulas_and_code_are_attributed_to_functions() {
|
||||
let resources = resources_of(
|
||||
"# ns\n\n## f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## g\n\n$$B = 1$$\n",
|
||||
"# @knowledge ns\n\n## @exec f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## @exec g\n\n$$B = 1$$\n",
|
||||
);
|
||||
assert_eq!(resources.len(), 3);
|
||||
let Resource::Formula { unit, latex, .. } = &resources[0] else {
|
||||
|
||||
@@ -42,37 +42,41 @@ pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Sig
|
||||
match &block.kind {
|
||||
MdKind::Heading { level, .. } if *level >= 3 => continue,
|
||||
MdKind::Paragraph => {
|
||||
let is_candidate = block.children.len() == 1
|
||||
&& matches!(block.children[0].kind, MdKind::Code { .. })
|
||||
&& block.children[0]
|
||||
.literal
|
||||
.as_deref()
|
||||
.map(|text| text.trim_start().starts_with('('))
|
||||
.unwrap_or(false);
|
||||
if !is_candidate {
|
||||
if block.children.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let carrier = &block.children[0];
|
||||
let (source, span, segments) = match &carrier.kind {
|
||||
MdKind::Code { ticks } => {
|
||||
let literal = carrier.literal.clone().unwrap_or_default();
|
||||
let inner = Span::new(
|
||||
carrier.span.start.saturating_add(*ticks),
|
||||
carrier.span.end.saturating_sub(*ticks),
|
||||
);
|
||||
(
|
||||
literal.clone(),
|
||||
carrier.span,
|
||||
PayloadSegments::single(&literal, inner),
|
||||
)
|
||||
}
|
||||
MdKind::Strong | MdKind::Emph => match PayloadSegments::of(carrier) {
|
||||
Ok((source, segments)) => (source, carrier.span, segments),
|
||||
Err(_) => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
if !source.trim_start().starts_with("params(") {
|
||||
return None;
|
||||
}
|
||||
let code = &block.children[0];
|
||||
let source = code.literal.clone().unwrap_or_default();
|
||||
let mut signature = parse(&source, code.span);
|
||||
// Rewrite parameter default expression spans onto the file.
|
||||
let segments = PayloadSegments::of(&MdNode {
|
||||
kind: MdKind::Strong,
|
||||
span: code.span,
|
||||
literal: None,
|
||||
children: vec![code.clone()],
|
||||
})
|
||||
.ok()
|
||||
.map(|(_, segments)| segments);
|
||||
if let Some(segments) = segments {
|
||||
for param in &mut signature.params {
|
||||
if let Some(default) = &mut param.default {
|
||||
segments.rewrite_expr(default);
|
||||
}
|
||||
let mut signature = parse(&source, span);
|
||||
for param in &mut signature.params {
|
||||
if let Some(default) = &mut param.default {
|
||||
segments.rewrite_expr(default);
|
||||
}
|
||||
}
|
||||
return Some((index, signature));
|
||||
}
|
||||
MdKind::List { .. } | MdKind::BlockQuote | MdKind::Item { .. } => continue,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
@@ -83,13 +87,33 @@ pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Sig
|
||||
pub fn parse(source: &str, span: Span) -> Signature {
|
||||
let mut diagnostics = Vec::new();
|
||||
let trimmed = source.trim();
|
||||
let inner = if let Some(rest) = trimmed.strip_prefix('(') {
|
||||
let is_params = trimmed.starts_with("params(");
|
||||
let syntax_code = if is_params {
|
||||
codes::SEM_SYNTAX
|
||||
} else {
|
||||
codes::EXPR_PARSE
|
||||
};
|
||||
let inner = if let Some(rest) = trimmed.strip_prefix("params(") {
|
||||
match rest.strip_suffix(')') {
|
||||
Some(inner) => inner,
|
||||
None => {
|
||||
diagnostics.push(Diagnostic::error(
|
||||
codes::SEM_SYNTAX,
|
||||
Some(span),
|
||||
"function signature must be closed by `)`",
|
||||
));
|
||||
rest
|
||||
}
|
||||
}
|
||||
} else if let Some(rest) = trimmed.strip_prefix('(') {
|
||||
// Plugin/ABI descriptors keep their existing parenthesised signature
|
||||
// spelling; language payloads are detected only as `params(...)`.
|
||||
rest.strip_suffix(')').unwrap_or(rest)
|
||||
} else {
|
||||
diagnostics.push(Diagnostic::error(
|
||||
codes::EXPR_PARSE,
|
||||
syntax_code,
|
||||
Some(span),
|
||||
"function signature must be parenthesised, e.g. `(r: Number)`",
|
||||
"function signature must be `params(...)`, e.g. `params(r: Number)`",
|
||||
));
|
||||
trimmed
|
||||
};
|
||||
@@ -102,7 +126,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
|
||||
if entry.trim().is_empty() {
|
||||
if !inner.trim().is_empty() {
|
||||
diagnostics.push(Diagnostic::error(
|
||||
codes::EXPR_PARSE,
|
||||
syntax_code,
|
||||
Some(span),
|
||||
"empty parameter in function signature",
|
||||
));
|
||||
@@ -129,7 +153,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
|
||||
}
|
||||
}
|
||||
Err(message) => diagnostics.push(Diagnostic::error(
|
||||
codes::EXPR_PARSE,
|
||||
syntax_code,
|
||||
Some(span),
|
||||
format!("invalid function signature: {message}"),
|
||||
)),
|
||||
@@ -293,7 +317,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parses_typed_signature_with_default() {
|
||||
let signature = parse("(r: Number, precision: Int = 2)", Span::new(0, 38));
|
||||
let signature = parse("params(r: Number, precision: Int = 2)", Span::new(0, 38));
|
||||
assert!(!signature.has_errors(), "{:?}", signature.diagnostics);
|
||||
assert_eq!(signature.params.len(), 2);
|
||||
assert_eq!(signature.params[0].name, "r");
|
||||
@@ -307,20 +331,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parses_untyped_and_empty() {
|
||||
let signature = parse("()", Span::new(0, 2));
|
||||
let signature = parse("params()", Span::new(0, 8));
|
||||
assert!(signature.params.is_empty());
|
||||
assert!(!signature.has_errors());
|
||||
let signature = parse("(n)", Span::new(0, 3));
|
||||
let signature = parse("params(n)", Span::new(0, 9));
|
||||
assert_eq!(signature.params[0].name, "n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicates_and_bad_defaults() {
|
||||
let duplicate = parse("(a, a)", Span::new(0, 6));
|
||||
let duplicate = parse("params(a, a)", Span::new(0, 12));
|
||||
assert!(duplicate.has_errors());
|
||||
let bad_default = parse("(a = f())", Span::new(0, 10));
|
||||
let bad_default = parse("params(a = f())", Span::new(0, 16));
|
||||
assert!(bad_default.has_errors());
|
||||
let bad_name = parse("(1x)", Span::new(0, 4));
|
||||
let bad_name = parse("params(1x)", Span::new(0, 10));
|
||||
assert!(bad_name.has_errors());
|
||||
}
|
||||
|
||||
|
||||
+200
-101
@@ -16,7 +16,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_ir::{FunctionId, ModuleId, UnitId, UnitInfo, UnitKind};
|
||||
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind};
|
||||
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind, MdNode};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{codes, Diagnostic};
|
||||
|
||||
@@ -35,6 +35,8 @@ pub struct HeadingInfo {
|
||||
pub path: Vec<String>,
|
||||
/// Role derived from level and position.
|
||||
pub kind: UnitKind,
|
||||
/// Semantic mode declared or inherited by this heading.
|
||||
pub mode: SemanticMode,
|
||||
}
|
||||
|
||||
/// A function range mapped from a level-2 heading.
|
||||
@@ -93,6 +95,91 @@ impl UnitIndex {
|
||||
}
|
||||
}
|
||||
|
||||
fn has_payload(node: &MdNode) -> bool {
|
||||
match &node.kind {
|
||||
MdKind::Strong | MdKind::Emph | MdKind::Code { .. } => true,
|
||||
MdKind::Paragraph | MdKind::List { .. } | MdKind::Item { .. } | MdKind::BlockQuote => {
|
||||
node.children.iter().any(has_payload)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the heading/function index for a parsed document.
|
||||
/// Semantic mode declared or inherited by a heading (RFC-LANG-0002).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SemanticMode {
|
||||
/// Document/knowledge region; no executable statements.
|
||||
Knowledge,
|
||||
/// Executable region; only an Exec H2 is callable.
|
||||
Exec,
|
||||
}
|
||||
|
||||
fn heading_declaration(
|
||||
node: &MdNode,
|
||||
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
|
||||
let Some(first) = node.children.first() else {
|
||||
return (None, None, None);
|
||||
};
|
||||
let MdKind::Text = first.kind else {
|
||||
return (None, None, None);
|
||||
};
|
||||
let literal = first.literal.as_deref().unwrap_or_default();
|
||||
let (mode, rest) = if let Some(rest) = literal.strip_prefix("@exec") {
|
||||
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
|
||||
return (None, None, None);
|
||||
}
|
||||
(SemanticMode::Exec, rest)
|
||||
} else if let Some(rest) = literal.strip_prefix("@knowledge") {
|
||||
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
|
||||
return (None, None, None);
|
||||
}
|
||||
(SemanticMode::Knowledge, rest)
|
||||
} else if literal.starts_with('@')
|
||||
&& literal
|
||||
.trim_start_matches('@')
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(char::is_alphabetic)
|
||||
{
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
Some(Diagnostic::error(
|
||||
codes::SEM_INVALID_MODE_MARKER,
|
||||
Some(first.span),
|
||||
"unknown heading mode marker; use exactly `@exec` or `@knowledge`",
|
||||
)),
|
||||
);
|
||||
} else {
|
||||
return (None, None, None);
|
||||
};
|
||||
let title = rest.trim();
|
||||
if title.is_empty() {
|
||||
return (
|
||||
Some(mode),
|
||||
None,
|
||||
Some(Diagnostic::error(
|
||||
codes::SEM_EMPTY_UNIT_NAME,
|
||||
Some(node.span),
|
||||
"mode declaration has an empty heading name",
|
||||
)),
|
||||
);
|
||||
}
|
||||
if title.starts_with("@exec") || title.starts_with("@knowledge") {
|
||||
return (
|
||||
Some(mode),
|
||||
None,
|
||||
Some(Diagnostic::error(
|
||||
codes::SEM_INVALID_MODE_MARKER,
|
||||
Some(node.span),
|
||||
"a heading may declare only one semantic mode",
|
||||
)),
|
||||
);
|
||||
}
|
||||
(Some(mode), Some(title.to_string()), None)
|
||||
}
|
||||
|
||||
/// Build the heading/function index for a parsed document.
|
||||
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
let mut index = UnitIndex::default();
|
||||
@@ -108,8 +195,8 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
function: None,
|
||||
});
|
||||
|
||||
// Stack of (level, path) for ancestor headings with smaller level.
|
||||
let mut stack: Vec<(u8, Vec<String>)> = Vec::new();
|
||||
// Stack of (level, path, mode) for ancestors.
|
||||
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new();
|
||||
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
|
||||
let mut current_namespace: Option<String> = None;
|
||||
let mut current_function: Option<FunctionId> = None;
|
||||
@@ -120,11 +207,26 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
continue;
|
||||
};
|
||||
let level = *level;
|
||||
let raw_name = normalize_name(&plain_text(child));
|
||||
let Some(name) = raw_name else {
|
||||
let (declared, declared_name, declaration_error) = heading_declaration(child);
|
||||
if let Some(error) = declaration_error {
|
||||
index.diagnostics.push(error);
|
||||
if declared_name.is_none() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let inherited = stack
|
||||
.last()
|
||||
.map(|(_, _, mode)| *mode)
|
||||
.unwrap_or(SemanticMode::Knowledge);
|
||||
let mode = declared.unwrap_or(inherited);
|
||||
let raw_name = match declared_name {
|
||||
Some(name) => name,
|
||||
None => plain_text(child),
|
||||
};
|
||||
let Some(name) = normalize_name(&raw_name) else {
|
||||
index.diagnostics.push(
|
||||
Diagnostic::error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
codes::SEM_EMPTY_UNIT_NAME,
|
||||
Some(child.span),
|
||||
"heading name must not be empty",
|
||||
)
|
||||
@@ -133,7 +235,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
continue;
|
||||
};
|
||||
|
||||
while let Some((parent_level, _)) = stack.last() {
|
||||
while let Some((parent_level, _, _)) = stack.last() {
|
||||
if *parent_level >= level {
|
||||
stack.pop();
|
||||
} else {
|
||||
@@ -142,7 +244,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
}
|
||||
let parent_path = stack
|
||||
.last()
|
||||
.map(|(_, path)| path.clone())
|
||||
.map(|(_, path, _)| path.clone())
|
||||
.unwrap_or_default();
|
||||
let path = {
|
||||
let mut path = parent_path.clone();
|
||||
@@ -150,14 +252,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
path
|
||||
};
|
||||
|
||||
// Duplicate canonical names in the same scope are a hard error; never
|
||||
// silently rename with -1/-2 suffixes.
|
||||
let key = (parent_path.clone(), name.clone());
|
||||
if let Some(previous) = seen.get(&key) {
|
||||
let previous = *previous;
|
||||
index.diagnostics.push(
|
||||
Diagnostic::error(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
codes::SEM_DUPLICATE_UNIT_NAME,
|
||||
Some(child.span),
|
||||
format!("duplicate heading name `{name}` in the same scope"),
|
||||
)
|
||||
@@ -170,14 +270,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
|
||||
let kind = match level {
|
||||
1 => UnitKind::Namespace,
|
||||
2 => UnitKind::Function,
|
||||
2 if mode == SemanticMode::Exec => UnitKind::Function,
|
||||
2 => UnitKind::Knowledge,
|
||||
_ => UnitKind::Section,
|
||||
};
|
||||
if level == 1 {
|
||||
current_namespace = Some(name.clone());
|
||||
current_function = None;
|
||||
}
|
||||
let function = if level == 2 {
|
||||
if level >= 3 && mode == SemanticMode::Exec && current_function.is_none() {
|
||||
index.diagnostics.push(
|
||||
Diagnostic::error(
|
||||
codes::SEM_EXEC_WITHOUT_FUNCTION,
|
||||
Some(child.span),
|
||||
"executable section has no owning Exec H2 function",
|
||||
)
|
||||
.with_hint("put the section under an Exec H2, or mark it @knowledge"),
|
||||
);
|
||||
}
|
||||
let function = if level == 2 && mode == SemanticMode::Exec {
|
||||
let local = name.clone();
|
||||
let qualified = match ¤t_namespace {
|
||||
Some(namespace) => format!("{namespace}.{local}"),
|
||||
@@ -189,9 +300,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
};
|
||||
current_function = Some(id.clone());
|
||||
Some(id)
|
||||
} else if level >= 3 {
|
||||
} else if level >= 3 && mode == SemanticMode::Exec {
|
||||
current_function.clone()
|
||||
} else {
|
||||
if level <= 2 {
|
||||
current_function = None;
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
@@ -202,6 +316,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
span: child.span,
|
||||
path: path.clone(),
|
||||
kind,
|
||||
mode,
|
||||
};
|
||||
let unit_id = UnitId {
|
||||
module: module.clone(),
|
||||
@@ -215,12 +330,40 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
kind,
|
||||
function,
|
||||
});
|
||||
if level == 1 && mode == SemanticMode::Exec {
|
||||
// H1 Exec: direct-body carriers before the next heading have no
|
||||
// owning H2 function. A Knowledge H2 body is inert (inline code
|
||||
// there is documentation), and Exec H3 sections are checked above.
|
||||
let mut scan = node_index + 1;
|
||||
while scan < doc.root.children.len() {
|
||||
if let MdKind::Heading { .. } = doc.root.children[scan].kind {
|
||||
break;
|
||||
}
|
||||
if has_payload(&doc.root.children[scan]) {
|
||||
index.diagnostics.push(Diagnostic::error(
|
||||
codes::SEM_EXEC_WITHOUT_FUNCTION,
|
||||
Some(doc.root.children[scan].span),
|
||||
"executable payload has no owning Exec H2 function",
|
||||
));
|
||||
break;
|
||||
}
|
||||
scan += 1;
|
||||
}
|
||||
}
|
||||
heading_infos.push(info.clone());
|
||||
stack.push((level, info.path.clone()));
|
||||
stack.push((level, info.path.clone(), mode));
|
||||
}
|
||||
|
||||
// Function body ranges and spans.
|
||||
for heading in heading_infos.iter().filter(|h| h.level == 2) {
|
||||
// A Knowledge H2 has no function range.
|
||||
if !index
|
||||
.units
|
||||
.iter()
|
||||
.any(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let body_start = heading.node_index + 1;
|
||||
let body_end = doc.root.children[body_start..]
|
||||
.iter()
|
||||
@@ -239,33 +382,23 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
} else {
|
||||
heading.span
|
||||
};
|
||||
let local_name = heading.name.clone();
|
||||
let namespace = match heading.path.len() {
|
||||
0 => None,
|
||||
_ if heading.path.len() == 1 => None,
|
||||
_ => Some(heading.path[0].clone()),
|
||||
};
|
||||
let namespace = namespace.filter(|_| {
|
||||
index
|
||||
.units
|
||||
.iter()
|
||||
.any(|unit| unit.kind == UnitKind::Namespace && unit.name == heading.path[0])
|
||||
});
|
||||
let qualified = match &namespace {
|
||||
Some(namespace) => format!("{namespace}.{local_name}"),
|
||||
None => local_name.clone(),
|
||||
let unit = index
|
||||
.units
|
||||
.iter()
|
||||
.find(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
|
||||
.expect("function unit exists");
|
||||
let FunctionId { name, .. } = unit.function.clone().expect("function id");
|
||||
let local_name = name.rsplit('.').next().unwrap_or(&name).to_string();
|
||||
let namespace = if name.contains('.') {
|
||||
Some(name.rsplit_once('.').unwrap().0.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
index.functions.push(FunctionScope {
|
||||
id: FunctionId {
|
||||
module: module.clone(),
|
||||
name: qualified,
|
||||
},
|
||||
id: unit.function.clone().unwrap(),
|
||||
local_name,
|
||||
namespace,
|
||||
unit: UnitId {
|
||||
module: module.clone(),
|
||||
path: heading.path.clone(),
|
||||
},
|
||||
unit: unit.id.clone(),
|
||||
heading_span: heading.span,
|
||||
body_start,
|
||||
body_end,
|
||||
@@ -273,67 +406,34 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
});
|
||||
}
|
||||
|
||||
// Warnings for would-be execution nodes outside every function body.
|
||||
for (node_index, child) in doc.root.children.iter().enumerate() {
|
||||
if index.function_containing_block(node_index).is_some() {
|
||||
for heading in &heading_infos {
|
||||
let Some(unit) = index.units.iter().find(|unit| unit.id.path == heading.path) else {
|
||||
continue;
|
||||
};
|
||||
let slug = github_slug(&heading.name);
|
||||
if slug.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut warn = |span: Span, what: &str| {
|
||||
index.diagnostics.push(
|
||||
Diagnostic::warning(
|
||||
codes::MARKDOWN_INERT_EXECUTABLE,
|
||||
Some(span),
|
||||
format!("{what} outside a function body is inert document content"),
|
||||
)
|
||||
.with_hint("move it under a level-2 heading (`## 函数名`) to execute it"),
|
||||
);
|
||||
};
|
||||
match &child.kind {
|
||||
MdKind::BlockQuote => warn(child.span, "a block quote invocation"),
|
||||
MdKind::List { .. } => warn(child.span, "a list control structure"),
|
||||
MdKind::Paragraph => {
|
||||
let mut found: Option<(Span, &'static str)> = None;
|
||||
child.walk(&mut |node| {
|
||||
if found.is_none() {
|
||||
match node.kind {
|
||||
MdKind::Strong => found = Some((node.span, "an execution statement")),
|
||||
MdKind::Emph => found = Some((node.span, "a return statement")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some((span, what)) = found {
|
||||
warn(span, what);
|
||||
let mut count = index.anchors.keys().filter(|key| *key == &slug).count();
|
||||
let key = if count == 0 {
|
||||
slug.clone()
|
||||
} else {
|
||||
loop {
|
||||
count += 1;
|
||||
let candidate = format!("{slug}-{count}");
|
||||
if !index.anchors.contains_key(&candidate) {
|
||||
break candidate;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Derive GitHub-style anchors for navigation and `ref("#...")`. Anchors are
|
||||
// not identity: they may collide and receive -1/-2 suffixes exactly like
|
||||
// GitHub's slugger, while internal ids stay canonical.
|
||||
let mut slug_counts: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for unit in &index.units {
|
||||
if unit.level == 0 {
|
||||
continue;
|
||||
}
|
||||
let base = github_slug(&unit.name);
|
||||
if base.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let count = slug_counts.entry(base.clone()).or_insert(0);
|
||||
let slug = if *count == 0 {
|
||||
base
|
||||
} else {
|
||||
format!("{base}-{count}")
|
||||
};
|
||||
*count += 1;
|
||||
index.anchors.insert(slug, unit.id.clone());
|
||||
index.anchors.insert(key, unit.id.clone());
|
||||
}
|
||||
|
||||
index.headings = heading_infos;
|
||||
index
|
||||
.diagnostics
|
||||
.dedup_by(|a, b| a.code == b.code && a.span == b.span && a.message == b.message);
|
||||
index
|
||||
}
|
||||
|
||||
/// GitHub-style heading slug, kept in a separate namespace from canonical
|
||||
@@ -366,7 +466,7 @@ mod tests {
|
||||
#[test]
|
||||
fn builds_function_ranges() {
|
||||
let index = index_of(
|
||||
"# 命名空间\n\n## 阶乘\n\n**x = 1**\n\n### 小节\n\n正文\n\n## 下一个\n\n*y*\n",
|
||||
"# @knowledge 命名空间\n\n## @exec 阶乘\n\n`x = 1`\n\n### 小节\n\n正文\n\n## @exec 下一个\n\n`return y`\n",
|
||||
);
|
||||
assert_eq!(index.functions.len(), 2);
|
||||
assert_eq!(index.functions[0].local_name, "阶乘");
|
||||
@@ -380,7 +480,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn root_level_function_without_namespace() {
|
||||
let index = index_of("## main\n\n> 打印(1)\n");
|
||||
let index = index_of("## @exec main\n\n`打印(1)`\n");
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
assert_eq!(index.functions[0].id.name, "main");
|
||||
assert!(index.functions[0].namespace.is_none());
|
||||
@@ -389,16 +489,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn empty_heading_is_an_error() {
|
||||
let index = index_of("## \n\n正文\n");
|
||||
let index = index_of("## @exec\n\n正文\n");
|
||||
assert!(index
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT && d.message.contains("empty")));
|
||||
.any(|d| d.code == "sem.empty_unit_name" && d.message.contains("empty")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_function_names_are_errors() {
|
||||
let index = index_of("## f\n\n## f\n");
|
||||
let index = index_of("## @exec f\n\n## @exec f\n");
|
||||
let errors = index
|
||||
.diagnostics
|
||||
.iter()
|
||||
@@ -409,7 +509,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn same_name_in_different_namespaces_is_allowed() {
|
||||
let index = index_of("# a\n\n## f\n\n# b\n\n## f\n");
|
||||
let index = index_of("# @knowledge a\n\n## @exec f\n\n# @knowledge b\n\n## @exec f\n");
|
||||
let duplicates = index
|
||||
.diagnostics
|
||||
.iter()
|
||||
@@ -423,11 +523,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn executable_outside_function_warns_but_does_not_execute() {
|
||||
let index = index_of("**x = 1**\n\n## f\n\n*y*\n");
|
||||
assert!(index
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == codes::MARKDOWN_INERT_EXECUTABLE));
|
||||
// RFC-LANG-0002: a Strong at the Knowledge root is inert prose with no
|
||||
// diagnostic; only an Exec H2 is a callable function.
|
||||
let index = index_of("**x = 1**\n\n## @exec f\n\n`return y`\n");
|
||||
assert!(index.diagnostics.is_empty());
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,8 @@ pub enum UnitKind {
|
||||
Namespace,
|
||||
/// Level-2 heading: function.
|
||||
Function,
|
||||
/// Level-2 heading in Knowledge mode: inert knowledge unit.
|
||||
Knowledge,
|
||||
/// Level-3+ heading inside a function: named section, not a callable unit.
|
||||
Section,
|
||||
}
|
||||
|
||||
@@ -66,6 +66,19 @@ impl FrontMatter {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Whether the top-level YAML mapping contains `key`.
|
||||
///
|
||||
/// Returns `false` for invalid YAML. Used to reject removed syntax
|
||||
/// selectors such as `marqdo_semantics` or `syntax` without making the
|
||||
/// frontend depend on a YAML crate.
|
||||
pub fn has_key(&self, key: &str) -> bool {
|
||||
let Ok(yaml) = &self.yaml else {
|
||||
return false;
|
||||
};
|
||||
yaml.as_mapping()
|
||||
.is_some_and(|mapping| mapping.contains_key(key))
|
||||
}
|
||||
|
||||
/// The raw YAML parses successfully.
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.yaml.is_ok()
|
||||
|
||||
@@ -273,7 +273,7 @@ mod tests {
|
||||
fn excludes_git_and_marqdo_directories() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(&root.join("index.mq.md"), b"## main\n");
|
||||
write(&root.join("index.mq.md"), b"## @exec main\n");
|
||||
write(&root.join(".git/HEAD"), b"ref: main\n");
|
||||
write(&root.join(".marqdo/env/env.json"), b"{}");
|
||||
write(&root.join("nested/.marqdo/state"), b"x");
|
||||
@@ -343,7 +343,7 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = dir.path().join("source");
|
||||
let target = dir.path().join("target");
|
||||
write(&source.join("index.mq.md"), b"## main\n");
|
||||
write(&source.join("index.mq.md"), b"## @exec main\n");
|
||||
write(&source.join("data/value.txt"), b"42");
|
||||
write(&source.join(".git/HEAD"), b"ignored");
|
||||
let digest = hash_tree(&source).unwrap();
|
||||
|
||||
@@ -1599,7 +1599,7 @@ capabilities:
|
||||
"project:\n name: geometry\n version: 0.1.0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(first.join("index.mq.md"), "## f\n\n*1*\n").unwrap();
|
||||
std::fs::write(first.join("index.mq.md"), "## @exec f\n\n`return 1`\n").unwrap();
|
||||
let manifest = Manifest::load(&root.join(MANIFEST_FILE)).unwrap();
|
||||
let resolver =
|
||||
PackageResolver::new(root.clone(), Some(manifest.clone()), None).with_unlocked(true);
|
||||
@@ -1668,7 +1668,7 @@ capabilities:
|
||||
"project:\n name: remote\n version: 0.2.0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## hello\n\n*1*\n").unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## @exec hello\n\n`return 1`\n").unwrap();
|
||||
git(&dep, &["init", "-q"]);
|
||||
git(&dep, &["add", "."]);
|
||||
git(&dep, &["commit", "-q", "-m", "initial"]);
|
||||
@@ -1721,7 +1721,7 @@ capabilities:
|
||||
"project:\n name: geometry\n version: 0.1.0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## area\n\n*1*\n").unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## @exec area\n\n`return 1`\n").unwrap();
|
||||
std::fs::write(
|
||||
root.join(MANIFEST_FILE),
|
||||
"project:\n name: p\n version: 0.1.0\ndependencies:\n geometry:\n path: ./deps/geometry\n",
|
||||
@@ -1765,19 +1765,19 @@ capabilities:
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n a:\n path: ./deps/a\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("index.mq.md"), "## main\n\n*1*\n").unwrap();
|
||||
std::fs::write(root.join("index.mq.md"), "## @exec main\n\n`return 1`\n").unwrap();
|
||||
std::fs::write(
|
||||
a.join(MANIFEST_FILE),
|
||||
"project:\n name: a\n version: 0.1.0\ndependencies:\n b:\n path: ./b\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(a.join("index.mq.md"), "## a\n\n*1*\n").unwrap();
|
||||
std::fs::write(a.join("index.mq.md"), "## @exec a\n\n`return 1`\n").unwrap();
|
||||
std::fs::write(
|
||||
b.join(MANIFEST_FILE),
|
||||
"project:\n name: b\n version: 0.1.0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(b.join("index.mq.md"), "## b\n\n*2*\n").unwrap();
|
||||
std::fs::write(b.join("index.mq.md"), "## @exec b\n\n`return 2`\n").unwrap();
|
||||
let manifest = Manifest::load(&root.join(MANIFEST_FILE)).unwrap();
|
||||
let resolver = PackageResolver::new(root.clone(), Some(manifest), None).with_unlocked(true);
|
||||
let graph = resolver.resolve_lock_graph().unwrap();
|
||||
@@ -1813,7 +1813,7 @@ capabilities:
|
||||
"project:\n name: geometry\n version: 0.1.0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## area\n\n*1*\n").unwrap();
|
||||
std::fs::write(dep.join("index.mq.md"), "## @exec area\n\n`return 1`\n").unwrap();
|
||||
std::fs::write(
|
||||
root.join(MANIFEST_FILE),
|
||||
"project:\n name: p\n version: 0.1.0\ndependencies:\n geometry:\n path: ./deps/geometry\n",
|
||||
|
||||
@@ -64,28 +64,28 @@ fn run_and_output(source: &str, function: &str) -> (Result<Value, RuntimeError>,
|
||||
|
||||
#[test]
|
||||
fn recursion_branch_and_return() {
|
||||
let source = "## 阶乘\n\n1. `n <= 1`\n\n *1*\n\n2. `n > 1`\n\n **结果 = n * 阶乘(n=n-1)**\n\n *结果*\n";
|
||||
let source = "## @exec 阶乘\n\n`if n <= 1`\n\n`return 1`\n\n`else`\n\n`if n > 1`\n\n`结果 = n * 阶乘(n=n-1)`\n\n`return 结果`\n\n`end`\n\n`end`\n";
|
||||
let value = run_named(source, "阶乘", &[("n", Value::int(5))]).unwrap();
|
||||
assert_eq!(value, Value::int(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_mutates_and_returns_unit_for_fallthrough() {
|
||||
let source = "## 倒计时\n\n**n = 3**\n\n- `n > 0`\n\n **n = n - 1**\n";
|
||||
let source = "## @exec 倒计时\n\n`n = 3`\n\n`while n > 0`\n\n`n = n - 1`\n\n`end`\n";
|
||||
let (result, _) = run_and_output(source, "倒计时");
|
||||
assert_eq!(result.unwrap(), Value::Unit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_inside_loop_propagates() {
|
||||
let source = "## 找\n\n**i = 0**\n\n- `true`\n\n **i = i + 1**\n\n - `i >= 3`\n\n *i*\n";
|
||||
let source = "## @exec 找\n\n`i = 0`\n\n`while true`\n\n`i = i + 1`\n\n`if i >= 3`\n\n`return i`\n\n`end`\n\n`end`\n";
|
||||
let (result, _) = run_and_output(source, "找");
|
||||
assert_eq!(result.unwrap(), Value::int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_signature_supports_positional_arguments() {
|
||||
let source = "## 加\n\n`(a: Int, b: Int = 10)`\n\n*a + b*\n";
|
||||
let source = "## @exec 加\n\n`params(a: Int, b: Int = 10)`\n\n`return a + b`\n";
|
||||
let program = build(source);
|
||||
let mut host = host();
|
||||
let result = run(
|
||||
@@ -101,7 +101,7 @@ fn explicit_signature_supports_positional_arguments() {
|
||||
|
||||
#[test]
|
||||
fn builtins_for_conversions_and_length() {
|
||||
let source = "## f\n\n*长度(\"你好\") + 整数(\"40\") + 整数(2.0)*\n";
|
||||
let source = "## @exec f\n\n`return 长度(\"你好\") + 整数(\"40\") + 整数(2.0)`\n";
|
||||
let value = run_named(source, "f", &[]).unwrap();
|
||||
assert_eq!(value, Value::int(44));
|
||||
}
|
||||
@@ -109,21 +109,21 @@ fn builtins_for_conversions_and_length() {
|
||||
#[test]
|
||||
fn function_reference_can_be_called() {
|
||||
let source =
|
||||
"## 平方\n\n`(n: Int)`\n\n*n * n*\n\n## 主\n\n**f = ref(\"#平方\")**\n\n*f(n=4)*\n";
|
||||
"## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n";
|
||||
let value = run_named(source, "主", &[]).unwrap();
|
||||
assert_eq!(value, Value::int(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_bool_condition_is_a_runtime_error() {
|
||||
let source = "## f\n\n**x = 1**\n\n- `x`\n\n **x = x + 1**\n\n*x*\n";
|
||||
let source = "## @exec f\n\n`x = 1`\n\n`while x`\n\n`x = x + 1`\n\n`end`\n\n`return x`\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "runtime.type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fuel_budget_is_enforced() {
|
||||
let program = build("## f\n\n- `true`\n\n **x = 1**\n\n*0*\n");
|
||||
let program = build("## @exec f\n\n`while true`\n\n`x = 1`\n\n`end`\n\n`return 0`\n");
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
@@ -143,7 +143,7 @@ fn fuel_budget_is_enforced() {
|
||||
|
||||
#[test]
|
||||
fn recursion_depth_is_bounded() {
|
||||
let source = "## f\n\n*f(n=n + 1)*\n";
|
||||
let source = "## @exec f\n\n`return f(n=n + 1)`\n";
|
||||
let program = build(source);
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
@@ -165,14 +165,15 @@ fn recursion_depth_is_bounded() {
|
||||
|
||||
#[test]
|
||||
fn ambiguous_ref_resource_is_an_error() {
|
||||
let source = "## f\n\n### 公式\n\n$$a = 1$$\n\n$$b = 2$$\n\n**x = ref(\"#公式\")**\n\n*x*\n";
|
||||
let source =
|
||||
"## @exec f\n\n### 公式\n\n$$a = 1$$\n\n$$b = 2$$\n\n`x = ref(\"#公式\")`\n\n`return x`\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "ref.ambiguous");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_without_the_bundled_stdlib_is_a_structured_error() {
|
||||
let source = "## f\n\n> 打印(1)\n\n*None*\n";
|
||||
let source = "## @exec f\n\n`打印(1)`\n\n`return None`\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "kernel.unavailable");
|
||||
assert!(
|
||||
@@ -184,7 +185,7 @@ fn print_without_the_bundled_stdlib_is_a_structured_error() {
|
||||
|
||||
#[test]
|
||||
fn function_ref_and_resource_members_are_readable() {
|
||||
let source = "## 目标\n\n*1*\n\n## main\n\n### 公式\n\n$$a = 1$$\n\n### 代码\n\n```text\nx\n```\n\n**f = ref(\"#目标\")**\n\n**g = ref(\"#公式\")**\n\n**c = ref(\"#代码\")**\n\n*[f.module, f.name, g.latex, g.display, c.language, c.source]*\n";
|
||||
let source = "## @exec 目标\n\n`return 1`\n\n## @exec main\n\n### 公式\n\n$$a = 1$$\n\n### 代码\n\n```text\nx\n```\n\n`f = ref(\"#目标\")`\n\n`g = ref(\"#公式\")`\n\n`c = ref(\"#代码\")`\n\n`return [f.module, f.name, g.latex, g.display, c.language, c.source]`\n";
|
||||
let value = run_named(source, "main", &[]).unwrap();
|
||||
let Value::List(items) = value else {
|
||||
panic!("expected list");
|
||||
@@ -199,7 +200,7 @@ fn function_ref_and_resource_members_are_readable() {
|
||||
|
||||
#[test]
|
||||
fn memory_region_is_shared_by_handle_identity() {
|
||||
let source = "## f\n\n**m = memory.new(1, 2)**\n\n**n = m**\n\n**`m[3] = 7`**\n\n*[n[3], m == n, memory.size(n)]*\n";
|
||||
let source = "## @exec f\n\n`m = memory.new(1, 2)`\n\n`n = m`\n\n`m[3] = 7`\n\n`return [n[3], m == n, memory.size(n)]`\n";
|
||||
let value = run_named(source, "f", &[]).unwrap();
|
||||
assert_eq!(
|
||||
value,
|
||||
@@ -209,7 +210,7 @@ fn memory_region_is_shared_by_handle_identity() {
|
||||
|
||||
#[test]
|
||||
fn memory_handle_cannot_reach_the_host_boundary() {
|
||||
let source = "## f\n\n**m = memory.new(1, 1)**\n\n> fs.read(m)\n\n*0*\n";
|
||||
let source = "## @exec f\n\n`m = memory.new(1, 1)`\n\n`fs.read(m)`\n\n`return 0`\n";
|
||||
let error = run_named(source, "f", &[]).unwrap_err();
|
||||
assert_eq!(error.code(), "runtime.type");
|
||||
assert!(
|
||||
@@ -223,7 +224,8 @@ fn memory_handle_cannot_reach_the_host_boundary() {
|
||||
|
||||
#[test]
|
||||
fn memory_budget_is_enforced_without_changing_the_region() {
|
||||
let program = build("## f\n\n**m = memory.new(1, 1)**\n\n*[m[0], memory.grow(m, 1)]*\n");
|
||||
let program =
|
||||
build("## @exec f\n\n`m = memory.new(1, 1)`\n\n`return [m[0], memory.grow(m, 1)]`\n");
|
||||
let mut host = host();
|
||||
let error = run_with_limits(
|
||||
&program,
|
||||
|
||||
@@ -13,6 +13,36 @@ pub mod codes {
|
||||
pub const MARKDOWN_INERT_EXECUTABLE: &str = "markdown.inert_executable";
|
||||
/// Front matter is malformed or appears somewhere other than the document start.
|
||||
pub const FRONTMATTER_INVALID: &str = "frontmatter.invalid";
|
||||
/// A heading uses an invalid `@exec`/`@knowledge` mode marker.
|
||||
pub const SEM_INVALID_MODE_MARKER: &str = "sem.invalid_mode_marker";
|
||||
/// A mode declaration has no semantic heading name.
|
||||
pub const SEM_EMPTY_UNIT_NAME: &str = "sem.empty_unit_name";
|
||||
/// Duplicate canonical heading/unit name in one scope.
|
||||
pub const SEM_DUPLICATE_UNIT_NAME: &str = "sem.duplicate_unit_name";
|
||||
/// Executable payload appears under no Exec H2 function.
|
||||
pub const SEM_EXEC_WITHOUT_FUNCTION: &str = "sem.exec_without_function";
|
||||
/// A payload carrier contains a nested inline structure.
|
||||
pub const SEM_PAYLOAD_NESTED: &str = "sem.payload_nested";
|
||||
/// A payload carrier is empty in an Exec scope.
|
||||
pub const SEM_EMPTY_PAYLOAD: &str = "sem.empty_payload";
|
||||
/// A payload failed semantic statement validation.
|
||||
pub const SEM_SYNTAX: &str = "sem.syntax";
|
||||
/// `else` does not bind an open `if`.
|
||||
pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else";
|
||||
/// A second `else` appears for one `if`.
|
||||
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
|
||||
/// `end` closes no open frame.
|
||||
pub const SEM_UNMATCHED_END: &str = "sem.unmatched_end";
|
||||
/// A control frame is not closed before the heading ends.
|
||||
pub const SEM_UNCLOSED_CONTROL: &str = "sem.unclosed_control";
|
||||
/// `params(...)` is not the first direct Exec H2 payload.
|
||||
pub const SEM_SIGNATURE_POSITION: &str = "sem.signature_position";
|
||||
/// A version directive such as `marqdo_semantics` is forbidden.
|
||||
pub const SEM_UNSUPPORTED_VERSION_DIRECTIVE: &str = "sem.unsupported_version_directive";
|
||||
/// `run` found no callable entry function.
|
||||
pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function";
|
||||
/// A signature was inferred rather than declared.
|
||||
pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature";
|
||||
/// An executable payload failed to parse as an expression or statement.
|
||||
pub const EXPR_PARSE: &str = "expr.parse";
|
||||
/// A function name is referenced but no such function exists.
|
||||
|
||||
Reference in new issue
Block a user