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.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 数学
|
||||
# @knowledge 数学
|
||||
|
||||
## 阶乘
|
||||
## @exec 阶乘
|
||||
|
||||
定义:
|
||||
|
||||
@@ -8,12 +8,18 @@ $$
|
||||
n! = \begin{cases}1,& n\le1\\n(n-1)!,& n>1\end{cases}
|
||||
$$
|
||||
|
||||
1. `n <= 1`,递归终点。
|
||||
`if n <= 1`
|
||||
|
||||
*1*
|
||||
递归终点,返回 1。
|
||||
|
||||
2. `n > 1`,计算更小的问题。
|
||||
`return 1`
|
||||
|
||||
**结果 = n * 阶乘(n=n-1)**
|
||||
`else`
|
||||
|
||||
*结果*
|
||||
计算更小的问题。
|
||||
|
||||
`结果 = n * 阶乘(n=n-1)`
|
||||
|
||||
`return 结果`
|
||||
|
||||
`end`
|
||||
@@ -1,7 +1,7 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**问候 = "你好,Marqdo"**
|
||||
`问候 = "你好,Marqdo"`
|
||||
|
||||
> 打印(问候)
|
||||
> **打印(问候)**
|
||||
|
||||
*问候*
|
||||
`return 问候`
|
||||
@@ -1,11 +1,11 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
### 代码
|
||||
`结果 = foreign.call(ref("#代码"), {})`
|
||||
|
||||
> **打印(结果)**
|
||||
|
||||
### @knowledge 代码
|
||||
|
||||
```mocklang
|
||||
ignored by the mock provider
|
||||
```
|
||||
|
||||
**结果 = foreign.call(ref("#代码"), {})**
|
||||
|
||||
> 打印(结果)
|
||||
+5
-5
@@ -1,15 +1,15 @@
|
||||
# 数学
|
||||
# @knowledge 数学
|
||||
|
||||
## 圆面积公式
|
||||
## @knowledge 圆面积公式
|
||||
|
||||
$$
|
||||
A = \pi r^2
|
||||
$$
|
||||
|
||||
## 计算圆面积
|
||||
## @exec 计算圆面积
|
||||
|
||||
依据[圆面积公式](#圆面积公式)代入半径。
|
||||
|
||||
**面积 = math.eval(ref("#圆面积公式"), {"r": 4}, target="A")**
|
||||
`面积 = math.eval(ref("#圆面积公式"), {"r": 4}, target="A")`
|
||||
|
||||
*面积*
|
||||
`return 面积`
|
||||
@@ -1,14 +1,14 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
此函数演示“可引用的存储区域”与普通 Markdown 叙述并存。
|
||||
区域按 64 KiB 逻辑页增长,副本共享同一区域身份。
|
||||
|
||||
**区域 = memory.new(1, 4)**
|
||||
`区域 = memory.new(1, 4)`
|
||||
|
||||
**`区域[8] = 42`**
|
||||
`区域[8] = 42`
|
||||
|
||||
**另一个名字 = 区域**
|
||||
`另一个名字 = 区域`
|
||||
|
||||
**`另一个名字[9] = 99`**
|
||||
`另一个名字[9] = 99`
|
||||
|
||||
*区域[8] + 区域[9]*
|
||||
`return 区域[8] + 区域[9]`
|
||||
@@ -1,10 +1,10 @@
|
||||
## 圆面积
|
||||
## @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
|
||||
|
||||
@@ -3,8 +3,8 @@ import:
|
||||
geometry: "./geometry.mq.md"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**面积 = geometry.圆面积(r=2)**
|
||||
`面积 = geometry.圆面积(r=2)`
|
||||
|
||||
> 打印(面积)
|
||||
> **打印(面积)**
|
||||
@@ -4,12 +4,12 @@ import:
|
||||
geometry_v2: "@geometry_v2"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**一 = geometry_v1.area()**
|
||||
`一 = geometry_v1.area()`
|
||||
|
||||
**二 = geometry_v2.area()**
|
||||
`二 = geometry_v2.area()`
|
||||
|
||||
> 打印(一)
|
||||
> **打印(一)**
|
||||
|
||||
> 打印(二)
|
||||
> **打印(二)**
|
||||
@@ -4,24 +4,24 @@ root:
|
||||
package: root:multi-version@0.1.0
|
||||
manifest_digest: 959bfcdd1f8174365e43a2690d80bb61ea2b7c9ca5e1476abc582600551a0d40
|
||||
packages:
|
||||
- instance_id: dep:geometry@1.0.0#76cb510d5f6ef15845a648ddf20749bc5a87bbce04008f4666cf9ac9ea14f643
|
||||
- instance_id: dep:geometry@1.0.0#d856df8a5cc47974ec256d3c939d8a1e206d82126111d2ffe1b959fcc29a4311
|
||||
name: geometry
|
||||
version: 1.0.0
|
||||
source:
|
||||
kind: path
|
||||
path: packages/geometry-v1
|
||||
content_digest: 76cb510d5f6ef15845a648ddf20749bc5a87bbce04008f4666cf9ac9ea14f643
|
||||
content_digest: d856df8a5cc47974ec256d3c939d8a1e206d82126111d2ffe1b959fcc29a4311
|
||||
manifest_digest: 3049840e18aefb2766c62406db0545cb9cc100d9d12b1dd9585e6ecb358c321a
|
||||
dependencies: {}
|
||||
- instance_id: dep:geometry@2.0.0#f364164e6b6927e85bd9e4c360de575ee7bef2b3e8bd30180cab04052ceaff29
|
||||
- instance_id: dep:geometry@2.0.0#7c625a31b3f95a1fba38f0d87afd95554937b6c2ae261e8c9208637d76e5389d
|
||||
name: geometry
|
||||
version: 2.0.0
|
||||
source:
|
||||
kind: path
|
||||
path: packages/geometry-v2
|
||||
content_digest: f364164e6b6927e85bd9e4c360de575ee7bef2b3e8bd30180cab04052ceaff29
|
||||
content_digest: 7c625a31b3f95a1fba38f0d87afd95554937b6c2ae261e8c9208637d76e5389d
|
||||
manifest_digest: b206f83f82af59995a6bda82a36627d98deb709cfac36c684ced1531f4afba2a
|
||||
dependencies: {}
|
||||
root_dependencies:
|
||||
geometry_v1: dep:geometry@1.0.0#76cb510d5f6ef15845a648ddf20749bc5a87bbce04008f4666cf9ac9ea14f643
|
||||
geometry_v2: dep:geometry@2.0.0#f364164e6b6927e85bd9e4c360de575ee7bef2b3e8bd30180cab04052ceaff29
|
||||
geometry_v1: dep:geometry@1.0.0#d856df8a5cc47974ec256d3c939d8a1e206d82126111d2ffe1b959fcc29a4311
|
||||
geometry_v2: dep:geometry@2.0.0#7c625a31b3f95a1fba38f0d87afd95554937b6c2ae261e8c9208637d76e5389d
|
||||
@@ -1,3 +1,3 @@
|
||||
## area
|
||||
## @exec area
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
@@ -1,3 +1,3 @@
|
||||
## area
|
||||
## @exec area
|
||||
|
||||
*2*
|
||||
`return 2`
|
||||
@@ -125,11 +125,11 @@ are callable through the namespace that prefixes their export names. Plugin
|
||||
calls take **named arguments only** in this build:
|
||||
|
||||
```markdown
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**结果 = solver.add(a=20, b=22)**
|
||||
`结果 = solver.add(a=20, b=22)`
|
||||
|
||||
> 打印(结果)
|
||||
> **打印(结果)**
|
||||
```
|
||||
|
||||
```sh
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**结果 = solver.add(a=20, b=22)**
|
||||
`结果 = solver.add(a=20, b=22)`
|
||||
|
||||
> 打印(结果)
|
||||
> **打印(结果)**
|
||||
@@ -1,9 +1,9 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**和 = solver.add(a=20, b=22)**
|
||||
`和 = solver.add(a=20, b=22)`
|
||||
|
||||
**相反数 = solver.neg(a=7)**
|
||||
`相反数 = solver.neg(a=7)`
|
||||
|
||||
> 打印(和)
|
||||
> **打印(和)**
|
||||
|
||||
> 打印(相反数)
|
||||
> **打印(相反数)**
|
||||
@@ -1,4 +1,4 @@
|
||||
## Python 校验
|
||||
## @knowledge Python 校验
|
||||
|
||||
```python
|
||||
import json, math, sys
|
||||
@@ -9,8 +9,8 @@ area = math.pi * r ** 2
|
||||
print(json.dumps({"type": "map", "entries": {"area": {"type": "float", "value": area}}}))
|
||||
```
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**结果 = foreign.call(ref("#python-校验"), {"r": 3})**
|
||||
`结果 = foreign.call(ref("#python-校验"), {"r": 3})`
|
||||
|
||||
> 打印(结果.area)
|
||||
> **打印(结果.area)**
|
||||
@@ -1,6 +1,6 @@
|
||||
# 参考
|
||||
# @knowledge 参考
|
||||
|
||||
## 牛顿第二定律
|
||||
## @knowledge 牛顿第二定律
|
||||
|
||||
$$
|
||||
F = m a
|
||||
@@ -8,8 +8,8 @@ $$
|
||||
|
||||
参见[圆面积](./math.mq.md#计算圆面积)(这是静态引用,不会执行)。
|
||||
|
||||
## 计算作用力
|
||||
## @exec 计算作用力
|
||||
|
||||
**力 = math.eval(ref("#牛顿第二定律"), {"m": 2, "a": 3}, target="F")**
|
||||
`力 = math.eval(ref("#牛顿第二定律"), {"m": 2, "a": 3}, target="F")`
|
||||
|
||||
*力*
|
||||
`return 力`
|
||||
@@ -3,8 +3,8 @@ import:
|
||||
io: "std:io"
|
||||
---
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
> io.写值(["bundle", 1, 2.5])
|
||||
> **io.写值(["bundle", 1, 2.5])**
|
||||
|
||||
*None*
|
||||
`return None`
|
||||
+6
-4
@@ -1,8 +1,10 @@
|
||||
|
||||
# @exec clock
|
||||
## 现在
|
||||
|
||||
`()`
|
||||
`params()`
|
||||
|
||||
返回项目模式下的 UTC Unix 毫秒。`pure`/`strict` 返回
|
||||
`permission.denied`,与 `resource.request` 的其他操作一致。
|
||||
返回项目模式下的 UTC Unix 毫秒。pure/strict 返回
|
||||
permission.denied,与 resource.request 的其他操作一致。
|
||||
|
||||
*resource.request("clock.now", [])*
|
||||
`return resource.request("clock.now", [])`
|
||||
@@ -1,17 +1,19 @@
|
||||
|
||||
# @exec compress
|
||||
## 压缩
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
把 UTF-8 文本压缩为 gzip 字节列表(`List<Int>`,0–255)。输入上限
|
||||
把 UTF-8 文本压缩为 gzip 字节列表(List<Int>,0–255)。输入上限
|
||||
8 MiB;结果确定(不写入时间戳/文件名)。
|
||||
|
||||
*resource.request("compress.gzip", [文本])*
|
||||
`return resource.request("compress.gzip", [文本])`
|
||||
|
||||
## 解压
|
||||
|
||||
`(字节列表)`
|
||||
`params(字节列表)`
|
||||
|
||||
解压 gzip 字节列表并校验 UTF-8。输出上限 8 MiB;坏 gzip 返回
|
||||
`compress.invalid`,非 UTF-8 返回 `compress.not_utf8`。
|
||||
compress.invalid,非 UTF-8 返回 compress.not_utf8。
|
||||
|
||||
*resource.request("compress.gunzip", [字节列表])*
|
||||
`return resource.request("compress.gunzip", [字节列表])`
|
||||
+179
-116
@@ -1,20 +1,22 @@
|
||||
|
||||
# @exec csv
|
||||
## 成功
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
*{ok: true, value: 值}*
|
||||
`return {ok: true, value: 值}`
|
||||
|
||||
## 失败
|
||||
|
||||
`(代码, 消息)`
|
||||
`params(代码, 消息)`
|
||||
|
||||
*{ok: false, code: 代码, message: 消息}*
|
||||
`return {ok: false, code: 代码, message: 消息}`
|
||||
|
||||
## 解析行
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
解析单行 CSV:逗号分隔、双引号包裹、`""` 表示一个字面双引号。
|
||||
解析单行 CSV:逗号分隔、双引号包裹、"" 表示一个字面双引号。
|
||||
不处理换行、多行字段或首尾空白。未闭合引号和未加引号字段中的双引号
|
||||
返回可恢复错误。
|
||||
|
||||
@@ -30,71 +32,90 @@
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `下标 < 长度(点) and 错误 == ""`
|
||||
`while 下标 < 长度(点) and 错误 == ""`
|
||||
|
||||
**字符 = text.from_codepoint(点[下标])**
|
||||
**字符 = text.from_codepoint(点[下标])**
|
||||
|
||||
1. `引号内 and 字符 == "\""`
|
||||
`if 引号内 and 字符 == "\""`
|
||||
|
||||
1. `下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""`
|
||||
`if 下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""`
|
||||
|
||||
**`字段 = 字段 + "\""`**
|
||||
**`字段 = 字段 + "\""`**
|
||||
|
||||
**下标 = 下标 + 2**
|
||||
**下标 = 下标 + 2**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**引号内 = false**
|
||||
**引号内 = false**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
2. `引号内`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 引号内`
|
||||
|
||||
**字段 = 字段 + 字符**
|
||||
**字段 = 字段 + 字符**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
3. `字符 == "\""`
|
||||
`else`
|
||||
`if 字符 == "\""`
|
||||
|
||||
1. `字段 == ""`
|
||||
`if 字段 == ""`
|
||||
|
||||
**引号内 = true**
|
||||
**引号内 = true**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**错误 = "csv.invalid_quote"**
|
||||
**错误 = "csv.invalid_quote"**
|
||||
|
||||
4. `字符 == ","`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 字符 == ","`
|
||||
|
||||
**字段表 = list.append(字段表, 字段)**
|
||||
**字段表 = list.append(字段表, 字段)**
|
||||
|
||||
**字段 = ""**
|
||||
**字段 = ""**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
5. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**字段 = 字段 + 字符**
|
||||
**字段 = 字段 + 字符**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
1. `错误 != ""`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 错误 != ""`
|
||||
|
||||
*失败(错误, "未加引号字段中出现双引号")*
|
||||
`return 失败(错误, "未加引号字段中出现双引号")`
|
||||
|
||||
1. `引号内`
|
||||
`else`
|
||||
`if 引号内`
|
||||
|
||||
*失败("csv.unterminated_quote", "引号未闭合")*
|
||||
`return 失败("csv.unterminated_quote", "引号未闭合")`
|
||||
|
||||
*成功(list.concat(字段表, [字段]))*
|
||||
`end`
|
||||
`end`
|
||||
`return 成功(list.concat(字段表, [字段]))`
|
||||
|
||||
## 格式化字段
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
含逗号、双引号、换行或回车的字段加引号,内部双引号写成 `""`。
|
||||
含逗号、双引号、换行或回车的字段加引号,内部双引号写成 ""。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -102,72 +123,85 @@
|
||||
|
||||
**需要引号 = false**
|
||||
|
||||
- `下标 < 长度(点) and not 需要引号`
|
||||
`while 下标 < 长度(点) and not 需要引号`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
**码点 = 点[下标]**
|
||||
|
||||
1. `码点 == 34 or 码点 == 44 or 码点 == 10 or 码点 == 13`
|
||||
`if 码点 == 34 or 码点 == 44 or 码点 == 10 or 码点 == 13`
|
||||
|
||||
**需要引号 = true**
|
||||
**需要引号 = true**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
1. `not 需要引号`
|
||||
`end`
|
||||
`if not 需要引号`
|
||||
|
||||
*文本*
|
||||
`return 文本`
|
||||
|
||||
`end`
|
||||
**`结果 = "\""`**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
1. `点[下标] == 34`
|
||||
`if 点[下标] == 34`
|
||||
|
||||
**`结果 = 结果 + "\"\""`**
|
||||
**`结果 = 结果 + "\"\""`**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*`结果 + "\""`*
|
||||
`end`
|
||||
``return 结果 + "\""``
|
||||
|
||||
## 格式化行
|
||||
|
||||
`(列表)`
|
||||
`params(列表)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表)`
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + ","**
|
||||
**结果 = 结果 + ","**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 格式化字段(文本(列表[下标]))**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 格式化字段(文本(列表[下标]))**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 解析
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
解析多行 CSV(逗号分隔、双引号、`""` 转义、CRLF/LF 行尾,引号内可含
|
||||
换行)。返回 `{ok:true, value:List<List<Text>>}`;未闭合引号和不合法
|
||||
解析多行 CSV(逗号分隔、双引号、"" 转义、CRLF/LF 行尾,引号内可含
|
||||
换行)。返回 {ok:true, value:List<List<Text>>};未闭合引号和不合法
|
||||
引号返回可恢复错误。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
@@ -184,108 +218,137 @@
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `下标 < 长度(点) and 错误 == ""`
|
||||
`while 下标 < 长度(点) and 错误 == ""`
|
||||
|
||||
**字符 = text.from_codepoint(点[下标])**
|
||||
**字符 = text.from_codepoint(点[下标])**
|
||||
|
||||
1. `引号内 and 字符 == "\""`
|
||||
`if 引号内 and 字符 == "\""`
|
||||
|
||||
1. `下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""`
|
||||
`if 下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""`
|
||||
|
||||
**`字段 = 字段 + "\""`**
|
||||
**`字段 = 字段 + "\""`**
|
||||
|
||||
**下标 = 下标 + 2**
|
||||
**下标 = 下标 + 2**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**引号内 = false**
|
||||
**引号内 = false**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
2. `引号内`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 引号内`
|
||||
|
||||
**字段 = 字段 + 字符**
|
||||
**字段 = 字段 + 字符**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
3. `字符 == "\""`
|
||||
`else`
|
||||
`if 字符 == "\""`
|
||||
|
||||
1. `字段 == ""`
|
||||
`if 字段 == ""`
|
||||
|
||||
**引号内 = true**
|
||||
**引号内 = true**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**错误 = "csv.invalid_quote"**
|
||||
**错误 = "csv.invalid_quote"**
|
||||
|
||||
4. `字符 == ","`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 字符 == ","`
|
||||
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
|
||||
**字段 = ""**
|
||||
**字段 = ""**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
5. `字符 == "\n"`
|
||||
`else`
|
||||
`if 字符 == "\n"`
|
||||
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
|
||||
**行 = list.append(行, 当前行)**
|
||||
**行 = list.append(行, 当前行)**
|
||||
|
||||
**当前行 = []**
|
||||
**当前行 = []**
|
||||
|
||||
**字段 = ""**
|
||||
**字段 = ""**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
6. `字符 == "\r"`
|
||||
`else`
|
||||
`if 字符 == "\r"`
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
7. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**字段 = 字段 + 字符**
|
||||
**字段 = 字段 + 字符**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
1. `错误 != ""`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 错误 != ""`
|
||||
|
||||
*失败(错误, "未加引号字段中出现双引号")*
|
||||
`return 失败(错误, "未加引号字段中出现双引号")`
|
||||
|
||||
1. `引号内`
|
||||
`else`
|
||||
`if 引号内`
|
||||
|
||||
*失败("csv.unterminated_quote", "引号未闭合")*
|
||||
`return 失败("csv.unterminated_quote", "引号未闭合")`
|
||||
|
||||
1. `字段 != "" or 长度(当前行) > 0`
|
||||
`else`
|
||||
`if 字段 != "" or 长度(当前行) > 0`
|
||||
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
**当前行 = list.append(当前行, 字段)**
|
||||
|
||||
**行 = list.append(行, 当前行)**
|
||||
**行 = list.append(行, 当前行)**
|
||||
|
||||
*成功(行)*
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`return 成功(行)`
|
||||
|
||||
## 格式化
|
||||
|
||||
`(行列表)`
|
||||
`params(行列表)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(行列表)`
|
||||
`while 行号 < 长度(行列表)`
|
||||
|
||||
1. `行号 > 0`
|
||||
`if 行号 > 0`
|
||||
|
||||
**结果 = 结果 + "\n"**
|
||||
**结果 = 结果 + "\n"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 格式化行(行列表[行号])**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 格式化行(行列表[行号])**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
+468
-292
File diff suppressed because it is too large.
Load diff
+181
-130
@@ -1,6 +1,8 @@
|
||||
|
||||
# @exec table
|
||||
## 选择列
|
||||
|
||||
`(数据, 列)`
|
||||
`params(数据, 列)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -8,19 +10,20 @@
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**行 = table.row(数据, 行号)**
|
||||
**行 = table.row(数据, 行号)**
|
||||
|
||||
**结果行 = list.append(结果行, [行[列]])**
|
||||
**结果行 = list.append(结果行, [行[列]])**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*表([列名[列]], 结果行)*
|
||||
`end`
|
||||
`return 表([列名[列]], 结果行)`
|
||||
|
||||
## 过滤数值大于
|
||||
|
||||
`(数据, 列, 阈值)`
|
||||
`params(数据, 列, 阈值)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -28,25 +31,29 @@
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**行 = table.row(数据, 行号)**
|
||||
**行 = table.row(数据, 行号)**
|
||||
|
||||
1. `行[列] > 阈值`
|
||||
`if 行[列] > 阈值`
|
||||
|
||||
**结果行 = list.append(结果行, 行)**
|
||||
**结果行 = list.append(结果行, 行)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*表(列名, 结果行)*
|
||||
`end`
|
||||
`return 表(列名, 结果行)`
|
||||
|
||||
## 插入有序
|
||||
|
||||
`(已排序, 行, 列)`
|
||||
`params(已排序, 行, 列)`
|
||||
|
||||
**新列表 = []**
|
||||
|
||||
@@ -54,37 +61,44 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(已排序)`
|
||||
`while 下标 < 长度(已排序)`
|
||||
|
||||
**当前行 = 已排序[下标]**
|
||||
**当前行 = 已排序[下标]**
|
||||
|
||||
1. `not 已插入 and 当前行[列] > 行[列]`
|
||||
`if not 已插入 and 当前行[列] > 行[列]`
|
||||
|
||||
**新列表 = list.append(新列表, 行)**
|
||||
**新列表 = list.append(新列表, 行)**
|
||||
|
||||
**新列表 = list.append(新列表, 当前行)**
|
||||
**新列表 = list.append(新列表, 当前行)**
|
||||
|
||||
**已插入 = true**
|
||||
**已插入 = true**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**新列表 = list.append(新列表, 当前行)**
|
||||
**新列表 = list.append(新列表, 当前行)**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
1. `not 已插入`
|
||||
`end`
|
||||
`if not 已插入`
|
||||
|
||||
**新列表 = list.append(新列表, 行)**
|
||||
**新列表 = list.append(新列表, 行)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
*新列表*
|
||||
`end`
|
||||
`end`
|
||||
`return 新列表`
|
||||
|
||||
## 排序
|
||||
|
||||
`(数据, 列)`
|
||||
`params(数据, 列)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -94,17 +108,18 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 行数`
|
||||
`while 下标 < 行数`
|
||||
|
||||
**已排序 = 插入有序(已排序, table.row(数据, 下标), 列)**
|
||||
**已排序 = 插入有序(已排序, table.row(数据, 下标), 列)**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*表(列名, 已排序)*
|
||||
`end`
|
||||
`return 表(列名, 已排序)`
|
||||
|
||||
## 追加行
|
||||
|
||||
`(数据, 行)`
|
||||
`params(数据, 行)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -112,17 +127,18 @@
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**所有行 = list.append(所有行, table.row(数据, 行号))**
|
||||
**所有行 = list.append(所有行, table.row(数据, 行号))**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*表(列名, list.append(所有行, 行))*
|
||||
`end`
|
||||
`return 表(列名, list.append(所有行, 行))`
|
||||
|
||||
## 设置单元格
|
||||
|
||||
`(数据, 目标行, 目标列, 值)`
|
||||
`params(数据, 目标行, 目标列, 值)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -130,41 +146,49 @@
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**行 = table.row(数据, 行号)**
|
||||
**行 = table.row(数据, 行号)**
|
||||
|
||||
1. `行号 == 目标行`
|
||||
`if 行号 == 目标行`
|
||||
|
||||
**新行 = []**
|
||||
**新行 = []**
|
||||
|
||||
**列号 = 0**
|
||||
**列号 = 0**
|
||||
|
||||
- `列号 < 长度(行)`
|
||||
`while 列号 < 长度(行)`
|
||||
|
||||
1. `列号 == 目标列`
|
||||
`if 列号 == 目标列`
|
||||
|
||||
**新行 = list.append(新行, 值)**
|
||||
**新行 = list.append(新行, 值)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**新行 = list.append(新行, 行[列号])**
|
||||
**新行 = list.append(新行, 行[列号])**
|
||||
|
||||
**列号 = 列号 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**列号 = 列号 + 1**
|
||||
|
||||
**新行表 = list.append(新行表, 新行)**
|
||||
`end`
|
||||
**新行表 = list.append(新行表, 新行)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**新行表 = list.append(新行表, 行)**
|
||||
**新行表 = list.append(新行表, 行)**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*表(列名, 新行表)*
|
||||
`end`
|
||||
`return 表(列名, 新行表)`
|
||||
|
||||
## 连接
|
||||
|
||||
`(左, 右, 左列, 右列)`
|
||||
`params(左, 右, 左列, 右列)`
|
||||
|
||||
**表头 = list.concat(table.columns(左), table.columns(右))**
|
||||
|
||||
@@ -172,117 +196,134 @@
|
||||
|
||||
**左行号 = 0**
|
||||
|
||||
- `左行号 < 长度(左)`
|
||||
`while 左行号 < 长度(左)`
|
||||
|
||||
**左行 = table.row(左, 左行号)**
|
||||
**左行 = table.row(左, 左行号)**
|
||||
|
||||
**键 = 左行[左列]**
|
||||
**键 = 左行[左列]**
|
||||
|
||||
**右行号 = 0**
|
||||
**右行号 = 0**
|
||||
|
||||
- `右行号 < 长度(右)`
|
||||
`while 右行号 < 长度(右)`
|
||||
|
||||
**右行 = table.row(右, 右行号)**
|
||||
**右行 = table.row(右, 右行号)**
|
||||
|
||||
1. `右行[右列] == 键`
|
||||
`if 右行[右列] == 键`
|
||||
|
||||
**结果行 = list.append(结果行, list.concat(左行, 右行))**
|
||||
**结果行 = list.append(结果行, list.concat(左行, 右行))**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**右行号 = 右行号 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**右行号 = 右行号 + 1**
|
||||
|
||||
**左行号 = 左行号 + 1**
|
||||
`end`
|
||||
**左行号 = 左行号 + 1**
|
||||
|
||||
*表(表头, 结果行)*
|
||||
`end`
|
||||
`return 表(表头, 结果行)`
|
||||
|
||||
## 分组
|
||||
|
||||
`(数据, 键列, 值列)`
|
||||
`params(数据, 键列, 值列)`
|
||||
|
||||
**结果 = {}**
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**行 = table.row(数据, 行号)**
|
||||
**行 = table.row(数据, 行号)**
|
||||
|
||||
**键 = 行[键列]**
|
||||
**键 = 行[键列]**
|
||||
|
||||
**当前 = map.get(结果, 键)**
|
||||
**当前 = map.get(结果, 键)**
|
||||
|
||||
**列表 = []**
|
||||
**列表 = []**
|
||||
|
||||
1. `map.has(结果, 键)`
|
||||
`if map.has(结果, 键)`
|
||||
|
||||
**列表 = 当前**
|
||||
**列表 = 当前**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**列表 = list.append(列表, 行[值列])**
|
||||
`end`
|
||||
`end`
|
||||
**列表 = list.append(列表, 行[值列])**
|
||||
|
||||
**结果 = map.set(结果, 键, 列表)**
|
||||
**结果 = map.set(结果, 键, 列表)**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 连接片段
|
||||
|
||||
`(片段)`
|
||||
`params(片段)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(片段)`
|
||||
`while 下标 < 长度(片段)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + " | "**
|
||||
**结果 = 结果 + " | "**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 片段[下标]**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 片段[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 连接行
|
||||
|
||||
`(行列表)`
|
||||
`params(行列表)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(行列表)`
|
||||
`while 下标 < 长度(行列表)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + "\n"**
|
||||
**结果 = 结果 + "\n"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 行列表[下标]**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 行列表[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 转义单元格
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
**文本值 = 文本(值)**
|
||||
|
||||
@@ -292,27 +333,33 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
1. `点[下标] == 124`
|
||||
`if 点[下标] == 124`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(92) + "|"**
|
||||
**结果 = 结果 + text.from_codepoint(92) + "|"**
|
||||
|
||||
2. `点[下标] == 10 or 点[下标] == 13`
|
||||
`else`
|
||||
`if 点[下标] == 10 or 点[下标] == 13`
|
||||
|
||||
**结果 = 结果 + " "**
|
||||
**结果 = 结果 + " "**
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 转GFM
|
||||
|
||||
`(数据)`
|
||||
`params(数据)`
|
||||
|
||||
**列名 = table.columns(数据)**
|
||||
|
||||
@@ -320,12 +367,13 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列名)`
|
||||
`while 下标 < 长度(列名)`
|
||||
|
||||
**表头 = list.append(表头, 转义单元格(列名[下标]))**
|
||||
**表头 = list.append(表头, 转义单元格(列名[下标]))**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
**行列表 = []**
|
||||
|
||||
**行列表 = list.append(行列表, "| " + 连接片段(表头) + " |")**
|
||||
@@ -334,32 +382,35 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列名)`
|
||||
`while 下标 < 长度(列名)`
|
||||
|
||||
**分隔 = list.append(分隔, "---")**
|
||||
**分隔 = list.append(分隔, "---")**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
**行列表 = list.append(行列表, "| " + 连接片段(分隔) + " |")**
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(数据)`
|
||||
`while 行号 < 长度(数据)`
|
||||
|
||||
**行 = table.row(数据, 行号)**
|
||||
**行 = table.row(数据, 行号)**
|
||||
|
||||
**单元格 = []**
|
||||
**单元格 = []**
|
||||
|
||||
**列号 = 0**
|
||||
**列号 = 0**
|
||||
|
||||
- `列号 < 长度(行)`
|
||||
`while 列号 < 长度(行)`
|
||||
|
||||
**单元格 = list.append(单元格, 转义单元格(行[列号]))**
|
||||
**单元格 = list.append(单元格, 转义单元格(行[列号]))**
|
||||
|
||||
**列号 = 列号 + 1**
|
||||
**列号 = 列号 + 1**
|
||||
|
||||
**行列表 = list.append(行列表, "| " + 连接片段(单元格) + " |")**
|
||||
`end`
|
||||
**行列表 = list.append(行列表, "| " + 连接片段(单元格) + " |")**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*连接行(行列表)*
|
||||
`end`
|
||||
`return 连接行(行列表)`
|
||||
+131
-90
@@ -1,98 +1,115 @@
|
||||
|
||||
# @exec datetime
|
||||
## 失败
|
||||
|
||||
`(消息)`
|
||||
`params(消息)`
|
||||
|
||||
*{ok: false, code: "datetime.invalid", message: 消息}*
|
||||
`return {ok: false, code: "datetime.invalid", message: 消息}`
|
||||
|
||||
## 闰年
|
||||
|
||||
`(年)`
|
||||
`params(年)`
|
||||
|
||||
*年 % 4 == 0 and (年 % 100 != 0 or 年 % 400 == 0)*
|
||||
`return 年 % 4 == 0 and (年 % 100 != 0 or 年 % 400 == 0)`
|
||||
|
||||
## 每月天数
|
||||
|
||||
`(年, 月)`
|
||||
`params(年, 月)`
|
||||
|
||||
1. `月 == 2`
|
||||
`if 月 == 2`
|
||||
|
||||
1. `闰年(年)`
|
||||
`if 闰年(年)`
|
||||
|
||||
*29*
|
||||
`return 29`
|
||||
|
||||
*28*
|
||||
`end`
|
||||
`return 28`
|
||||
|
||||
2. `月 == 4 or 月 == 6 or 月 == 9 or 月 == 11`
|
||||
`else`
|
||||
`if 月 == 4 or 月 == 6 or 月 == 9 or 月 == 11`
|
||||
|
||||
*30*
|
||||
`return 30`
|
||||
|
||||
*31*
|
||||
`end`
|
||||
`end`
|
||||
`return 31`
|
||||
|
||||
## 补零2
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
`if 值 < 10`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
`return "0" + 文本(值)`
|
||||
|
||||
*文本(值)*
|
||||
`end`
|
||||
`return 文本(值)`
|
||||
|
||||
## 补零3
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
`if 值 < 10`
|
||||
|
||||
*"00" + 文本(值)*
|
||||
`return "00" + 文本(值)`
|
||||
|
||||
2. `值 < 100`
|
||||
`else`
|
||||
`if 值 < 100`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
`return "0" + 文本(值)`
|
||||
|
||||
*文本(值)*
|
||||
`end`
|
||||
`end`
|
||||
`return 文本(值)`
|
||||
|
||||
## 补零4
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
`if 值 < 10`
|
||||
|
||||
*"000" + 文本(值)*
|
||||
`return "000" + 文本(值)`
|
||||
|
||||
2. `值 < 100`
|
||||
`else`
|
||||
`if 值 < 100`
|
||||
|
||||
*"00" + 文本(值)*
|
||||
`return "00" + 文本(值)`
|
||||
|
||||
3. `值 < 1000`
|
||||
`else`
|
||||
`if 值 < 1000`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
`return "0" + 文本(值)`
|
||||
|
||||
*文本(值)*
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`return 文本(值)`
|
||||
|
||||
## 月份
|
||||
|
||||
`(mp)`
|
||||
`params(mp)`
|
||||
|
||||
1. `mp < 10`
|
||||
`if mp < 10`
|
||||
|
||||
*mp + 3*
|
||||
`return mp + 3`
|
||||
|
||||
*mp - 9*
|
||||
`end`
|
||||
`return mp - 9`
|
||||
|
||||
## 年份
|
||||
|
||||
`(年, 月)`
|
||||
`params(年, 月)`
|
||||
|
||||
1. `月 <= 2`
|
||||
`if 月 <= 2`
|
||||
|
||||
*年 + 1*
|
||||
`return 年 + 1`
|
||||
|
||||
*年*
|
||||
`end`
|
||||
`return 年`
|
||||
|
||||
## 日期部件
|
||||
|
||||
`(天)`
|
||||
`params(天)`
|
||||
|
||||
Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
@@ -114,45 +131,51 @@ Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**月 = 月份(mp)**
|
||||
|
||||
*{年: 年份(年, 月), 月: 月, 日: 日}*
|
||||
`return {年: 年份(年, 月), 月: 月, 日: 日}`
|
||||
|
||||
## 日期序号
|
||||
|
||||
`(年, 月, 日)`
|
||||
`params(年, 月, 日)`
|
||||
|
||||
**y = 年**
|
||||
|
||||
1. `月 <= 2`
|
||||
`if 月 <= 2`
|
||||
|
||||
**y = y - 1**
|
||||
**y = y - 1**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**era = y // 400**
|
||||
|
||||
**yoe = y - era * 400**
|
||||
|
||||
**m = 月**
|
||||
|
||||
1. `月 > 2`
|
||||
`if 月 > 2`
|
||||
|
||||
**m = 月 - 3**
|
||||
**m = 月 - 3**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**m = 月 + 9**
|
||||
**m = 月 + 9**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**doy = (153 * m + 2) // 5 + 日 - 1**
|
||||
|
||||
**doe = yoe * 365 + yoe // 4 - yoe // 100 + doy**
|
||||
|
||||
*era * 146097 + doe - 719468*
|
||||
`return era * 146097 + doe - 719468`
|
||||
|
||||
## 是数字串
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -160,42 +183,47 @@ Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点) and 结果`
|
||||
`while 下标 < 长度(点) and 结果`
|
||||
|
||||
1. `点[下标] < 48 or 点[下标] > 57`
|
||||
`if 点[下标] < 48 or 点[下标] > 57`
|
||||
|
||||
**结果 = false**
|
||||
**结果 = false**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 片段
|
||||
|
||||
`(点, 起点, 终点)`
|
||||
`params(点, 起点, 终点)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 起点**
|
||||
|
||||
- `下标 < 终点`
|
||||
`while 下标 < 终点`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 格式化
|
||||
|
||||
`(毫秒)`
|
||||
`params(毫秒)`
|
||||
|
||||
输出 UTC ISO-8601:`YYYY-MM-DDTHH:MM:SSZ`;毫秒非零时追加
|
||||
`.mmm`。负数毫秒按 1970 前的 UTC 时间处理。
|
||||
输出 UTC ISO-8601:YYYY-MM-DDTHH:MM:SSZ;毫秒非零时追加
|
||||
.mmm。负数毫秒按 1970 前的 UTC 时间处理。
|
||||
|
||||
**秒 = 毫秒 // 1000**
|
||||
|
||||
@@ -215,29 +243,33 @@ Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**基 = 补零4(日期.年) + "-" + 补零2(日期.月) + "-" + 补零2(日期.日) + "T" + 补零2(时) + ":" + 补零2(分) + ":" + 补零2(秒数)**
|
||||
|
||||
1. `毫 == 0`
|
||||
`if 毫 == 0`
|
||||
|
||||
*基 + "Z"*
|
||||
`return 基 + "Z"`
|
||||
|
||||
*基 + "." + 补零3(毫) + "Z"*
|
||||
`end`
|
||||
`return 基 + "." + 补零3(毫) + "Z"`
|
||||
|
||||
## 解析
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
解析 `YYYY-MM-DDTHH:MM:SSZ` 或带 `.mmm` 的 UTC 文本,返回 Unix 毫秒。
|
||||
范围、闰年和格式错误都是可恢复 `datetime.invalid`。
|
||||
解析 YYYY-MM-DDTHH:MM:SSZ 或带 .mmm 的 UTC 文本,返回 Unix 毫秒。
|
||||
范围、闰年和格式错误都是可恢复 datetime.invalid。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
1. `长度(点) < 20 or 长度(点) > 24`
|
||||
`if 长度(点) < 20 or 长度(点) > 24`
|
||||
|
||||
*失败("长度不是 20–24 个码点")*
|
||||
`return 失败("长度不是 20–24 个码点")`
|
||||
|
||||
1. `点[4] != 45 or 点[7] != 45 or 点[10] != 84 or 点[13] != 58 or 点[16] != 58`
|
||||
`else`
|
||||
`if 点[4] != 45 or 点[7] != 45 or 点[10] != 84 or 点[13] != 58 or 点[16] != 58`
|
||||
|
||||
*失败("分隔符不符合 YYYY-MM-DDTHH:MM:SS")*
|
||||
`return 失败("分隔符不符合 YYYY-MM-DDTHH:MM:SS")`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**年文本 = 片段(点, 0, 4)**
|
||||
|
||||
**月文本 = 片段(点, 5, 7)**
|
||||
@@ -250,10 +282,11 @@ Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**秒文本 = 片段(点, 17, 19)**
|
||||
|
||||
1. `not 是数字串(年文本) or not 是数字串(月文本) or not 是数字串(日文本) or not 是数字串(时文本) or not 是数字串(分文本) or not 是数字串(秒文本)`
|
||||
`if not 是数字串(年文本) or not 是数字串(月文本) or not 是数字串(日文本) or not 是数字串(时文本) or not 是数字串(分文本) or not 是数字串(秒文本)`
|
||||
|
||||
*失败("日期时间分量必须是数字")*
|
||||
`return 失败("日期时间分量必须是数字")`
|
||||
|
||||
`end`
|
||||
**年 = 整数(年文本)**
|
||||
|
||||
**月 = 整数(月文本)**
|
||||
@@ -270,30 +303,38 @@ Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**结束 = 20**
|
||||
|
||||
1. `长度(点) >= 24 and 点[19] == 46 and 点[23] == 90`
|
||||
`if 长度(点) >= 24 and 点[19] == 46 and 点[23] == 90`
|
||||
|
||||
**毫文本 = 片段(点, 20, 23)**
|
||||
**毫文本 = 片段(点, 20, 23)**
|
||||
|
||||
**结束 = 24**
|
||||
**结束 = 24**
|
||||
|
||||
1. `长度(点) != 结束 or 点[结束 - 1] != 90`
|
||||
`else`
|
||||
`if 长度(点) != 结束 or 点[结束 - 1] != 90`
|
||||
|
||||
*失败("必须以 Z 结尾")*
|
||||
`return 失败("必须以 Z 结尾")`
|
||||
|
||||
1. `not 是数字串(毫文本)`
|
||||
`else`
|
||||
`if not 是数字串(毫文本)`
|
||||
|
||||
*失败("毫秒必须是数字")*
|
||||
`return 失败("毫秒必须是数字")`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**毫 = 整数(毫文本)**
|
||||
|
||||
1. `年 < 1970 or 月 < 1 or 月 > 12 or 日 < 1 or 日 > 每月天数(年, 月)`
|
||||
`if 年 < 1970 or 月 < 1 or 月 > 12 or 日 < 1 or 日 > 每月天数(年, 月)`
|
||||
|
||||
*失败("日期超出范围")*
|
||||
`return 失败("日期超出范围")`
|
||||
|
||||
1. `时 < 0 or 时 > 23 or 分 < 0 or 分 > 59 or 秒 < 0 or 秒 > 59`
|
||||
`else`
|
||||
`if 时 < 0 or 时 > 23 or 分 < 0 or 分 > 59 or 秒 < 0 or 秒 > 59`
|
||||
|
||||
*失败("时间超出范围")*
|
||||
`return 失败("时间超出范围")`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**毫秒 = 日期序号(年, 月, 日) * 86400000 + 时 * 3600000 + 分 * 60000 + 秒 * 1000 + 毫**
|
||||
|
||||
*{ok: true, value: 毫秒}*
|
||||
`return {ok: true, value: 毫秒}`
|
||||
+14
-12
@@ -3,38 +3,40 @@ import:
|
||||
io: "./io.mq.md"
|
||||
---
|
||||
|
||||
## 演示函数
|
||||
## @exec 演示函数
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
### 公式
|
||||
### @knowledge 公式
|
||||
|
||||
$$a = 1$$
|
||||
|
||||
### 代码
|
||||
### @knowledge 代码
|
||||
|
||||
```text
|
||||
print(1)
|
||||
```
|
||||
|
||||
### @exec 主流程
|
||||
|
||||
**列表 = ["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]**
|
||||
|
||||
> io.写值(列表)
|
||||
> **io.写值(列表)**
|
||||
|
||||
> 打印(列表)
|
||||
> **打印(列表)**
|
||||
|
||||
**表格 = 表(["名称", "分数"], [["甲", 87], ["乙", 92]])**
|
||||
|
||||
> io.写值(表格)
|
||||
> **io.写值(表格)**
|
||||
|
||||
> 打印(表格)
|
||||
> **打印(表格)**
|
||||
|
||||
**特殊 = [ref("#公式"), ref("#代码"), ref("#演示函数")]**
|
||||
|
||||
> io.写值(特殊)
|
||||
> **io.写值(特殊)**
|
||||
|
||||
> 打印(特殊)
|
||||
> **打印(特殊)**
|
||||
|
||||
*None*
|
||||
`return None`
|
||||
+15
-10
@@ -1,25 +1,30 @@
|
||||
|
||||
# @exec env
|
||||
## 读取
|
||||
|
||||
`(名称)`
|
||||
`params(名称)`
|
||||
|
||||
读取一个显式授权的环境变量。名称是精确匹配,不支持 glob;未授权是
|
||||
`permission.denied`,未设置是 `env.not_found`,非 UTF-8 是
|
||||
`env.not_unicode`。
|
||||
permission.denied,未设置是 env.not_found,非 UTF-8 是
|
||||
env.not_unicode。
|
||||
|
||||
*resource.request("env.get", [名称])*
|
||||
`return resource.request("env.get", [名称])`
|
||||
|
||||
## 存在
|
||||
|
||||
`(名称)`
|
||||
`params(名称)`
|
||||
|
||||
**结果 = 读取(名称)**
|
||||
|
||||
1. `结果.ok`
|
||||
`if 结果.ok`
|
||||
|
||||
*{ok: true, value: true}*
|
||||
`return {ok: true, value: true}`
|
||||
|
||||
1. `结果.code == "env.not_found"`
|
||||
`else`
|
||||
`if 结果.code == "env.not_found"`
|
||||
|
||||
*{ok: true, value: false}*
|
||||
`return {ok: true, value: false}`
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`end`
|
||||
`return 结果`
|
||||
+173
-106
@@ -1,6 +1,8 @@
|
||||
|
||||
# @exec format
|
||||
## 字节长度
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -8,119 +10,156 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
**码点 = 点[下标]**
|
||||
|
||||
1. `码点 < 128`
|
||||
`if 码点 < 128`
|
||||
|
||||
**总字节 = 总字节 + 1**
|
||||
**总字节 = 总字节 + 1**
|
||||
|
||||
2. `码点 < 2048`
|
||||
`else`
|
||||
`if 码点 < 2048`
|
||||
|
||||
**总字节 = 总字节 + 2**
|
||||
**总字节 = 总字节 + 2**
|
||||
|
||||
3. `码点 < 65536`
|
||||
`else`
|
||||
`if 码点 < 65536`
|
||||
|
||||
**总字节 = 总字节 + 3**
|
||||
**总字节 = 总字节 + 3**
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**总字节 = 总字节 + 4**
|
||||
**总字节 = 总字节 + 4**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*总字节*
|
||||
`end`
|
||||
`return 总字节`
|
||||
|
||||
## 显示
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
按语言值语义格式化,用于与内置 `打印` 的输出对照。
|
||||
按语言值语义格式化,用于与内置 打印 的输出对照。
|
||||
覆盖 Unit/None/Bool/Int/Float/Text/List/Map/Table/Formula/Code/
|
||||
FunctionRef/PluginHandle/Memory/Resource。
|
||||
|
||||
**类别 = 类型(值)**
|
||||
|
||||
1. `类别 == "Unit"`
|
||||
`if 类别 == "Unit"`
|
||||
|
||||
*"Unit"*
|
||||
`return "Unit"`
|
||||
|
||||
2. `类别 == "None"`
|
||||
`else`
|
||||
`if 类别 == "None"`
|
||||
|
||||
*"None"*
|
||||
`return "None"`
|
||||
|
||||
3. `类别 == "Text"`
|
||||
`else`
|
||||
`if 类别 == "Text"`
|
||||
|
||||
*值*
|
||||
`return 值`
|
||||
|
||||
4. `类别 == "List"`
|
||||
`else`
|
||||
`if 类别 == "List"`
|
||||
|
||||
*列表显示(值)*
|
||||
`return 列表显示(值)`
|
||||
|
||||
5. `类别 == "Map"`
|
||||
`else`
|
||||
`if 类别 == "Map"`
|
||||
|
||||
*映射显示(值)*
|
||||
`return 映射显示(值)`
|
||||
|
||||
6. `类别 == "Table"`
|
||||
`else`
|
||||
`if 类别 == "Table"`
|
||||
|
||||
*表格显示(值)*
|
||||
`return 表格显示(值)`
|
||||
|
||||
7. `类别 == "Formula"`
|
||||
`else`
|
||||
`if 类别 == "Formula"`
|
||||
|
||||
*"Formula(" + 转义文本(值.latex) + ")"*
|
||||
`return "Formula(" + 转义文本(值.latex) + ")"`
|
||||
|
||||
8. `类别 == "Code"`
|
||||
`else`
|
||||
`if 类别 == "Code"`
|
||||
|
||||
*"Code(" + 转义文本(值.language) + ", " + 文本(字节长度(值.source)) + " bytes)"*
|
||||
`return "Code(" + 转义文本(值.language) + ", " + 文本(字节长度(值.source)) + " bytes)"`
|
||||
|
||||
9. `类别 == "FunctionRef"`
|
||||
`else`
|
||||
`if 类别 == "FunctionRef"`
|
||||
|
||||
*"FunctionRef(" + 值.module + "::" + 值.name + ")"*
|
||||
`return "FunctionRef(" + 值.module + "::" + 值.name + ")"`
|
||||
|
||||
10. `类别 == "PluginHandle"`
|
||||
`else`
|
||||
`if 类别 == "PluginHandle"`
|
||||
|
||||
*"PluginHandle(" + 值.plugin + "::" + 值.export + ")"*
|
||||
`return "PluginHandle(" + 值.plugin + "::" + 值.export + ")"`
|
||||
|
||||
11. `类别 == "Memory"`
|
||||
`else`
|
||||
`if 类别 == "Memory"`
|
||||
|
||||
*"Memory"*
|
||||
`return "Memory"`
|
||||
|
||||
12. `类别 == "Resource"`
|
||||
`else`
|
||||
`if 类别 == "Resource"`
|
||||
|
||||
*"Resource"*
|
||||
`return "Resource"`
|
||||
|
||||
13. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*文本(值)*
|
||||
`return 文本(值)`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 列表显示
|
||||
|
||||
`(列表)`
|
||||
`params(列表)`
|
||||
|
||||
**结果 = "["**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表)`
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + ", "**
|
||||
**结果 = 结果 + ", "**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 值显示(列表[下标])**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 值显示(列表[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果 + "]"*
|
||||
`end`
|
||||
`return 结果 + "]"`
|
||||
|
||||
## 映射显示
|
||||
|
||||
`(映射)`
|
||||
`params(映射)`
|
||||
|
||||
**键 = map.keys(映射)**
|
||||
|
||||
@@ -128,27 +167,31 @@ FunctionRef/PluginHandle/Memory/Resource。
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(键)`
|
||||
`while 下标 < 长度(键)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + ", "**
|
||||
**结果 = 结果 + ", "**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**当前键 = 键[下标]**
|
||||
`end`
|
||||
`end`
|
||||
**当前键 = 键[下标]**
|
||||
|
||||
**结果 = 结果 + 当前键 + ": " + 值显示(map.get(映射, 当前键))**
|
||||
**结果 = 结果 + 当前键 + ": " + 值显示(map.get(映射, 当前键))**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果 + "}"*
|
||||
`end`
|
||||
`return 结果 + "}"`
|
||||
|
||||
## 表格显示
|
||||
|
||||
`(表格)`
|
||||
`params(表格)`
|
||||
|
||||
**列 = table.columns(表格)**
|
||||
|
||||
@@ -156,77 +199,89 @@ FunctionRef/PluginHandle/Memory/Resource。
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
- `行号 < 长度(表格)`
|
||||
`while 行号 < 长度(表格)`
|
||||
|
||||
1. `行号 > 0`
|
||||
`if 行号 > 0`
|
||||
|
||||
**结果 = 结果 + "; "**
|
||||
**结果 = 结果 + "; "**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**行 = table.row(表格, 行号)**
|
||||
`end`
|
||||
`end`
|
||||
**行 = table.row(表格, 行号)**
|
||||
|
||||
**单元格 = []**
|
||||
**单元格 = []**
|
||||
|
||||
**列号 = 0**
|
||||
**列号 = 0**
|
||||
|
||||
- `列号 < 长度(行)`
|
||||
`while 列号 < 长度(行)`
|
||||
|
||||
**单元格 = list.append(单元格, 显示(行[列号]))**
|
||||
**单元格 = list.append(单元格, 显示(行[列号]))**
|
||||
|
||||
**列号 = 列号 + 1**
|
||||
**列号 = 列号 + 1**
|
||||
|
||||
**结果 = 结果 + 连接文本(单元格, " | ")**
|
||||
`end`
|
||||
**结果 = 结果 + 连接文本(单元格, " | ")**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
*结果 + "}"*
|
||||
`end`
|
||||
`return 结果 + "}"`
|
||||
|
||||
## 连接文本
|
||||
|
||||
`(列表, 分隔)`
|
||||
`params(列表, 分隔)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表)`
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
1. `下标 > 0`
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + 分隔**
|
||||
**结果 = 结果 + 分隔**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**结果 = 结果 + 列表[下标]**
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 列表[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 值显示
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
列表/映射/表格内部使用 repr 语义:Text 带引号并转义,其它值递归显示。
|
||||
|
||||
**类别 = 类型(值)**
|
||||
|
||||
1. `类别 == "Text"`
|
||||
`if 类别 == "Text"`
|
||||
|
||||
*转义文本(值)*
|
||||
`return 转义文本(值)`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*显示(值)*
|
||||
`return 显示(值)`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 转义文本
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -234,34 +289,46 @@ FunctionRef/PluginHandle/Memory/Resource。
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
**码点 = 点[下标]**
|
||||
|
||||
1. `码点 == 34`
|
||||
`if 码点 == 34`
|
||||
|
||||
**`结果 = 结果 + "\\\""`**
|
||||
**`结果 = 结果 + "\\\""`**
|
||||
|
||||
2. `码点 == 92`
|
||||
`else`
|
||||
`if 码点 == 92`
|
||||
|
||||
**`结果 = 结果 + "\\\\"`**
|
||||
**`结果 = 结果 + "\\\\"`**
|
||||
|
||||
3. `码点 == 10`
|
||||
`else`
|
||||
`if 码点 == 10`
|
||||
|
||||
**`结果 = 结果 + "\\n"`**
|
||||
**`结果 = 结果 + "\\n"`**
|
||||
|
||||
4. `码点 == 9`
|
||||
`else`
|
||||
`if 码点 == 9`
|
||||
|
||||
**`结果 = 结果 + "\\t"`**
|
||||
**`结果 = 结果 + "\\t"`**
|
||||
|
||||
5. `码点 == 13`
|
||||
`else`
|
||||
`if 码点 == 13`
|
||||
|
||||
**`结果 = 结果 + "\\r"`**
|
||||
**`结果 = 结果 + "\\r"`**
|
||||
|
||||
6. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(码点)**
|
||||
**结果 = 结果 + text.from_codepoint(码点)**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*`结果 + "\""`*
|
||||
`end`
|
||||
``return 结果 + "\""``
|
||||
+100
-69
@@ -3,12 +3,14 @@ import:
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec file
|
||||
|
||||
## 读文本
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
以 UTF-8 读取一个有界的项目文件。文件在打开时整文件载入,上限 8 MiB;
|
||||
结果使用可恢复 `Result` 形状。
|
||||
结果使用可恢复 Result 形状。
|
||||
|
||||
**流 = resource.open("file", 路径, ["read"])**
|
||||
|
||||
@@ -18,32 +20,40 @@ import:
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
1. `not 读取.ok`
|
||||
`if not 读取.ok`
|
||||
|
||||
*读取*
|
||||
`return 读取`
|
||||
|
||||
2. `not 关闭.ok`
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
*关闭*
|
||||
`return 关闭`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**文本 = utf8.解码(内存, 0, 读取.value.count)**
|
||||
**文本 = utf8.解码(内存, 0, 读取.value.count)**
|
||||
|
||||
1. `not 文本.ok`
|
||||
`if not 文本.ok`
|
||||
|
||||
*文本*
|
||||
`return 文本`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: 文本.value}*
|
||||
`return {ok: true, value: 文本.value}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 写文本
|
||||
|
||||
`(路径, 文本)`
|
||||
`params(路径, 文本)`
|
||||
|
||||
把文本按 UTF-8 写入项目文件。路径必须已经通过 `fs_write` 授权;
|
||||
文件只在 `resource.close` 成功时创建或覆盖,写入缓冲上限 8 MiB。
|
||||
把文本按 UTF-8 写入项目文件。路径必须已经通过 fs_write 授权;
|
||||
文件只在 resource.close 成功时创建或覆盖,写入缓冲上限 8 MiB。
|
||||
|
||||
**内存 = memory.new(128, 128)**
|
||||
|
||||
@@ -55,24 +65,29 @@ import:
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
1. `not 写入.ok`
|
||||
`if not 写入.ok`
|
||||
|
||||
*写入*
|
||||
`return 写入`
|
||||
|
||||
2. `not 关闭.ok`
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
*关闭*
|
||||
`return 关闭`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: {count: 写入.value.count}}*
|
||||
`return {ok: true, value: {count: 写入.value.count}}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 复制文件
|
||||
|
||||
`(源, 目标)`
|
||||
`params(源, 目标)`
|
||||
|
||||
按字节复制一个有界的项目文件。源读取和目标写入分别需要
|
||||
`fs_read`/`fs_write` 授权,结果值与 [`写文本`](#写文本) 相同。
|
||||
fs_read/fs_write 授权,结果值与 [写文本](#写文本) 相同。
|
||||
|
||||
**输入 = resource.open("file", 源, ["read"])**
|
||||
|
||||
@@ -82,125 +97,141 @@ import:
|
||||
|
||||
**关闭输入 = resource.close(输入)**
|
||||
|
||||
1. `not 读取.ok`
|
||||
`if not 读取.ok`
|
||||
|
||||
*读取*
|
||||
`return 读取`
|
||||
|
||||
2. `not 关闭输入.ok`
|
||||
`else`
|
||||
`if not 关闭输入.ok`
|
||||
|
||||
*关闭输入*
|
||||
`return 关闭输入`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**输出 = resource.open("file", 目标, ["write"])**
|
||||
**输出 = resource.open("file", 目标, ["write"])**
|
||||
|
||||
**写入 = resource.write(输出, 内存, 0, 读取.value.count)**
|
||||
**写入 = resource.write(输出, 内存, 0, 读取.value.count)**
|
||||
|
||||
**关闭输出 = resource.close(输出)**
|
||||
**关闭输出 = resource.close(输出)**
|
||||
|
||||
1. `not 写入.ok`
|
||||
`if not 写入.ok`
|
||||
|
||||
*写入*
|
||||
`return 写入`
|
||||
|
||||
2. `not 关闭输出.ok`
|
||||
`else`
|
||||
`if not 关闭输出.ok`
|
||||
|
||||
*关闭输出*
|
||||
`return 关闭输出`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: {count: 写入.value.count}}*
|
||||
`return {ok: true, value: {count: 写入.value.count}}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 存在
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
*resource.request("fs.exists", [路径])*
|
||||
`return resource.request("fs.exists", [路径])`
|
||||
|
||||
## 元数据
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
*resource.request("fs.metadata", [路径])*
|
||||
`return resource.request("fs.metadata", [路径])`
|
||||
|
||||
## 是文件
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**元数据 = resource.request("fs.metadata", [路径])**
|
||||
|
||||
1. `not 元数据.ok`
|
||||
`if not 元数据.ok`
|
||||
|
||||
*元数据*
|
||||
`return 元数据`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: 元数据.value.kind == "file"}*
|
||||
`return {ok: true, value: 元数据.value.kind == "file"}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 是目录
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**元数据 = resource.request("fs.metadata", [路径])**
|
||||
|
||||
1. `not 元数据.ok`
|
||||
`if not 元数据.ok`
|
||||
|
||||
*元数据*
|
||||
`return 元数据`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: 元数据.value.kind == "directory"}*
|
||||
`return {ok: true, value: 元数据.value.kind == "directory"}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 列出目录
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
*resource.request("fs.list", [路径])*
|
||||
`return resource.request("fs.list", [路径])`
|
||||
|
||||
## 创建目录
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
*resource.request("fs.mkdir", [路径])*
|
||||
`return resource.request("fs.mkdir", [路径])`
|
||||
|
||||
## 删除
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
删除一个文件或空目录。非空目录返回 `fs.not_empty`,不递归删除。
|
||||
删除一个文件或空目录。非空目录返回 fs.not_empty,不递归删除。
|
||||
|
||||
*resource.request("fs.remove", [路径])*
|
||||
`return resource.request("fs.remove", [路径])`
|
||||
|
||||
## 重命名
|
||||
|
||||
`(源, 目标)`
|
||||
`params(源, 目标)`
|
||||
|
||||
目标已存在时返回 `fs.exists`,不覆盖。
|
||||
目标已存在时返回 fs.exists,不覆盖。
|
||||
|
||||
*resource.request("fs.rename", [源, 目标])*
|
||||
`return resource.request("fs.rename", [源, 目标])`
|
||||
|
||||
## 追加文本
|
||||
|
||||
`(路径, 文本)`
|
||||
`params(路径, 文本)`
|
||||
|
||||
把文本追加到项目文件;文件不存在时创建。仍受 8 MiB 单次读取上限和
|
||||
`fs_write` 授权约束。
|
||||
fs_write 授权约束。
|
||||
|
||||
*resource.request("fs.append", [路径, 文本])*
|
||||
`return resource.request("fs.append", [路径, 文本])`
|
||||
|
||||
## 读取片段
|
||||
|
||||
`(路径, 偏移, 长度)`
|
||||
`params(路径, 偏移, 长度)`
|
||||
|
||||
从偏移处读取最多 `长度` 字节,按 UTF-8 解码后返回文本。偏移/长度必须
|
||||
从偏移处读取最多 长度 字节,按 UTF-8 解码后返回文本。偏移/长度必须
|
||||
是非负整数,长度上限 8 MiB。
|
||||
|
||||
*resource.request("fs.read_at", [路径, 偏移, 长度])*
|
||||
`return resource.request("fs.read_at", [路径, 偏移, 长度])`
|
||||
|
||||
## 遍历
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
递归列出目录下的普通文件,返回相对项目根的路径列表。跳过符号链接,
|
||||
深度上限 64,条目上限 4096。
|
||||
|
||||
*resource.request("fs.walk", [路径])*
|
||||
`return resource.request("fs.walk", [路径])`
|
||||
+12
-10
@@ -5,34 +5,36 @@ import:
|
||||
console: "./io/console.mq.md"
|
||||
---
|
||||
|
||||
# @exec io
|
||||
|
||||
## 写文本
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
*stream.写文本(文本)*
|
||||
`return stream.写文本(文本)`
|
||||
|
||||
## 写全部
|
||||
|
||||
`(流, 内存, 起点, 长度)`
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
*stream.写全部(流, 内存, 起点, 长度)*
|
||||
`return stream.写全部(流, 内存, 起点, 长度)`
|
||||
|
||||
## 写值
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
按语言值语义格式化后输出,并追加换行。
|
||||
|
||||
*stream.写文本(format.显示(值) + "\n")*
|
||||
`return stream.写文本(format.显示(值) + "\n")`
|
||||
|
||||
## 读取行
|
||||
|
||||
`()`
|
||||
`params()`
|
||||
|
||||
*console.读取行()*
|
||||
`return console.读取行()`
|
||||
|
||||
## 打印
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
*console.打印(值)*
|
||||
`return console.打印(值)`
|
||||
+73
-46
@@ -5,12 +5,14 @@ import:
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec console
|
||||
|
||||
## 读取行
|
||||
|
||||
`()`
|
||||
`params()`
|
||||
|
||||
从已授权的 `stdio/stdin` 资源读取一行。按有界块读取并增量解码 UTF-8;
|
||||
EOF 返回 `{ok:false, code:"io.eof"}`,无效 UTF-8 返回可恢复错误。
|
||||
从已授权的 stdio/stdin 资源读取一行。按有界块读取并增量解码 UTF-8;
|
||||
EOF 返回 {ok:false, code:"io.eof"},无效 UTF-8 返回可恢复错误。
|
||||
|
||||
**流 = resource.open("stdio", "stdin", ["read"])**
|
||||
|
||||
@@ -22,98 +24,123 @@ EOF 返回 `{ok:false, code:"io.eof"}`,无效 UTF-8 返回可恢复错误。
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `not 结束`
|
||||
`while not 结束`
|
||||
|
||||
**读取 = resource.read(流, 内存, 0, 1)**
|
||||
**读取 = resource.read(流, 内存, 0, 1)**
|
||||
|
||||
1. `not 读取.ok`
|
||||
`if not 读取.ok`
|
||||
|
||||
**结束 = true**
|
||||
**结束 = true**
|
||||
|
||||
**错误 = 读取.code**
|
||||
**错误 = 读取.code**
|
||||
|
||||
2. `读取.value.eof and 读取.value.count == 0`
|
||||
`else`
|
||||
`if 读取.value.eof and 读取.value.count == 0`
|
||||
|
||||
**结束 = true**
|
||||
**结束 = true**
|
||||
|
||||
3. `内存[0] == 10`
|
||||
`else`
|
||||
`if 内存[0] == 10`
|
||||
|
||||
**结束 = true**
|
||||
**结束 = true**
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**字节 = list.append(字节, 内存[0])**
|
||||
**字节 = list.append(字节, 内存[0])**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
1. `错误 != ""`
|
||||
`if 错误 != ""`
|
||||
|
||||
*{ok: false, code: 错误, message: "stdin read failed"}*
|
||||
`return {ok: false, code: 错误, message: "stdin read failed"}`
|
||||
|
||||
2. `not 关闭.ok`
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
*关闭*
|
||||
`return 关闭`
|
||||
|
||||
3. `长度(字节) == 0`
|
||||
`else`
|
||||
`if 长度(字节) == 0`
|
||||
|
||||
*{ok: false, code: "io.eof", message: "end of input"}*
|
||||
`return {ok: false, code: "io.eof", message: "end of input"}`
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**数据长度 = 长度(字节)**
|
||||
**数据长度 = 长度(字节)**
|
||||
|
||||
1. `数据长度 > 0 and 字节[数据长度 - 1] == 13`
|
||||
`if 数据长度 > 0 and 字节[数据长度 - 1] == 13`
|
||||
|
||||
**数据长度 = 数据长度 - 1**
|
||||
**数据长度 = 数据长度 - 1**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**页 = (数据长度 + 65535) // 65536**
|
||||
`end`
|
||||
`end`
|
||||
**页 = (数据长度 + 65535) // 65536**
|
||||
|
||||
**数据 = memory.new(页, 页)**
|
||||
**数据 = memory.new(页, 页)**
|
||||
|
||||
**下标 = 0**
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 数据长度`
|
||||
`while 下标 < 数据长度`
|
||||
|
||||
**`数据[下标] = 字节[下标]`**
|
||||
**`数据[下标] = 字节[下标]`**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
**解码 = utf8.解码(数据, 0, 数据长度)**
|
||||
`end`
|
||||
**解码 = utf8.解码(数据, 0, 数据长度)**
|
||||
|
||||
1. `not 解码.ok`
|
||||
`if not 解码.ok`
|
||||
|
||||
*解码*
|
||||
`return 解码`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: 解码.value}*
|
||||
`return {ok: true, value: 解码.value}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 打印
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
**结果 = stream.写文本(format.显示(值) + "\n")**
|
||||
|
||||
1. `not 结果.ok`
|
||||
`if not 结果.ok`
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: None}*
|
||||
`return {ok: true, value: None}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 写文本
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
*stream.写文本(文本)*
|
||||
`return stream.写文本(文本)`
|
||||
|
||||
## 写全部
|
||||
|
||||
`(流, 内存, 起点, 长度)`
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
*stream.写全部(流, 内存, 起点, 长度)*
|
||||
`return stream.写全部(流, 内存, 起点, 长度)`
|
||||
+55
-34
@@ -4,26 +4,31 @@ import:
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec stream
|
||||
|
||||
## 页数
|
||||
|
||||
`(字节)`
|
||||
`params(字节)`
|
||||
|
||||
**页 = (字节 + 65535) // 65536**
|
||||
|
||||
1. `页 == 0`
|
||||
`if 页 == 0`
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*页*
|
||||
`return 页`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 写全部
|
||||
|
||||
`(流, 内存, 起点, 长度)`
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
把 `长度` 字节从 `内存` 写到资源流。短写只返回实际数量,调用方继续;
|
||||
零进度返回 `io.write_zero`,不静默吞掉失败。
|
||||
把 长度 字节从 内存 写到资源流。短写只返回实际数量,调用方继续;
|
||||
零进度返回 io.write_zero,不静默吞掉失败。
|
||||
|
||||
**已写 = 0**
|
||||
|
||||
@@ -33,48 +38,59 @@ import:
|
||||
|
||||
**错误结果 = {ok: false, code: "io.write_zero", message: "resource.write made no progress"}**
|
||||
|
||||
- `已写 < 长度`
|
||||
`while 已写 < 长度`
|
||||
|
||||
**剩余 = 长度 - 已写**
|
||||
**剩余 = 长度 - 已写**
|
||||
|
||||
**本次 = resource.write(流, 内存, 起点 + 已写, 剩余)**
|
||||
**本次 = resource.write(流, 内存, 起点 + 已写, 剩余)**
|
||||
|
||||
1. `not 本次.ok`
|
||||
`if not 本次.ok`
|
||||
|
||||
**失败 = true**
|
||||
**失败 = true**
|
||||
|
||||
**错误结果 = 本次**
|
||||
**错误结果 = 本次**
|
||||
|
||||
**已写 = 长度**
|
||||
**已写 = 长度**
|
||||
|
||||
2. `本次.value.count == 0`
|
||||
`else`
|
||||
`if 本次.value.count == 0`
|
||||
|
||||
**失败 = true**
|
||||
**失败 = true**
|
||||
|
||||
**已写 = 长度**
|
||||
**已写 = 长度**
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**已写 = 已写 + 本次.value.count**
|
||||
**已写 = 已写 + 本次.value.count**
|
||||
|
||||
1. `失败`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 失败`
|
||||
|
||||
*错误结果*
|
||||
`return 错误结果`
|
||||
|
||||
2. `已写 < 长度`
|
||||
`else`
|
||||
`if 已写 < 长度`
|
||||
|
||||
*错误结果*
|
||||
`return 错误结果`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: {count: 长度}}*
|
||||
`return {ok: true, value: {count: 长度}}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 写文本
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
把文本编码为 UTF-8 并写入已授权的 stdout 资源流。内存按实际字节长度增长,
|
||||
写入循环检查 `{ok,count}`;只有全部字节写完并关闭成功才返回成功。
|
||||
写入循环检查 {ok,count};只有全部字节写完并关闭成功才返回成功。
|
||||
|
||||
**字节数 = format.字节长度(文本)**
|
||||
|
||||
@@ -88,14 +104,19 @@ import:
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
1. `not 写结果.ok`
|
||||
`if not 写结果.ok`
|
||||
|
||||
*写结果*
|
||||
`return 写结果`
|
||||
|
||||
2. `not 关闭.ok`
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
*关闭*
|
||||
`return 关闭`
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*{ok: true, value: {count: 长度}}*
|
||||
`return {ok: true, value: {count: 长度}}`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
+184
-126
@@ -3,117 +3,140 @@ import:
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec http
|
||||
|
||||
## 切片字节
|
||||
|
||||
`(字节, 起, 止)`
|
||||
`params(字节, 起, 止)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
**下标 = 起**
|
||||
|
||||
- `下标 < 止 and 下标 < 长度(字节)`
|
||||
`while 下标 < 止 and 下标 < 长度(字节)`
|
||||
|
||||
**结果 = list.append(结果, 字节[下标])**
|
||||
**结果 = list.append(结果, 字节[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 找子串
|
||||
|
||||
`(字节, 子, 起点)`
|
||||
`params(字节, 子, 起点)`
|
||||
|
||||
**结果 = 0 - 1**
|
||||
|
||||
**下标 = 起点**
|
||||
|
||||
- `下标 + 长度(子) <= 长度(字节) and 结果 < 0`
|
||||
`while 下标 + 长度(子) <= 长度(字节) and 结果 < 0`
|
||||
|
||||
**偏移 = 0**
|
||||
**偏移 = 0**
|
||||
|
||||
**匹配 = true**
|
||||
**匹配 = true**
|
||||
|
||||
- `偏移 < 长度(子) and 匹配`
|
||||
`while 偏移 < 长度(子) and 匹配`
|
||||
|
||||
1. `字节[下标 + 偏移] != 子[偏移]`
|
||||
`if 字节[下标 + 偏移] != 子[偏移]`
|
||||
|
||||
**匹配 = false**
|
||||
**匹配 = false**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**偏移 = 偏移 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**偏移 = 偏移 + 1**
|
||||
|
||||
1. `匹配`
|
||||
`end`
|
||||
`if 匹配`
|
||||
|
||||
**结果 = 下标**
|
||||
**结果 = 下标**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 找字符
|
||||
|
||||
`(字节, 值, 起点)`
|
||||
`params(字节, 值, 起点)`
|
||||
|
||||
**结果 = 0 - 1**
|
||||
|
||||
**下标 = 起点**
|
||||
|
||||
- `下标 < 长度(字节) and 结果 < 0`
|
||||
`while 下标 < 长度(字节) and 结果 < 0`
|
||||
|
||||
1. `字节[下标] == 值`
|
||||
`if 字节[下标] == 值`
|
||||
|
||||
**结果 = 下标**
|
||||
**结果 = 下标**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 十六进制值
|
||||
|
||||
`(字节)`
|
||||
`params(字节)`
|
||||
|
||||
**数值 = 0**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(字节)`
|
||||
`while 下标 < 长度(字节)`
|
||||
|
||||
**值 = 字节[下标]**
|
||||
**值 = 字节[下标]**
|
||||
|
||||
1. `值 >= 48 and 值 <= 57`
|
||||
`if 值 >= 48 and 值 <= 57`
|
||||
|
||||
**数值 = 数值 * 16 + 值 - 48**
|
||||
**数值 = 数值 * 16 + 值 - 48**
|
||||
|
||||
2. `值 >= 65 and 值 <= 70`
|
||||
`else`
|
||||
`if 值 >= 65 and 值 <= 70`
|
||||
|
||||
**数值 = 数值 * 16 + 值 - 55**
|
||||
**数值 = 数值 * 16 + 值 - 55**
|
||||
|
||||
3. `值 >= 97 and 值 <= 102`
|
||||
`else`
|
||||
`if 值 >= 97 and 值 <= 102`
|
||||
|
||||
**数值 = 数值 * 16 + 值 - 87**
|
||||
**数值 = 数值 * 16 + 值 - 87**
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*数值*
|
||||
`end`
|
||||
`return 数值`
|
||||
|
||||
## 文本字节
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
把 UTF-8 文本编码为字节列表,上限 8 MiB。
|
||||
|
||||
@@ -125,43 +148,46 @@ import:
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 字节数`
|
||||
`while 下标 < 字节数`
|
||||
|
||||
**结果 = list.append(结果, 内存[下标])**
|
||||
**结果 = list.append(结果, 内存[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 字节文本
|
||||
|
||||
`(字节)`
|
||||
`params(字节)`
|
||||
|
||||
把字节列表按 UTF-8 解码为文本,上限 8 MiB。
|
||||
|
||||
**长度值 = 长度(字节)**
|
||||
|
||||
1. `长度值 == 0`
|
||||
`if 长度值 == 0`
|
||||
|
||||
*{ok: true, value: ""}*
|
||||
`return {ok: true, value: ""}`
|
||||
|
||||
`end`
|
||||
**页 = (长度值 + 65535) // 65536**
|
||||
|
||||
**内存 = memory.new(页, 页)**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度值`
|
||||
`while 下标 < 长度值`
|
||||
|
||||
**内存[下标] = 字节[下标]**
|
||||
**内存[下标] = 字节[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*utf8.解码(内存, 0, 长度值)*
|
||||
`end`
|
||||
`return utf8.解码(内存, 0, 长度值)`
|
||||
|
||||
## 解码分块字节
|
||||
|
||||
`(体)`
|
||||
`params(体)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
@@ -169,51 +195,62 @@ import:
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `位置 < 长度(体) and 错误 == ""`
|
||||
`while 位置 < 长度(体) and 错误 == ""`
|
||||
|
||||
**行尾 = 找子串(体, [13, 10], 位置)**
|
||||
**行尾 = 找子串(体, [13, 10], 位置)**
|
||||
|
||||
1. `行尾 < 0`
|
||||
`if 行尾 < 0`
|
||||
|
||||
**错误 = "http.chunked"**
|
||||
**错误 = "http.chunked"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**大小 = 十六进制值(切片字节(体, 位置, 行尾))**
|
||||
**大小 = 十六进制值(切片字节(体, 位置, 行尾))**
|
||||
|
||||
1. `大小 == 0`
|
||||
`if 大小 == 0`
|
||||
|
||||
**位置 = 长度(体)**
|
||||
**位置 = 长度(体)**
|
||||
|
||||
2. `位置 + 大小 + 4 > 长度(体)`
|
||||
`else`
|
||||
`if 位置 + 大小 + 4 > 长度(体)`
|
||||
|
||||
**错误 = "http.chunked"**
|
||||
**错误 = "http.chunked"**
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = list.concat(结果, 切片字节(体, 行尾 + 2, 行尾 + 2 + 大小))**
|
||||
**结果 = list.concat(结果, 切片字节(体, 行尾 + 2, 行尾 + 2 + 大小))**
|
||||
|
||||
**位置 = 行尾 + 2 + 大小 + 2**
|
||||
**位置 = 行尾 + 2 + 大小 + 2**
|
||||
|
||||
1. `错误 != ""`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 错误 != ""`
|
||||
|
||||
*{ok: false, code: 错误, message: "分块长度无效"}*
|
||||
`return {ok: false, code: 错误, message: "分块长度无效"}`
|
||||
|
||||
*{ok: true, value: 结果}*
|
||||
`end`
|
||||
`return {ok: true, value: 结果}`
|
||||
|
||||
## 解析响应字节
|
||||
|
||||
`(字节)`
|
||||
`params(字节)`
|
||||
|
||||
解析 HTTP/1.1 响应字节。头部按 ASCII 解析,正文保持原始字节;chunked
|
||||
长度以字节计。成功返回 `{ok:true, value:{status, reason, headers, body}}`。
|
||||
长度以字节计。成功返回 {ok:true, value:{status, reason, headers, body}}。
|
||||
|
||||
**头部结束 = 找子串(字节, [13, 10, 13, 10], 0)**
|
||||
|
||||
1. `头部结束 < 0`
|
||||
`if 头部结束 < 0`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "缺少头部结束"}*
|
||||
`return {ok: false, code: "http.invalid", message: "缺少头部结束"}`
|
||||
|
||||
`end`
|
||||
**头部 = 切片字节(字节, 0, 头部结束)**
|
||||
|
||||
**体 = 切片字节(字节, 头部结束 + 4, 长度(字节))**
|
||||
@@ -224,123 +261,142 @@ import:
|
||||
|
||||
**下一行 = 找子串(头部, [13, 10], 0)**
|
||||
|
||||
- `下一行 >= 0`
|
||||
`while 下一行 >= 0`
|
||||
|
||||
**行列表 = list.append(行列表, 切片字节(头部, 行起, 下一行))**
|
||||
**行列表 = list.append(行列表, 切片字节(头部, 行起, 下一行))**
|
||||
|
||||
**行起 = 下一行 + 2**
|
||||
**行起 = 下一行 + 2**
|
||||
|
||||
**下一行 = 找子串(头部, [13, 10], 行起)**
|
||||
**下一行 = 找子串(头部, [13, 10], 行起)**
|
||||
|
||||
`end`
|
||||
**行列表 = list.append(行列表, 切片字节(头部, 行起, 长度(头部)))**
|
||||
|
||||
1. `长度(行列表) == 0`
|
||||
`if 长度(行列表) == 0`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "缺少状态行"}*
|
||||
`return {ok: false, code: "http.invalid", message: "缺少状态行"}`
|
||||
|
||||
`end`
|
||||
**状态行 = 字节文本(行列表[0])**
|
||||
|
||||
1. `not 状态行.ok`
|
||||
`if not 状态行.ok`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "状态行不是 ASCII"}*
|
||||
`return {ok: false, code: "http.invalid", message: "状态行不是 ASCII"}`
|
||||
|
||||
`end`
|
||||
**状态字节 = 行列表[0]**
|
||||
|
||||
**第一空格 = 找字符(状态字节, 32, 0)**
|
||||
|
||||
**第二空格 = 找字符(状态字节, 32, 第一空格 + 1)**
|
||||
|
||||
1. `第一空格 < 0 or 第二空格 < 0`
|
||||
`if 第一空格 < 0 or 第二空格 < 0`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "状态行格式无效"}*
|
||||
`return {ok: false, code: "http.invalid", message: "状态行格式无效"}`
|
||||
|
||||
`end`
|
||||
**状态文本 = 字节文本(切片字节(状态字节, 第一空格 + 1, 第二空格))**
|
||||
|
||||
1. `not 状态文本.ok`
|
||||
`if not 状态文本.ok`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "状态码不是 ASCII"}*
|
||||
`return {ok: false, code: "http.invalid", message: "状态码不是 ASCII"}`
|
||||
|
||||
`end`
|
||||
**状态 = 整数(状态文本.value)**
|
||||
|
||||
**原因 = 字节文本(切片字节(状态字节, 第二空格 + 1, 长度(状态字节)))**
|
||||
|
||||
1. `not 原因.ok`
|
||||
`if not 原因.ok`
|
||||
|
||||
*{ok: false, code: "http.invalid", message: "原因短语不是 ASCII"}*
|
||||
`return {ok: false, code: "http.invalid", message: "原因短语不是 ASCII"}`
|
||||
|
||||
`end`
|
||||
**头 = {}**
|
||||
|
||||
**行号 = 1**
|
||||
|
||||
- `行号 < 长度(行列表)`
|
||||
`while 行号 < 长度(行列表)`
|
||||
|
||||
**行 = 行列表[行号]**
|
||||
**行 = 行列表[行号]**
|
||||
|
||||
**冒号 = 找字符(行, 58, 0)**
|
||||
**冒号 = 找字符(行, 58, 0)**
|
||||
|
||||
1. `冒号 >= 0`
|
||||
`if 冒号 >= 0`
|
||||
|
||||
**名 = 字节文本(切片字节(行, 0, 冒号))**
|
||||
**名 = 字节文本(切片字节(行, 0, 冒号))**
|
||||
|
||||
**值 = 字节文本(切片字节(行, 冒号 + 2, 长度(行)))**
|
||||
**值 = 字节文本(切片字节(行, 冒号 + 2, 长度(行)))**
|
||||
|
||||
1. `名.ok and 值.ok`
|
||||
`if 名.ok and 值.ok`
|
||||
|
||||
**头 = map.set(头, 名.value, 值.value)**
|
||||
**头 = map.set(头, 名.value, 值.value)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
2. `true`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
`end`
|
||||
**传输 = map.get(头, "Transfer-Encoding")**
|
||||
|
||||
**解码后 = 体**
|
||||
|
||||
1. `传输 == "chunked"`
|
||||
`if 传输 == "chunked"`
|
||||
|
||||
**分块 = 解码分块字节(体)**
|
||||
**分块 = 解码分块字节(体)**
|
||||
|
||||
1. `not 分块.ok`
|
||||
`if not 分块.ok`
|
||||
|
||||
*分块*
|
||||
`return 分块`
|
||||
|
||||
**解码后 = 分块.value**
|
||||
`end`
|
||||
**解码后 = 分块.value**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
*{ok: true, value: {status: 状态, reason: 原因.value, headers: 头, body: 解码后}}*
|
||||
`end`
|
||||
`end`
|
||||
`return {ok: true, value: {status: 状态, reason: 原因.value, headers: 头, body: 解码后}}`
|
||||
|
||||
## 解析响应
|
||||
|
||||
`(文本)`
|
||||
`params(文本)`
|
||||
|
||||
兼容文本 API:按字节解析后,把正文按 UTF-8 解码。
|
||||
|
||||
**响应 = 解析响应字节(文本字节(文本))**
|
||||
|
||||
1. `not 响应.ok`
|
||||
`if not 响应.ok`
|
||||
|
||||
*{状态: 0, 原因: "", 头: {}, 体: ""}*
|
||||
`return {状态: 0, 原因: "", 头: {}, 体: ""}`
|
||||
|
||||
`end`
|
||||
**正文 = 字节文本(响应.value.body)**
|
||||
|
||||
1. `not 正文.ok`
|
||||
`if not 正文.ok`
|
||||
|
||||
*{状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: ""}*
|
||||
`return {状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: ""}`
|
||||
|
||||
*{状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: 正文.value}*
|
||||
`end`
|
||||
`return {状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: 正文.value}`
|
||||
|
||||
## 构建请求字节
|
||||
|
||||
`(方法, 路径, 头列表, 体字节)`
|
||||
`params(方法, 路径, 头列表, 体字节)`
|
||||
|
||||
构建 HTTP/1.1 请求字节。方法、路径、头名/值按 UTF-8 编码;正文使用
|
||||
传入的字节列表。
|
||||
@@ -349,21 +405,22 @@ import:
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(头列表)`
|
||||
`while 下标 < 长度(头列表)`
|
||||
|
||||
**头 = 头列表[下标]**
|
||||
**头 = 头列表[下标]**
|
||||
|
||||
**结果 = list.concat(结果, 文本字节(文本(头[0]) + ": " + 文本(头[1]) + "\r\n"))**
|
||||
**结果 = list.concat(结果, 文本字节(文本(头[0]) + ": " + 文本(头[1]) + "\r\n"))**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
**结果 = list.concat(结果, [13, 10])**
|
||||
|
||||
*list.concat(结果, 体字节)*
|
||||
`return list.concat(结果, 体字节)`
|
||||
|
||||
## 构建请求
|
||||
|
||||
`(方法, 路径, 头列表, 体文本)`
|
||||
`params(方法, 路径, 头列表, 体文本)`
|
||||
|
||||
兼容文本 API,正文按 UTF-8 编码。
|
||||
|
||||
@@ -371,8 +428,9 @@ import:
|
||||
|
||||
**文本结果 = 字节文本(请求)**
|
||||
|
||||
1. `not 文本结果.ok`
|
||||
`if not 文本结果.ok`
|
||||
|
||||
*""*
|
||||
`return ""`
|
||||
|
||||
*文本结果.value*
|
||||
`end`
|
||||
`return 文本结果.value`
|
||||
+95
-64
@@ -1,22 +1,27 @@
|
||||
|
||||
# @exec path
|
||||
## 是否绝对
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**点 = text.codepoints(路径)**
|
||||
|
||||
1. `长度(点) == 0`
|
||||
`if 长度(点) == 0`
|
||||
|
||||
*false*
|
||||
`return false`
|
||||
|
||||
2. `点[0] == 47`
|
||||
`else`
|
||||
`if 点[0] == 47`
|
||||
|
||||
*true*
|
||||
`return true`
|
||||
|
||||
*false*
|
||||
`end`
|
||||
`end`
|
||||
`return false`
|
||||
|
||||
## 分割
|
||||
|
||||
`(文本, 分隔码点)`
|
||||
`params(文本, 分隔码点)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -26,65 +31,76 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
1. `点[下标] == 分隔码点`
|
||||
`if 点[下标] == 分隔码点`
|
||||
|
||||
**结果 = list.append(结果, 当前)**
|
||||
**结果 = list.append(结果, 当前)**
|
||||
|
||||
**当前 = ""**
|
||||
**当前 = ""**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**当前 = 当前 + text.from_codepoint(点[下标])**
|
||||
**当前 = 当前 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*list.append(结果, 当前)*
|
||||
`end`
|
||||
`return list.append(结果, 当前)`
|
||||
|
||||
## 连接
|
||||
|
||||
`(片段列表)`
|
||||
`params(片段列表)`
|
||||
|
||||
空片段被跳过,片段之间只插入一个 `/`。
|
||||
空片段被跳过,片段之间只插入一个 /。
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(片段列表)`
|
||||
`while 下标 < 长度(片段列表)`
|
||||
|
||||
**片段 = 文本(片段列表[下标])**
|
||||
**片段 = 文本(片段列表[下标])**
|
||||
|
||||
1. `片段 != ""`
|
||||
`if 片段 != ""`
|
||||
|
||||
1. `结果 == ""`
|
||||
`if 结果 == ""`
|
||||
|
||||
**结果 = 片段**
|
||||
**结果 = 片段**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = 结果 + "/" + 片段**
|
||||
**结果 = 结果 + "/" + 片段**
|
||||
|
||||
2. `true`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 文件名
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**片段 = 分割(路径, 47)**
|
||||
|
||||
*片段[长度(片段) - 1]*
|
||||
`return 片段[长度(片段) - 1]`
|
||||
|
||||
## 目录名
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**片段 = 分割(路径, 47)**
|
||||
|
||||
@@ -92,50 +108,53 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(片段) - 1`
|
||||
`while 下标 < 长度(片段) - 1`
|
||||
|
||||
**结果 = list.append(结果, 片段[下标])**
|
||||
**结果 = list.append(结果, 片段[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*连接(结果)*
|
||||
`end`
|
||||
`return 连接(结果)`
|
||||
|
||||
## 扩展名
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
**名字 = 文件名(路径)**
|
||||
|
||||
**点列表 = 分割(名字, 46)**
|
||||
|
||||
1. `长度(点列表) <= 1`
|
||||
`if 长度(点列表) <= 1`
|
||||
|
||||
*""*
|
||||
`return ""`
|
||||
|
||||
*点列表[长度(点列表) - 1]*
|
||||
`end`
|
||||
`return 点列表[长度(点列表) - 1]`
|
||||
|
||||
## 去尾
|
||||
|
||||
`(列表)`
|
||||
`params(列表)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表) - 1`
|
||||
`while 下标 < 长度(列表) - 1`
|
||||
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 规范
|
||||
|
||||
`(路径)`
|
||||
`params(路径)`
|
||||
|
||||
词法规范化:折叠 `.`、空片段和重复 `/`,用 `..` 消去前一片段;
|
||||
绝对路径保留前导 `/`。不访问文件系统。
|
||||
词法规范化:折叠 .、空片段和重复 /,用 .. 消去前一片段;
|
||||
绝对路径保留前导 /。不访问文件系统。
|
||||
|
||||
**片段 = 分割(路径, 47)**
|
||||
|
||||
@@ -145,36 +164,48 @@
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(片段)`
|
||||
`while 下标 < 长度(片段)`
|
||||
|
||||
**段 = 片段[下标]**
|
||||
**段 = 片段[下标]**
|
||||
|
||||
1. `段 == "" or 段 == "."`
|
||||
`if 段 == "" or 段 == "."`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
2. `段 == ".."`
|
||||
`else`
|
||||
`if 段 == ".."`
|
||||
|
||||
1. `长度(栈) > 0 and 栈[长度(栈) - 1] != ".."`
|
||||
`if 长度(栈) > 0 and 栈[长度(栈) - 1] != ".."`
|
||||
|
||||
**栈 = 去尾(栈)**
|
||||
**栈 = 去尾(栈)**
|
||||
|
||||
2. `not 绝对`
|
||||
`else`
|
||||
`if not 绝对`
|
||||
|
||||
**栈 = list.append(栈, 段)**
|
||||
**栈 = list.append(栈, 段)**
|
||||
|
||||
3. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略绝对根 = 0**
|
||||
**忽略绝对根 = 0**
|
||||
|
||||
3. `true`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**栈 = list.append(栈, 段)**
|
||||
**栈 = list.append(栈, 段)**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
1. `绝对`
|
||||
`end`
|
||||
`if 绝对`
|
||||
|
||||
*"/" + 连接(栈)*
|
||||
`return "/" + 连接(栈)`
|
||||
|
||||
*连接(栈)*
|
||||
`end`
|
||||
`return 连接(栈)`
|
||||
@@ -1,10 +1,12 @@
|
||||
|
||||
# @exec process
|
||||
## 运行
|
||||
|
||||
`(程序, 参数列表)`
|
||||
`params(程序, 参数列表)`
|
||||
|
||||
在项目模式下运行一个显式授权的可执行文件。程序路径必须与
|
||||
`--allow-process PROGRAM` 精确匹配;不经过 shell,清空环境变量,
|
||||
--allow-process PROGRAM 精确匹配;不经过 shell,清空环境变量,
|
||||
工作目录是项目根,stdin 为空。5 秒超时、1 MiB stdout/stderr 上限,
|
||||
结果形状为 `{status, stdout, stderr}`。
|
||||
结果形状为 {status, stdout, stderr}。
|
||||
|
||||
*resource.request("process.run", [程序, 参数列表])*
|
||||
`return resource.request("process.run", [程序, 参数列表])`
|
||||
+19
-14
@@ -1,37 +1,42 @@
|
||||
|
||||
# @exec random
|
||||
## 字节
|
||||
|
||||
`(数量)`
|
||||
`params(数量)`
|
||||
|
||||
读取 `数量` 个 OS 熵字节,返回 `List<Int>`(每个 0–255)。仅项目模式,
|
||||
需要显式 `--allow-random`;`pure`/`strict` 拒绝。
|
||||
读取 数量 个 OS 熵字节,返回 List<Int>(每个 0–255)。仅项目模式,
|
||||
需要显式 --allow-random;pure/strict 拒绝。
|
||||
|
||||
*resource.request("random.bytes", [数量])*
|
||||
`return resource.request("random.bytes", [数量])`
|
||||
|
||||
## 整数
|
||||
|
||||
`(上限)`
|
||||
`params(上限)`
|
||||
|
||||
返回 `0 <= 值 < 上限` 的整数。`上限` 必须大于 0;使用 8 个熵字节
|
||||
返回 0 <= 值 < 上限 的整数。上限 必须大于 0;使用 8 个熵字节
|
||||
组合后取模(无偏拒绝采样尚未实现)。
|
||||
|
||||
1. `上限 <= 0`
|
||||
`if 上限 <= 0`
|
||||
|
||||
*{ok: false, code: "random.invalid", message: "上限必须大于 0"}*
|
||||
`return {ok: false, code: "random.invalid", message: "上限必须大于 0"}`
|
||||
|
||||
`end`
|
||||
**字节结果 = 字节(8)**
|
||||
|
||||
1. `not 字节结果.ok`
|
||||
`if not 字节结果.ok`
|
||||
|
||||
*字节结果*
|
||||
`return 字节结果`
|
||||
|
||||
`end`
|
||||
**值 = 0**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 8`
|
||||
`while 下标 < 8`
|
||||
|
||||
**值 = 值 * 256 + 字节结果.value[下标]**
|
||||
**值 = 值 * 256 + 字节结果.value[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*{ok: true, value: 值 % 上限}*
|
||||
`end`
|
||||
`return {ok: true, value: 值 % 上限}`
|
||||
+264
-181
@@ -1,224 +1,260 @@
|
||||
|
||||
# @exec regex
|
||||
## 成功
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
*{ok: true, value: 值}*
|
||||
`return {ok: true, value: 值}`
|
||||
|
||||
## 失败
|
||||
|
||||
`(代码, 消息)`
|
||||
`params(代码, 消息)`
|
||||
|
||||
*{ok: false, code: 代码, message: 消息}*
|
||||
`return {ok: false, code: 代码, message: 消息}`
|
||||
|
||||
## 包含
|
||||
|
||||
`(列表, 值)`
|
||||
`params(列表, 值)`
|
||||
|
||||
**结果 = false**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表) and not 结果`
|
||||
`while 下标 < 长度(列表) and not 结果`
|
||||
|
||||
1. `列表[下标] == 值`
|
||||
`if 列表[下标] == 值`
|
||||
|
||||
**结果 = true**
|
||||
**结果 = true**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 去头
|
||||
|
||||
`(列表)`
|
||||
`params(列表)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
**下标 = 1**
|
||||
|
||||
- `下标 < 长度(列表)`
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 设置最后
|
||||
|
||||
`(列表, 值)`
|
||||
`params(列表, 值)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(列表)`
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
1. `下标 + 1 == 长度(列表)`
|
||||
`if 下标 + 1 == 长度(列表)`
|
||||
|
||||
**结果 = list.append(结果, 值)**
|
||||
**结果 = list.append(结果, 值)**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
**结果 = list.append(结果, 列表[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 片段
|
||||
|
||||
`(点, 起点, 终点)`
|
||||
`params(点, 起点, 终点)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 起点**
|
||||
|
||||
- `下标 < 终点`
|
||||
`while 下标 < 终点`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 是数字
|
||||
|
||||
`(码点)`
|
||||
`params(码点)`
|
||||
|
||||
*码点 >= 48 and 码点 <= 57*
|
||||
`return 码点 >= 48 and 码点 <= 57`
|
||||
|
||||
## 字面令牌
|
||||
|
||||
`(码点)`
|
||||
`params(码点)`
|
||||
|
||||
包含数量词,默认恰好一次。
|
||||
|
||||
*{kind: "literal", value: 码点, neg: false, min: 1, max: 1}*
|
||||
`return {kind: "literal", value: 码点, neg: false, min: 1, max: 1}`
|
||||
|
||||
## 任意令牌
|
||||
|
||||
`()`
|
||||
`params()`
|
||||
|
||||
*{kind: "any", value: 0, neg: false, min: 1, max: 1}*
|
||||
`return {kind: "any", value: 0, neg: false, min: 1, max: 1}`
|
||||
|
||||
## 类令牌
|
||||
|
||||
`(集合, 否定)`
|
||||
`params(集合, 否定)`
|
||||
|
||||
*{kind: "class", value: 集合, neg: 否定, min: 1, max: 1}*
|
||||
`return {kind: "class", value: 集合, neg: 否定, min: 1, max: 1}`
|
||||
|
||||
## 锚点令牌
|
||||
|
||||
`(方向)`
|
||||
`params(方向)`
|
||||
|
||||
*{kind: "anchor", value: 方向, neg: false, min: 1, max: 1}*
|
||||
`return {kind: "anchor", value: 方向, neg: false, min: 1, max: 1}`
|
||||
|
||||
## 设置量词
|
||||
|
||||
`(令牌, 码点)`
|
||||
`params(令牌, 码点)`
|
||||
|
||||
1. `码点 == 42`
|
||||
`if 码点 == 42`
|
||||
|
||||
*{kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: -1}*
|
||||
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: -1}`
|
||||
|
||||
2. `码点 == 43`
|
||||
`else`
|
||||
`if 码点 == 43`
|
||||
|
||||
*{kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 1, max: -1}*
|
||||
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 1, max: -1}`
|
||||
|
||||
*{kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: 1}*
|
||||
`end`
|
||||
`end`
|
||||
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: 1}`
|
||||
|
||||
## 编译类
|
||||
|
||||
`(点, 位置)`
|
||||
`params(点, 位置)`
|
||||
|
||||
**当前 = 位置 + 1**
|
||||
|
||||
**否定 = false**
|
||||
|
||||
1. `当前 < 长度(点) and 点[当前] == 94`
|
||||
`if 当前 < 长度(点) and 点[当前] == 94`
|
||||
|
||||
**否定 = true**
|
||||
**否定 = true**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略否定 = 0**
|
||||
**忽略否定 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**集合 = []**
|
||||
|
||||
**完成 = false**
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `当前 < 长度(点) and not 完成 and 错误 == ""`
|
||||
`while 当前 < 长度(点) and not 完成 and 错误 == ""`
|
||||
|
||||
**码点 = 点[当前]**
|
||||
**码点 = 点[当前]**
|
||||
|
||||
1. `码点 == 93`
|
||||
`if 码点 == 93`
|
||||
|
||||
**完成 = true**
|
||||
**完成 = true**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
2. `码点 == 92`
|
||||
`else`
|
||||
`if 码点 == 92`
|
||||
|
||||
1. `当前 + 1 >= 长度(点)`
|
||||
`if 当前 + 1 >= 长度(点)`
|
||||
|
||||
**错误 = "regex.invalid"**
|
||||
**错误 = "regex.invalid"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**集合 = list.append(集合, 点[当前 + 1])**
|
||||
**集合 = list.append(集合, 点[当前 + 1])**
|
||||
|
||||
**当前 = 当前 + 2**
|
||||
**当前 = 当前 + 2**
|
||||
|
||||
3. `当前 + 2 < 长度(点) and 点[当前 + 1] == 45 and 点[当前 + 2] != 93`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 当前 + 2 < 长度(点) and 点[当前 + 1] == 45 and 点[当前 + 2] != 93`
|
||||
|
||||
**开始 = 码点**
|
||||
**开始 = 码点**
|
||||
|
||||
**结束 = 点[当前 + 2]**
|
||||
**结束 = 点[当前 + 2]**
|
||||
|
||||
1. `开始 > 结束`
|
||||
`if 开始 > 结束`
|
||||
|
||||
**错误 = "regex.invalid"**
|
||||
**错误 = "regex.invalid"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**值 = 开始**
|
||||
**值 = 开始**
|
||||
|
||||
- `值 <= 结束`
|
||||
`while 值 <= 结束`
|
||||
|
||||
**集合 = list.append(集合, 值)**
|
||||
**集合 = list.append(集合, 值)**
|
||||
|
||||
**值 = 值 + 1**
|
||||
**值 = 值 + 1**
|
||||
|
||||
**当前 = 当前 + 3**
|
||||
`end`
|
||||
**当前 = 当前 + 3**
|
||||
|
||||
4. `true`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**集合 = list.append(集合, 码点)**
|
||||
**集合 = list.append(集合, 码点)**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
1. `not 完成`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if not 完成`
|
||||
|
||||
*失败("regex.invalid", "字符类未闭合")*
|
||||
`return 失败("regex.invalid", "字符类未闭合")`
|
||||
|
||||
1. `错误 != ""`
|
||||
`else`
|
||||
`if 错误 != ""`
|
||||
|
||||
*失败(错误, "字符类范围无效")*
|
||||
`return 失败(错误, "字符类范围无效")`
|
||||
|
||||
*成功({set: 集合, neg: 否定, next: 当前})*
|
||||
`end`
|
||||
`end`
|
||||
`return 成功({set: 集合, neg: 否定, next: 当前})`
|
||||
|
||||
## 编译
|
||||
|
||||
`(点, 位置)`
|
||||
`params(点, 位置)`
|
||||
|
||||
**令牌表 = []**
|
||||
|
||||
@@ -228,189 +264,232 @@
|
||||
|
||||
**代码 = ""**
|
||||
|
||||
- `当前 < 长度(点) and 错误 == ""`
|
||||
`while 当前 < 长度(点) and 错误 == ""`
|
||||
|
||||
**码点 = 点[当前]**
|
||||
**码点 = 点[当前]**
|
||||
|
||||
1. `码点 == 94`
|
||||
`if 码点 == 94`
|
||||
|
||||
**令牌表 = list.append(令牌表, 锚点令牌("start"))**
|
||||
**令牌表 = list.append(令牌表, 锚点令牌("start"))**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
2. `码点 == 36`
|
||||
`else`
|
||||
`if 码点 == 36`
|
||||
|
||||
**令牌表 = list.append(令牌表, 锚点令牌("end"))**
|
||||
**令牌表 = list.append(令牌表, 锚点令牌("end"))**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
3. `码点 == 91`
|
||||
`else`
|
||||
`if 码点 == 91`
|
||||
|
||||
**类结果 = 编译类(点, 当前)**
|
||||
**类结果 = 编译类(点, 当前)**
|
||||
|
||||
1. `not 类结果.ok`
|
||||
`if not 类结果.ok`
|
||||
|
||||
**错误 = 类结果.code**
|
||||
**错误 = 类结果.code**
|
||||
|
||||
**代码 = 类结果.message**
|
||||
**代码 = 类结果.message**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**令牌表 = list.append(令牌表, 类令牌(类结果.value.set, 类结果.value.neg))**
|
||||
**令牌表 = list.append(令牌表, 类令牌(类结果.value.set, 类结果.value.neg))**
|
||||
|
||||
**当前 = 类结果.value.next**
|
||||
**当前 = 类结果.value.next**
|
||||
|
||||
4. `码点 == 92`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 码点 == 92`
|
||||
|
||||
1. `当前 + 1 >= 长度(点)`
|
||||
`if 当前 + 1 >= 长度(点)`
|
||||
|
||||
**错误 = "regex.invalid"**
|
||||
**错误 = "regex.invalid"**
|
||||
|
||||
**代码 = "转义缺少字符"**
|
||||
**代码 = "转义缺少字符"**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**令牌表 = list.append(令牌表, 字面令牌(点[当前 + 1]))**
|
||||
**令牌表 = list.append(令牌表, 字面令牌(点[当前 + 1]))**
|
||||
|
||||
**当前 = 当前 + 2**
|
||||
**当前 = 当前 + 2**
|
||||
|
||||
5. `码点 == 46`
|
||||
`end`
|
||||
`end`
|
||||
`else`
|
||||
`if 码点 == 46`
|
||||
|
||||
**令牌表 = list.append(令牌表, 任意令牌())**
|
||||
**令牌表 = list.append(令牌表, 任意令牌())**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
6. `码点 == 40 or 码点 == 41 or 码点 == 124`
|
||||
`else`
|
||||
`if 码点 == 40 or 码点 == 41 or 码点 == 124`
|
||||
|
||||
**错误 = "regex.unsupported"**
|
||||
**错误 = "regex.unsupported"**
|
||||
|
||||
**代码 = "不支持分组或选择"**
|
||||
**代码 = "不支持分组或选择"**
|
||||
|
||||
7. `码点 == 42 or 码点 == 43 or 码点 == 63`
|
||||
`else`
|
||||
`if 码点 == 42 or 码点 == 43 or 码点 == 63`
|
||||
|
||||
**错误 = "regex.invalid"**
|
||||
**错误 = "regex.invalid"**
|
||||
|
||||
**代码 = "量词没有前一项"**
|
||||
**代码 = "量词没有前一项"**
|
||||
|
||||
8. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**令牌表 = list.append(令牌表, 字面令牌(码点))**
|
||||
**令牌表 = list.append(令牌表, 字面令牌(码点))**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
- `错误 == "" and 当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`while 错误 == "" and 当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
|
||||
|
||||
**令牌表 = 设置最后(令牌表, 设置量词(令牌表[长度(令牌表) - 1], 点[当前]))**
|
||||
**令牌表 = 设置最后(令牌表, 设置量词(令牌表[长度(令牌表) - 1], 点[当前]))**
|
||||
|
||||
**当前 = 当前 + 1**
|
||||
**当前 = 当前 + 1**
|
||||
|
||||
- `当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
|
||||
`while 当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
|
||||
|
||||
**错误 = "regex.invalid"**
|
||||
**错误 = "regex.invalid"**
|
||||
|
||||
**代码 = "连续量词无效"**
|
||||
**代码 = "连续量词无效"**
|
||||
|
||||
1. `错误 != ""`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 错误 != ""`
|
||||
|
||||
*失败(错误, 代码)*
|
||||
`return 失败(错误, 代码)`
|
||||
|
||||
*成功(令牌表)*
|
||||
`end`
|
||||
`return 成功(令牌表)`
|
||||
|
||||
## 单字符匹配
|
||||
|
||||
`(令牌, 码点)`
|
||||
`params(令牌, 码点)`
|
||||
|
||||
**类别 = 令牌.kind**
|
||||
|
||||
1. `类别 == "any"`
|
||||
`if 类别 == "any"`
|
||||
|
||||
*true*
|
||||
`return true`
|
||||
|
||||
2. `类别 == "literal"`
|
||||
`else`
|
||||
`if 类别 == "literal"`
|
||||
|
||||
*令牌.value == 码点*
|
||||
`return 令牌.value == 码点`
|
||||
|
||||
3. `类别 == "class"`
|
||||
`else`
|
||||
`if 类别 == "class"`
|
||||
|
||||
*包含(令牌.value, 码点) != 令牌.neg*
|
||||
`return 包含(令牌.value, 码点) != 令牌.neg`
|
||||
|
||||
*false*
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`return false`
|
||||
|
||||
## 尝试匹配
|
||||
|
||||
`(令牌, 下标, 当前, 点, 位置, 次数, 要求结束)`
|
||||
`params(令牌, 下标, 当前, 点, 位置, 次数, 要求结束)`
|
||||
|
||||
**下限 = 当前.min**
|
||||
|
||||
**上限 = 当前.max**
|
||||
|
||||
1. `次数 >= 下限 and 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
|
||||
`if 次数 >= 下限 and 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
|
||||
|
||||
*true*
|
||||
`return true`
|
||||
|
||||
1. `上限 >= 0 and 次数 >= 上限`
|
||||
`else`
|
||||
`if 上限 >= 0 and 次数 >= 上限`
|
||||
|
||||
*false*
|
||||
`return false`
|
||||
|
||||
1. `位置 < 长度(点) and 单字符匹配(当前, 点[位置])`
|
||||
`else`
|
||||
`if 位置 < 长度(点) and 单字符匹配(当前, 点[位置])`
|
||||
|
||||
*尝试匹配(令牌, 下标, 当前, 点, 位置 + 1, 次数 + 1, 要求结束)*
|
||||
`return 尝试匹配(令牌, 下标, 当前, 点, 位置 + 1, 次数 + 1, 要求结束)`
|
||||
|
||||
*false*
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`return false`
|
||||
|
||||
## 匹配序列
|
||||
|
||||
`(令牌, 下标, 点, 位置, 要求结束)`
|
||||
`params(令牌, 下标, 点, 位置, 要求结束)`
|
||||
|
||||
1. `下标 >= 长度(令牌)`
|
||||
`if 下标 >= 长度(令牌)`
|
||||
|
||||
1. `要求结束`
|
||||
`if 要求结束`
|
||||
|
||||
*位置 == 长度(点)*
|
||||
`return 位置 == 长度(点)`
|
||||
|
||||
*true*
|
||||
`end`
|
||||
`return true`
|
||||
|
||||
`end`
|
||||
**当前 = 令牌[下标]**
|
||||
|
||||
1. `当前.kind == "anchor"`
|
||||
`if 当前.kind == "anchor"`
|
||||
|
||||
1. `当前.value == "start" and 位置 == 0`
|
||||
`if 当前.value == "start" and 位置 == 0`
|
||||
|
||||
*匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)*
|
||||
`return 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
|
||||
|
||||
2. `当前.value == "end" and 位置 == 长度(点)`
|
||||
`else`
|
||||
`if 当前.value == "end" and 位置 == 长度(点)`
|
||||
|
||||
*匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)*
|
||||
`return 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
|
||||
|
||||
*false*
|
||||
`end`
|
||||
`end`
|
||||
`return false`
|
||||
|
||||
*尝试匹配(令牌, 下标, 当前, 点, 位置, 0, 要求结束)*
|
||||
`end`
|
||||
`return 尝试匹配(令牌, 下标, 当前, 点, 位置, 0, 要求结束)`
|
||||
|
||||
## 匹配
|
||||
|
||||
`(模式, 文本)`
|
||||
`params(模式, 文本)`
|
||||
|
||||
编译后要求整个文本匹配。支持 `^`、`$`、`.`、`*`、`+`、`?`、
|
||||
`[...]` 和 `\\` 转义;不支持分组和选择。
|
||||
编译后要求整个文本匹配。支持 ^、$、.、*、+、?、
|
||||
[...] 和 \\ 转义;不支持分组和选择。
|
||||
|
||||
**编译结果 = 编译(text.codepoints(模式), 0)**
|
||||
|
||||
1. `not 编译结果.ok`
|
||||
`if not 编译结果.ok`
|
||||
|
||||
*编译结果*
|
||||
`return 编译结果`
|
||||
|
||||
*{ok: true, value: 匹配序列(编译结果.value, 0, text.codepoints(文本), 0, true)}*
|
||||
`end`
|
||||
`return {ok: true, value: 匹配序列(编译结果.value, 0, text.codepoints(文本), 0, true)}`
|
||||
|
||||
## 搜索
|
||||
|
||||
`(模式, 文本)`
|
||||
`params(模式, 文本)`
|
||||
|
||||
**编译结果 = 编译(text.codepoints(模式), 0)**
|
||||
|
||||
1. `not 编译结果.ok`
|
||||
`if not 编译结果.ok`
|
||||
|
||||
*编译结果*
|
||||
`return 编译结果`
|
||||
|
||||
`end`
|
||||
**令牌 = 编译结果.value**
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
@@ -419,40 +498,44 @@
|
||||
|
||||
**结果 = false**
|
||||
|
||||
- `下标 <= 长度(点) and not 结果`
|
||||
`while 下标 <= 长度(点) and not 结果`
|
||||
|
||||
1. `匹配序列(令牌, 0, 点, 下标, false)`
|
||||
`if 匹配序列(令牌, 0, 点, 下标, false)`
|
||||
|
||||
**结果 = true**
|
||||
**结果 = true**
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*成功(结果)*
|
||||
`end`
|
||||
`return 成功(结果)`
|
||||
|
||||
## 扩展匹配
|
||||
|
||||
`(模式, 文本)`
|
||||
`params(模式, 文本)`
|
||||
|
||||
使用宿主正则引擎(支持分组、选择、`\\d` 等)判断是否匹配。模式无效时
|
||||
返回 `regex.invalid`。仅项目模式;纯 `.mq.md` 子集仍由 `匹配`/`搜索` 提供。
|
||||
使用宿主正则引擎(支持分组、选择、\\d 等)判断是否匹配。模式无效时
|
||||
返回 regex.invalid。仅项目模式;纯 .mq.md 子集仍由 匹配/搜索 提供。
|
||||
|
||||
*resource.request("regex.match", [模式, 文本])*
|
||||
`return resource.request("regex.match", [模式, 文本])`
|
||||
|
||||
## 扩展搜索
|
||||
|
||||
`(模式, 文本)`
|
||||
`params(模式, 文本)`
|
||||
|
||||
*resource.request("regex.match", [模式, 文本])*
|
||||
`return resource.request("regex.match", [模式, 文本])`
|
||||
|
||||
## 捕获
|
||||
|
||||
`(模式, 文本)`
|
||||
`params(模式, 文本)`
|
||||
|
||||
返回 `{ok:true, value:{matched:Bool, groups:List<Text|None>}}`。下标 0 是
|
||||
完整匹配;未参与匹配的分组是 `None`。
|
||||
返回 {ok:true, value:{matched:Bool, groups:List<Text|None>}}。下标 0 是
|
||||
完整匹配;未参与匹配的分组是 None。
|
||||
|
||||
*resource.request("regex.captures", [模式, 文本])*
|
||||
`return resource.request("regex.captures", [模式, 文本])`
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.1.0",
|
||||
"digest": "sha256:9a921f5fc7a929cee1fa4b4d8f2b401a3bf69198d1a753b5dc8de5d28d46583f"
|
||||
"digest": "sha256:c3fca0cc3bd8f89f0f45d52418113613dd0613711cfdba76b514e5e6244409d2"
|
||||
}
|
||||
@@ -3,8 +3,10 @@ import:
|
||||
clock: "std:clock"
|
||||
---
|
||||
|
||||
# @exec clock
|
||||
|
||||
## main
|
||||
|
||||
**现在 = clock.现在()**
|
||||
|
||||
*[现在.ok, 类型(现在.value), 现在.value > 1600000000000]*
|
||||
`return [现在.ok, 类型(现在.value), 现在.value > 1600000000000]`
|
||||
@@ -3,10 +3,12 @@ import:
|
||||
compress: "std:compress"
|
||||
---
|
||||
|
||||
# @exec compress
|
||||
|
||||
## main
|
||||
|
||||
**压缩结果 = compress.压缩("hello 世界")**
|
||||
|
||||
**解压结果 = compress.解压(压缩结果.value)**
|
||||
|
||||
*[压缩结果.ok, 长度(压缩结果.value) > 0, 解压结果.ok, 解压结果.value]*
|
||||
`return [压缩结果.ok, 长度(压缩结果.value) > 0, 解压结果.ok, 解压结果.value]`
|
||||
@@ -3,8 +3,10 @@ import:
|
||||
console: "std:io/console"
|
||||
---
|
||||
|
||||
# @exec console
|
||||
|
||||
## main
|
||||
|
||||
**行 = console.读取行()**
|
||||
|
||||
*[行.ok, 行.value]*
|
||||
`return [行.ok, 行.value]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
csv: "std:data/csv"
|
||||
---
|
||||
|
||||
# @exec csv
|
||||
|
||||
## main
|
||||
|
||||
**`行 = csv.解析行("甲,\"乙,丙\",\"说\"\"好\"")`**
|
||||
@@ -17,4 +19,4 @@ import:
|
||||
|
||||
**格式化 = csv.格式化(多行.value)**
|
||||
|
||||
*[行.value, csv.格式化行(行.value), 空.value, 坏.code, 框.value, 多行.ok, 多行.value, 格式化]*
|
||||
`return [行.value, csv.格式化行(行.value), 空.value, 坏.code, 框.value, 多行.ok, 多行.value, 格式化]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
datetime: "std:datetime"
|
||||
---
|
||||
|
||||
# @exec datetime
|
||||
|
||||
## main
|
||||
|
||||
*[datetime.格式化(0), datetime.格式化(1700000000123), datetime.解析("1970-01-01T00:00:00Z").value, datetime.解析("2026-11-21T08:00:00.123Z").value, datetime.解析("2026-13-01T00:00:00Z").ok, datetime.解析("2026-02-29T00:00:00Z").ok, datetime.格式化(-1)]*
|
||||
`return [datetime.格式化(0), datetime.格式化(1700000000123), datetime.解析("1970-01-01T00:00:00Z").value, datetime.解析("2026-11-21T08:00:00.123Z").value, datetime.解析("2026-13-01T00:00:00Z").ok, datetime.解析("2026-02-29T00:00:00Z").ok, datetime.格式化(-1)]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
demo: "std:demo"
|
||||
---
|
||||
|
||||
# @exec demo
|
||||
|
||||
## main
|
||||
|
||||
*demo.演示函数()*
|
||||
`return demo.演示函数()`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
env: "std:env"
|
||||
---
|
||||
|
||||
# @exec env
|
||||
|
||||
## main
|
||||
|
||||
**存在 = env.存在("MARQDO_TEST_ENV")**
|
||||
@@ -11,4 +13,4 @@ import:
|
||||
|
||||
**缺失 = env.读取("MARQDO_MISSING_ENV")**
|
||||
|
||||
*[存在.ok, 存在.value, 读取.ok, 读取.value, 缺失.ok, 缺失.code]*
|
||||
`return [存在.ok, 存在.value, 读取.ok, 读取.value, 缺失.ok, 缺失.code]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
format: "std:format"
|
||||
---
|
||||
|
||||
# @exec format
|
||||
|
||||
## main
|
||||
|
||||
*[format.字节长度("Aé"), format.显示(["文本", 2, 1.5]), format.显示({a: 1}), format.列表显示(["a", 2]), format.显示(None)]*
|
||||
`return [format.字节长度("Aé"), format.显示(["文本", 2, 1.5]), format.显示({a: 1}), format.列表显示(["a", 2]), format.显示(None)]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
fs: "std:fs/file"
|
||||
---
|
||||
|
||||
# @exec fs
|
||||
|
||||
## main
|
||||
|
||||
**创建 = fs.创建目录("out")**
|
||||
@@ -33,4 +35,4 @@ import:
|
||||
|
||||
**删除目录 = fs.删除("out")**
|
||||
|
||||
*[创建.ok, 写入.value.count, 存在.value, 元数据.value.kind, 元数据.value.size, 列表.value, 是文件.value, 是目录.value, 重命名.ok, 读取.value, 追加.value, 片段.value, 遍历.value, 删除.ok, 删除目录.ok]*
|
||||
`return [创建.ok, 写入.value.count, 存在.value, 元数据.value.kind, 元数据.value.size, 列表.value, 是文件.value, 是目录.value, 重命名.ok, 读取.value, 追加.value, 片段.value, 遍历.value, 删除.ok, 删除目录.ok]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
http: "std:net/http"
|
||||
---
|
||||
|
||||
# @exec http
|
||||
|
||||
## main
|
||||
|
||||
**响应文本 = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n"**
|
||||
@@ -19,4 +21,4 @@ import:
|
||||
|
||||
**请求文本 = http.字节文本(请求字节)**
|
||||
|
||||
*[响应.状态, 响应.原因, 响应.头["Content-Type"], 响应.体, 请求, 响应字节.value.status, 正文.value, 请求文本.value]*
|
||||
`return [响应.状态, 响应.原因, 响应.头["Content-Type"], 响应.体, 请求, 响应字节.value.status, 正文.value, 请求文本.value]`
|
||||
@@ -3,8 +3,10 @@ import:
|
||||
io: "std:io"
|
||||
---
|
||||
|
||||
# @exec io
|
||||
|
||||
## main
|
||||
|
||||
> io.写值("stdlib self-test")
|
||||
> **io.写值("stdlib self-test")**
|
||||
|
||||
*None*
|
||||
`return None`
|
||||
+11
-7
@@ -3,6 +3,8 @@ import:
|
||||
json: "std:data/json"
|
||||
---
|
||||
|
||||
# @exec json
|
||||
|
||||
## main
|
||||
|
||||
**`对象 = json.解析("{\"a\": 1, \"b\": [true, null, \"说\\\"好\"]}")`**
|
||||
@@ -17,22 +19,24 @@ import:
|
||||
|
||||
**深度下标 = 0**
|
||||
|
||||
- `深度下标 < 130`
|
||||
`while 深度下标 < 130`
|
||||
|
||||
**深度文本 = 深度文本 + "["**
|
||||
**深度文本 = 深度文本 + "["**
|
||||
|
||||
**深度下标 = 深度下标 + 1**
|
||||
**深度下标 = 深度下标 + 1**
|
||||
|
||||
`end`
|
||||
**深度下标 = 0**
|
||||
|
||||
- `深度下标 < 130`
|
||||
`while 深度下标 < 130`
|
||||
|
||||
**深度文本 = 深度文本 + "]"**
|
||||
**深度文本 = 深度文本 + "]"**
|
||||
|
||||
**深度下标 = 深度下标 + 1**
|
||||
**深度下标 = 深度下标 + 1**
|
||||
|
||||
`end`
|
||||
**深度 = json.解析(深度文本)**
|
||||
|
||||
**`多个 = json.解析多个("1 2 [3]")`**
|
||||
|
||||
*[对象.ok, 对象.value.a, 对象.value.b[2], json.格式化(浮点.value), 失败.ok, 失败.code, 尾随.code, 深度.ok, 深度.code, 多个.ok, 多个.value]*
|
||||
`return [对象.ok, 对象.value.a, 对象.value.b[2], json.格式化(浮点.value), 失败.ok, 失败.code, 尾随.code, 深度.ok, 深度.code, 多个.ok, 多个.value]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
path: "std:path"
|
||||
---
|
||||
|
||||
# @exec path
|
||||
|
||||
## main
|
||||
|
||||
*[path.连接(["a", "", "b", "c"]), path.文件名("a/b/c.txt"), path.目录名("a/b/c.txt"), path.扩展名("a/b/c.txt"), path.规范("./a//b/../c"), path.规范("/a/./b/../c"), path.规范("../a/b"), path.是否绝对("/a"), path.是否绝对("a")]*
|
||||
`return [path.连接(["a", "", "b", "c"]), path.文件名("a/b/c.txt"), path.目录名("a/b/c.txt"), path.扩展名("a/b/c.txt"), path.规范("./a//b/../c"), path.规范("/a/./b/../c"), path.规范("../a/b"), path.是否绝对("/a"), path.是否绝对("a")]`
|
||||
@@ -3,8 +3,10 @@ import:
|
||||
process: "std:process"
|
||||
---
|
||||
|
||||
# @exec process
|
||||
|
||||
## main
|
||||
|
||||
**结果 = process.运行("/bin/echo", ["hello"])**
|
||||
|
||||
*[结果.ok, 结果.value.status, 结果.value.stdout, 结果.value.stderr]*
|
||||
`return [结果.ok, 结果.value.status, 结果.value.stdout, 结果.value.stderr]`
|
||||
@@ -3,10 +3,12 @@ import:
|
||||
random: "std:random"
|
||||
---
|
||||
|
||||
# @exec random
|
||||
|
||||
## main
|
||||
|
||||
**字节结果 = random.字节(16)**
|
||||
|
||||
**整数结果 = random.整数(100)**
|
||||
|
||||
*[字节结果.ok, 长度(字节结果.value), 整数结果.ok, 整数结果.value >= 0, 整数结果.value < 100]*
|
||||
`return [字节结果.ok, 长度(字节结果.value), 整数结果.ok, 整数结果.value >= 0, 整数结果.value < 100]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
regex: "std:regex"
|
||||
---
|
||||
|
||||
# @exec regex
|
||||
|
||||
## main
|
||||
|
||||
**`星号 = regex.匹配("a*b", "aaab")`**
|
||||
@@ -31,4 +33,4 @@ import:
|
||||
|
||||
**捕获 = regex.捕获("^(a+)(b|c)$", "aab")**
|
||||
|
||||
*[星号.value, 加号.value, 锚点.value, 类.value, 否定类.value, 任意.value, 可选.value, 转义.value, 搜索.value, 无效.ok, 无效.code, 不支持.code, 扩展.value, 捕获.value.matched, 捕获.value.groups]*
|
||||
`return [星号.value, 加号.value, 锚点.value, 类.value, 否定类.value, 任意.value, 可选.value, 转义.value, 搜索.value, 无效.ok, 无效.code, 不支持.code, 扩展.value, 捕获.value.matched, 捕获.value.groups]`
|
||||
@@ -3,8 +3,10 @@ import:
|
||||
stream: "std:io/stream"
|
||||
---
|
||||
|
||||
# @exec stream
|
||||
|
||||
## main
|
||||
|
||||
**结果 = stream.写文本("stream\n")**
|
||||
|
||||
*[结果.ok, 结果.value.count]*
|
||||
`return [结果.ok, 结果.value.count]`
|
||||
@@ -3,6 +3,8 @@ import:
|
||||
table: "std:data/table"
|
||||
---
|
||||
|
||||
# @exec table
|
||||
|
||||
## main
|
||||
|
||||
**数据 = 表(["名称", "分数"], [["甲", 87], ["乙", 92], ["丙", 71]])**
|
||||
@@ -25,4 +27,4 @@ import:
|
||||
|
||||
**分组 = table.分组(表(["类别", "值"], [["a", 1], ["b", 2], ["a", 3]]), 0, 1)**
|
||||
|
||||
*[选择, 过滤, 排序, 追加, 设置, 连接, 分组, 数据, table.转GFM(数据)]*
|
||||
`return [选择, 过滤, 排序, 追加, 设置, 连接, 分组, 数据, table.转GFM(数据)]`
|
||||
@@ -3,10 +3,12 @@ import:
|
||||
text: "std:text"
|
||||
---
|
||||
|
||||
# @exec text
|
||||
|
||||
## main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**长度 = text.utf8编码("é", 内存, 0)**
|
||||
|
||||
*[长度, 内存[0], 内存[1]]*
|
||||
`return [长度, 内存[0], 内存[1]]`
|
||||
@@ -3,10 +3,12 @@ import:
|
||||
utf8: "std:text/utf8"
|
||||
---
|
||||
|
||||
# @exec utf8
|
||||
|
||||
## main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**长度 = utf8.编码("é", 内存, 0)**
|
||||
|
||||
*[长度, utf8.解码(内存, 0, 长度).value, utf8.解码(内存, 0, 1).ok]*
|
||||
`return [长度, utf8.解码(内存, 0, 长度).value, utf8.解码(内存, 0, 1).ok]`
|
||||
+34
-24
@@ -1,8 +1,10 @@
|
||||
|
||||
# @exec text
|
||||
## utf8编码
|
||||
|
||||
`(文本, 内存, 基址)`
|
||||
`params(文本, 内存, 基址)`
|
||||
|
||||
把 Unicode 标量序列按 UTF-8 写入 `Memory`,返回字节长度。
|
||||
把 Unicode 标量序列按 UTF-8 写入 Memory,返回字节长度。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -10,46 +12,54 @@
|
||||
|
||||
**偏移 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
**码点 = 点[下标]**
|
||||
|
||||
1. `码点 < 128`
|
||||
`if 码点 < 128`
|
||||
|
||||
**`内存[基址 + 偏移] = 码点`**
|
||||
**`内存[基址 + 偏移] = 码点`**
|
||||
|
||||
**偏移 = 偏移 + 1**
|
||||
**偏移 = 偏移 + 1**
|
||||
|
||||
2. `码点 < 2048`
|
||||
`else`
|
||||
`if 码点 < 2048`
|
||||
|
||||
**`内存[基址 + 偏移] = 192 + 码点 // 64`**
|
||||
**`内存[基址 + 偏移] = 192 + 码点 // 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 2**
|
||||
**偏移 = 偏移 + 2**
|
||||
|
||||
3. `码点 < 65536`
|
||||
`else`
|
||||
`if 码点 < 65536`
|
||||
|
||||
**`内存[基址 + 偏移] = 224 + 码点 // 4096`**
|
||||
**`内存[基址 + 偏移] = 224 + 码点 // 4096`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 64 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 64 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 3**
|
||||
**偏移 = 偏移 + 3**
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**`内存[基址 + 偏移] = 240 + 码点 // 262144`**
|
||||
**`内存[基址 + 偏移] = 240 + 码点 // 262144`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 4096 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 4096 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 // 64 % 64`**
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 // 64 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 3] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 3] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 4**
|
||||
**偏移 = 偏移 + 4**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*偏移*
|
||||
`end`
|
||||
`return 偏移`
|
||||
+122
-88
@@ -1,27 +1,29 @@
|
||||
|
||||
# @exec utf8
|
||||
## 成功
|
||||
|
||||
`(值)`
|
||||
`params(值)`
|
||||
|
||||
*{ok: true, value: 值}*
|
||||
`return {ok: true, value: 值}`
|
||||
|
||||
## 失败
|
||||
|
||||
`(代码, 消息)`
|
||||
`params(代码, 消息)`
|
||||
|
||||
*{ok: false, code: 代码, message: 消息}*
|
||||
`return {ok: false, code: 代码, message: 消息}`
|
||||
|
||||
## 续字节
|
||||
|
||||
`(字节)`
|
||||
`params(字节)`
|
||||
|
||||
*字节 >= 128 and 字节 < 192*
|
||||
`return 字节 >= 128 and 字节 < 192`
|
||||
|
||||
## 编码
|
||||
|
||||
`(文本, 内存, 基址)`
|
||||
`params(文本, 内存, 基址)`
|
||||
|
||||
把 Unicode 标量序列按 UTF-8 写入 `Memory`,返回字节长度。
|
||||
这是 `.mq.md` 自己实现的编码逻辑,不是 Rust 内建 UTF-8 转换。
|
||||
把 Unicode 标量序列按 UTF-8 写入 Memory,返回字节长度。
|
||||
这是 .mq.md 自己实现的编码逻辑,不是 Rust 内建 UTF-8 转换。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
@@ -29,125 +31,142 @@
|
||||
|
||||
**偏移 = 0**
|
||||
|
||||
- `下标 < 长度(点)`
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
**码点 = 点[下标]**
|
||||
|
||||
1. `码点 < 128`
|
||||
`if 码点 < 128`
|
||||
|
||||
**`内存[基址 + 偏移] = 码点`**
|
||||
**`内存[基址 + 偏移] = 码点`**
|
||||
|
||||
**偏移 = 偏移 + 1**
|
||||
**偏移 = 偏移 + 1**
|
||||
|
||||
2. `码点 < 2048`
|
||||
`else`
|
||||
`if 码点 < 2048`
|
||||
|
||||
**`内存[基址 + 偏移] = 192 + 码点 // 64`**
|
||||
**`内存[基址 + 偏移] = 192 + 码点 // 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 2**
|
||||
**偏移 = 偏移 + 2**
|
||||
|
||||
3. `码点 < 65536`
|
||||
`else`
|
||||
`if 码点 < 65536`
|
||||
|
||||
**`内存[基址 + 偏移] = 224 + 码点 // 4096`**
|
||||
**`内存[基址 + 偏移] = 224 + 码点 // 4096`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 64 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 64 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 3**
|
||||
**偏移 = 偏移 + 3**
|
||||
|
||||
4. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**`内存[基址 + 偏移] = 240 + 码点 // 262144`**
|
||||
**`内存[基址 + 偏移] = 240 + 码点 // 262144`**
|
||||
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 4096 % 64`**
|
||||
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 4096 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 // 64 % 64`**
|
||||
**`内存[基址 + 偏移 + 2] = 128 + 码点 // 64 % 64`**
|
||||
|
||||
**`内存[基址 + 偏移 + 3] = 128 + 码点 % 64`**
|
||||
**`内存[基址 + 偏移 + 3] = 128 + 码点 % 64`**
|
||||
|
||||
**偏移 = 偏移 + 4**
|
||||
**偏移 = 偏移 + 4**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*偏移*
|
||||
`end`
|
||||
`return 偏移`
|
||||
|
||||
## 解码2
|
||||
|
||||
`(内存, 基址, 长度, 偏移, 文本)`
|
||||
`params(内存, 基址, 长度, 偏移, 文本)`
|
||||
|
||||
1. `偏移 + 1 >= 长度`
|
||||
`if 偏移 + 1 >= 长度`
|
||||
|
||||
*[文本, 偏移, "utf8.truncated"]*
|
||||
`return [文本, 偏移, "utf8.truncated"]`
|
||||
|
||||
`end`
|
||||
**b1 = 内存[基址 + 偏移 + 1]**
|
||||
|
||||
1. `not 续字节(b1)`
|
||||
`if not 续字节(b1)`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_continuation"]*
|
||||
`return [文本, 偏移, "utf8.invalid_continuation"]`
|
||||
|
||||
`end`
|
||||
**码点 = (内存[基址 + 偏移] - 192) * 64 + (b1 - 128)**
|
||||
|
||||
1. `码点 < 128`
|
||||
`if 码点 < 128`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_scalar"]*
|
||||
`return [文本, 偏移, "utf8.invalid_scalar"]`
|
||||
|
||||
*[文本 + text.from_codepoint(码点), 偏移 + 2, ""]*
|
||||
`end`
|
||||
`return [文本 + text.from_codepoint(码点), 偏移 + 2, ""]`
|
||||
|
||||
## 解码3
|
||||
|
||||
`(内存, 基址, 长度, 偏移, 文本)`
|
||||
`params(内存, 基址, 长度, 偏移, 文本)`
|
||||
|
||||
1. `偏移 + 2 >= 长度`
|
||||
`if 偏移 + 2 >= 长度`
|
||||
|
||||
*[文本, 偏移, "utf8.truncated"]*
|
||||
`return [文本, 偏移, "utf8.truncated"]`
|
||||
|
||||
`end`
|
||||
**b1 = 内存[基址 + 偏移 + 1]**
|
||||
|
||||
**b2 = 内存[基址 + 偏移 + 2]**
|
||||
|
||||
1. `not (续字节(b1) and 续字节(b2))`
|
||||
`if not (续字节(b1) and 续字节(b2))`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_continuation"]*
|
||||
`return [文本, 偏移, "utf8.invalid_continuation"]`
|
||||
|
||||
`end`
|
||||
**码点 = (内存[基址 + 偏移] - 224) * 4096 + (b1 - 128) * 64 + (b2 - 128)**
|
||||
|
||||
1. `码点 < 2048 or (码点 >= 55296 and 码点 <= 57343)`
|
||||
`if 码点 < 2048 or (码点 >= 55296 and 码点 <= 57343)`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_scalar"]*
|
||||
`return [文本, 偏移, "utf8.invalid_scalar"]`
|
||||
|
||||
*[文本 + text.from_codepoint(码点), 偏移 + 3, ""]*
|
||||
`end`
|
||||
`return [文本 + text.from_codepoint(码点), 偏移 + 3, ""]`
|
||||
|
||||
## 解码4
|
||||
|
||||
`(内存, 基址, 长度, 偏移, 文本)`
|
||||
`params(内存, 基址, 长度, 偏移, 文本)`
|
||||
|
||||
1. `偏移 + 3 >= 长度`
|
||||
`if 偏移 + 3 >= 长度`
|
||||
|
||||
*[文本, 偏移, "utf8.truncated"]*
|
||||
`return [文本, 偏移, "utf8.truncated"]`
|
||||
|
||||
`end`
|
||||
**b1 = 内存[基址 + 偏移 + 1]**
|
||||
|
||||
**b2 = 内存[基址 + 偏移 + 2]**
|
||||
|
||||
**b3 = 内存[基址 + 偏移 + 3]**
|
||||
|
||||
1. `not (续字节(b1) and 续字节(b2) and 续字节(b3))`
|
||||
`if not (续字节(b1) and 续字节(b2) and 续字节(b3))`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_continuation"]*
|
||||
`return [文本, 偏移, "utf8.invalid_continuation"]`
|
||||
|
||||
`end`
|
||||
**码点 = (内存[基址 + 偏移] - 240) * 262144 + (b1 - 128) * 4096 + (b2 - 128) * 64 + (b3 - 128)**
|
||||
|
||||
1. `码点 < 65536 or 码点 > 1114111`
|
||||
`if 码点 < 65536 or 码点 > 1114111`
|
||||
|
||||
*[文本, 偏移, "utf8.invalid_scalar"]*
|
||||
`return [文本, 偏移, "utf8.invalid_scalar"]`
|
||||
|
||||
*[文本 + text.from_codepoint(码点), 偏移 + 4, ""]*
|
||||
`end`
|
||||
`return [文本 + text.from_codepoint(码点), 偏移 + 4, ""]`
|
||||
|
||||
## 解码
|
||||
|
||||
`(内存, 基址, 长度)`
|
||||
`params(内存, 基址, 长度)`
|
||||
|
||||
**偏移 = 0**
|
||||
|
||||
@@ -155,70 +174,85 @@
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
- `偏移 < 长度 and 错误 == ""`
|
||||
`while 偏移 < 长度 and 错误 == ""`
|
||||
|
||||
**首 = 内存[基址 + 偏移]**
|
||||
**首 = 内存[基址 + 偏移]**
|
||||
|
||||
1. `首 < 128`
|
||||
`if 首 < 128`
|
||||
|
||||
**文本 = 文本 + text.from_codepoint(首)**
|
||||
**文本 = 文本 + text.from_codepoint(首)**
|
||||
|
||||
**偏移 = 偏移 + 1**
|
||||
**偏移 = 偏移 + 1**
|
||||
|
||||
2. `首 < 194`
|
||||
`else`
|
||||
`if 首 < 194`
|
||||
|
||||
**错误 = "utf8.invalid_lead"**
|
||||
**错误 = "utf8.invalid_lead"**
|
||||
|
||||
3. `首 < 224`
|
||||
`else`
|
||||
`if 首 < 224`
|
||||
|
||||
**结果 = 解码2(内存, 基址, 长度, 偏移, 文本)**
|
||||
**结果 = 解码2(内存, 基址, 长度, 偏移, 文本)**
|
||||
|
||||
**文本 = 结果[0]**
|
||||
**文本 = 结果[0]**
|
||||
|
||||
**偏移 = 结果[1]**
|
||||
**偏移 = 结果[1]**
|
||||
|
||||
**错误 = 结果[2]**
|
||||
**错误 = 结果[2]**
|
||||
|
||||
4. `首 < 240`
|
||||
`else`
|
||||
`if 首 < 240`
|
||||
|
||||
**结果 = 解码3(内存, 基址, 长度, 偏移, 文本)**
|
||||
**结果 = 解码3(内存, 基址, 长度, 偏移, 文本)**
|
||||
|
||||
**文本 = 结果[0]**
|
||||
**文本 = 结果[0]**
|
||||
|
||||
**偏移 = 结果[1]**
|
||||
**偏移 = 结果[1]**
|
||||
|
||||
**错误 = 结果[2]**
|
||||
**错误 = 结果[2]**
|
||||
|
||||
5. `首 < 245`
|
||||
`else`
|
||||
`if 首 < 245`
|
||||
|
||||
**结果 = 解码4(内存, 基址, 长度, 偏移, 文本)**
|
||||
**结果 = 解码4(内存, 基址, 长度, 偏移, 文本)**
|
||||
|
||||
**文本 = 结果[0]**
|
||||
**文本 = 结果[0]**
|
||||
|
||||
**偏移 = 结果[1]**
|
||||
**偏移 = 结果[1]**
|
||||
|
||||
**错误 = 结果[2]**
|
||||
**错误 = 结果[2]**
|
||||
|
||||
6. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**错误 = "utf8.invalid_lead"**
|
||||
**错误 = "utf8.invalid_lead"**
|
||||
|
||||
1. `错误 == ""`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 错误 == ""`
|
||||
|
||||
*成功(文本)*
|
||||
`return 成功(文本)`
|
||||
|
||||
2. `true`
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
*失败(错误, "UTF-8 解码失败")*
|
||||
`return 失败(错误, "UTF-8 解码失败")`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## utf8编码
|
||||
|
||||
`(文本, 内存, 基址)`
|
||||
`params(文本, 内存, 基址)`
|
||||
|
||||
*编码(文本, 内存, 基址)*
|
||||
`return 编码(文本, 内存, 基址)`
|
||||
|
||||
## utf8解码
|
||||
|
||||
`(内存, 基址, 长度)`
|
||||
`params(内存, 基址, 长度)`
|
||||
|
||||
*解码(内存, 基址, 长度)*
|
||||
`return 解码(内存, 基址, 长度)`
|
||||
+112
-27
@@ -1,7 +1,7 @@
|
||||
# Marqdo conformance and integration test corpus
|
||||
|
||||
This directory holds the P0/P1 conformance corpus required by
|
||||
`docs/DEVELOPMENT_BLUEPRINT.md` §13/§14. The Rust harnesses live in
|
||||
RFC-LANG-0002 and `docs/DEVELOPMENT_BLUEPRINT.md` §13/§14. The Rust harnesses live in
|
||||
`crates/cli/tests/` (they use the workspace libraries directly and the
|
||||
`marqdo` binary via `CARGO_BIN_EXE_marqdo`); the fixtures are plain files here
|
||||
so they can be rendered, diffed and reviewed like Markdown documents.
|
||||
@@ -9,6 +9,20 @@ so they can be rendered, diffed and reviewed like Markdown documents.
|
||||
Everything here is data. Nothing in this directory modifies the repository, and
|
||||
no test commits, copies or rewrites files outside a throw-away temp directory.
|
||||
|
||||
> **Migration state (RFC-LANG-0002).** The source text in this corpus uses the
|
||||
> current single syntax. The Rust frontend still implements the pre-RFC mapping,
|
||||
> so the semantic, negative, property and CLI suites that execute Marqdo source
|
||||
> are **expected to be red** until the frontend migration lands. `conformance_ast`
|
||||
> is unaffected by the semantic change (the Markdown profile is unchanged).
|
||||
> `tests/negative/warnings/01-inferred-signature` pins the optional
|
||||
> `sem.inferred_signature` lint as enabled; the current frontend does not emit
|
||||
> it. `sem.no_entry_function` is a `run` entry-selection diagnostic and cannot be
|
||||
> pinned by `crates/cli/tests/negative.rs`, which only calls `analyze_source` /
|
||||
> `marqdo_runtime::run`; that coverage needs a CLI integration test. Do not
|
||||
> regenerate goldens or restore the old mapper to turn these suites green. See
|
||||
> [`../docs/STATUS.md`](../docs/STATUS.md) and
|
||||
> [`../docs/migration/README.md`](../docs/migration/README.md).
|
||||
|
||||
## Layout
|
||||
|
||||
```text
|
||||
@@ -17,8 +31,8 @@ tests/
|
||||
│ ├── ast/ 160 × *.mq.md + sibling *.ast.json goldens
|
||||
│ └── semantics/ 73 × *.mq.md + sibling *.expected.json goldens
|
||||
├── negative/
|
||||
│ ├── *.mq.md 52 × compile-time hard-error fixtures + *.expected.json
|
||||
│ ├── warnings/ 6 × inert-executable warning fixtures + *.expected.json
|
||||
│ ├── *.mq.md 45 × compile-time hard-error fixtures + *.expected.json
|
||||
│ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json
|
||||
│ └── runtime/ 21 × runtime-error fixtures + *.expected.json
|
||||
└── README.md this file
|
||||
```
|
||||
@@ -29,7 +43,7 @@ Rust harnesses (all in `crates/cli/tests/`):
|
||||
|---|---|
|
||||
| `conformance_ast.rs` | The frozen `marqdo.md.v1` profile parses each fixture into exactly the checked-in AST (node kinds, attributes, literals, byte spans, order). |
|
||||
| `conformance_semantics.rs` | Each semantic fixture compiles through `marqdo_frontend`, is assembled into `marqdo_ir::Program` and executed with `marqdo_runtime` + `marqdo_host::StdHost`; returned wire value and program stdout match. |
|
||||
| `negative.rs` | Invalid executable shapes are **hard errors** (never prose fallbacks), exact sorted diagnostic-code lists; warnings and runtime error codes are asserted in their own suites. |
|
||||
| `negative.rs` | Current-syntax diagnostics are **hard errors** (never prose fallbacks): exact sorted `sem.*`/`symbol.*`/`call.*`/`frontmatter.*` code lists, the `sem.inferred_signature` warning model with inert-knowledge controls, and runtime error codes — each asserted in its own suite. |
|
||||
| `properties.rs` | Blueprint §14.2 prose invariance: inserting/removing pure narration paragraphs never changes the executable function IR (modulo source spans) and diagnostics stay error-free. |
|
||||
| `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. |
|
||||
|
||||
@@ -63,8 +77,11 @@ The power/control-flow slice is pinned by:
|
||||
* semantic fixtures 37–44: right-associative power, unary-minus precedence,
|
||||
parentheses, float negative exponents, Strong+CodeSpan assignment, branch,
|
||||
loop and inert prose;
|
||||
* negative fixtures 49–52: missing power/condition operands and executable
|
||||
nodes swallowed by a condition paragraph;
|
||||
* negative fixtures 18–23: malformed payload statements (missing condition,
|
||||
trailing colon, `end if`, empty `return`, multi-statement payload, bad
|
||||
`params` syntax); fixtures 24–29 pin control-stack pairing, including the
|
||||
heading boundary that reports `sem.unclosed_control` and `sem.unmatched_end`
|
||||
independently;
|
||||
* runtime negatives 11–12: negative integer exponent and exponent budget;
|
||||
* `crates/marqdo-frontend/src/payload.rs` span tests and
|
||||
`crates/cli/tests/integration_cli.rs` CLI span/E2E assertions.
|
||||
@@ -77,8 +94,8 @@ The addressable-memory slice (RFC-CM P1, ADR-0022) is pinned by:
|
||||
* runtime negatives 13–18: out-of-bounds and huge offsets, byte values outside
|
||||
`0..=255`, index assignment on a `List`, growth beyond the declared maximum
|
||||
and negative page counts;
|
||||
* `tests/negative/runtime/15-index-assign-non-memory.mq.md` also guards the v1
|
||||
value semantics of `List` (it must not become shared mutable memory);
|
||||
* `tests/negative/runtime/15-index-assign-non-memory.mq.md` also guards the
|
||||
current value semantics of `List` (it must not become shared mutable memory);
|
||||
* `crates/marqdo-runtime/src/memory.rs` unit tests (aliasing, atomic failed
|
||||
growth, forged/stale handles, page arithmetic) and
|
||||
`crates/marqdo-runtime/tests/interpreter.rs` host-boundary/budget tests;
|
||||
@@ -277,8 +294,9 @@ RFC-CM CM-A06 resource streams (ADR-0025) are pinned by:
|
||||
|
||||
Fixture discovery is directory-based and sorted by file name, so the order is
|
||||
deterministic on every platform. The AST and semantic suites fail loudly if the
|
||||
corpus shrinks below 100 / 25 fixtures, and the negative suite fails below 30
|
||||
compile-time hard-error fixtures.
|
||||
corpus shrinks below 100 / 25 fixtures; the warning and runtime suites fail if
|
||||
their directories are empty; the negative suite fails below 30 compile-time
|
||||
hard-error fixtures.
|
||||
|
||||
## AST goldens and `UPDATE_GOLDENS`
|
||||
|
||||
@@ -326,38 +344,103 @@ golden without verifying the value would defeat the purpose of the corpus.
|
||||
|
||||
## Negative fixtures
|
||||
|
||||
Compile-time (`tests/negative/*.mq.md`):
|
||||
All three suites use the single current language contract
|
||||
(`docs/architecture/RFC-LANG-0002-unified-semantics.md`,
|
||||
`spec/mapping.md`, `spec/expression.ebnf`): `@exec`/`@knowledge` heading
|
||||
modes, interchangeable `Strong`/`Emph`/inline-`Code` one-statement payloads,
|
||||
and explicit `if`/`else`/`while`/`end`/`return`/`params`. Ordinary Markdown
|
||||
lists, block quotes, tables and emphasis are **not** errors: they are inert
|
||||
containers/knowledge with an empty execution projection. The v1
|
||||
`markdown.invalid_construct` shape errors ("ordered list must have a
|
||||
condition", "block quote must be a call", "Strong must not nest Emph", "empty
|
||||
heading") were removed with the old mapping; `markdown.inert_executable`
|
||||
warnings no longer exist either.
|
||||
|
||||
Compile-time (`tests/negative/*.mq.md`, 45 fixtures):
|
||||
|
||||
```json
|
||||
{"codes": ["markdown.invalid_construct"]}
|
||||
{"codes": ["sem.unclosed_control"]}
|
||||
```
|
||||
|
||||
The expected list is the exact sorted multiset of **error** diagnostic codes
|
||||
produced by `marqdo_frontend::analyze_source`. Warnings emitted by the same
|
||||
document are ignored here. Every listed code is additionally asserted to have
|
||||
`error` severity, and every fixture must produce at least one error — invalid
|
||||
executable shapes never fall back to prose.
|
||||
`error` severity, and every fixture must produce at least one error — an
|
||||
invalid Exec payload never falls back to prose.
|
||||
|
||||
Warnings (`tests/negative/warnings/*.mq.md`):
|
||||
Coverage by group:
|
||||
|
||||
| Group | Fixtures | Codes |
|
||||
|---|---|---|
|
||||
| heading modes and unit identity | 01–07, 44–45 | `sem.invalid_mode_marker`, `sem.empty_unit_name`, `sem.duplicate_unit_name`, `sem.exec_without_function` |
|
||||
| payload extraction | 08–17 | `sem.payload_nested` (nested `Emph`/`Strong`/`Link`/math/strikethrough/line break), `sem.empty_payload` (whitespace-only `Strong`/`Emph`) |
|
||||
| statement grammar | 18–23 | `sem.syntax` |
|
||||
| control stack and heading boundary | 24–29 | `sem.unmatched_else`, `sem.duplicate_else`, `sem.unmatched_end`, `sem.unclosed_control` |
|
||||
| signatures | 30–32 | `sem.signature_position` |
|
||||
| version selection | 33–34 | `sem.unsupported_version_directive` |
|
||||
| kept non-`sem` errors | 35–43 | `symbol.unknown`, `call.arity`, `symbol.uninitialized`, `frontmatter.invalid` |
|
||||
|
||||
Fixture 29 crosses a heading boundary on purpose: the opener's segment reports
|
||||
`sem.unclosed_control` and the later `### @exec` segment reports
|
||||
`sem.unmatched_end`; both are asserted, and neither is "repaired" across the
|
||||
boundary (`spec/mapping.md` §7).
|
||||
|
||||
`sem.no_entry_function` is a `run` entry-selection diagnostic: it is produced
|
||||
when the CLI cannot find an Exec H2 `main`. `crates/cli/tests/negative.rs` only
|
||||
calls `marqdo_frontend::analyze_source` and `marqdo_runtime::run`, and the
|
||||
latter reports an unknown *function* for a missing name; there is no CLI-entry
|
||||
suite in that harness, so this corpus cannot pin the code without a harness
|
||||
change. It is recorded here as a known gap rather than replaced by a weaker
|
||||
assertion (see `spec/references.md` §7 and `spec/mapping.md` §8).
|
||||
|
||||
### v1 → current reclassification
|
||||
|
||||
| v1 fixtures | v1 expectation | Current disposition |
|
||||
|---|---|---|
|
||||
| 01–08 nested `Strong`/`Emph` children | `markdown.invalid_construct` | kept as 08–15 with `sem.payload_nested` |
|
||||
| 09–12 empty/parse-error carriers | `markdown.invalid_construct`, `expr.parse` | empty carriers kept as 16–17 (`sem.empty_payload`); the unqualified expression-parse cases are replaced by the explicit `sem.syntax` statements in 18–23 |
|
||||
| 13–24 list/quote shape errors | `markdown.invalid_construct`, `expr.parse` | **removed**: ordinary lists/quotes are valid inert Markdown now; the positive control is `warnings/02-knowledge-and-containers-are-inert` |
|
||||
| 25–27 link-form calls (external/cross-module/anchor) | `ref.unresolved`, `module.unresolved` | **removed**: link-form calls no longer exist; `ref.unresolved`/`module.unresolved` are now `check --refs`/loader diagnostics outside this harness (`spec/references.md` §7) |
|
||||
| 28–29 duplicate function/namespace names | `markdown.invalid_construct` | kept as 44–45 with `sem.duplicate_unit_name` (duplicate canonical name, `spec/references.md` §2.3) |
|
||||
| 30–31 empty function/namespace headings | `markdown.invalid_construct` | replaced by 04–05 with `sem.empty_unit_name` on an actual mode declaration |
|
||||
| 32–40 unknown/call/signature/frontmatter errors | `symbol.unknown`, `call.arity`, `symbol.uninitialized`, `expr.parse`, `frontmatter.invalid` | kept 35–43 (`frontmatter.*`, `symbol.*`, `call.arity`, `symbol.uninitialized`); malformed-signature cases moved to `sem.syntax`/`sem.signature_position` (23, 30–32) |
|
||||
| 41–48 frontmatter/link/assignment/power shapes | `frontmatter.invalid`, `expr.parse` | frontmatter cases kept as 40–42; link/quote/assignment shapes removed with the old mapping; power/condition cases replaced by 18–29 |
|
||||
| 49–52 power/condition operands swallowed by a branch condition | `expr.parse`, `markdown.invalid_construct` | **removed**: executable nodes inside list items are now independent payloads. Replacement negatives are the `sem.syntax` (18–23) and control-stack (24–29) fixtures |
|
||||
|
||||
Warnings (`tests/negative/warnings/*.mq.md`, 2 fixtures):
|
||||
|
||||
```json
|
||||
{"severity": "warning", "codes": ["markdown.inert_executable"]}
|
||||
{"severity": "warning", "codes": ["sem.inferred_signature"]}
|
||||
```
|
||||
|
||||
These documents must compile **without errors**; the sorted multiset of warning
|
||||
codes must match exactly. `return`/`strong`/lists/block quotes outside a
|
||||
function body are inert content (warning), not hard errors.
|
||||
codes must match exactly. Fixture 01 pins the `sem.inferred_signature` lint for
|
||||
an Exec H2 that relies on free-variable inference. Fixture 02 is a
|
||||
zero-diagnostic control: it proves that ordinary ordered lists, bullet lists
|
||||
and block quotes are valid inert Markdown even inside an `@exec` section, and
|
||||
that an explicit `params(...)` declaration (allowed after prose) suppresses the
|
||||
inferred-signature warning. The lint is specified as **optional**
|
||||
(`spec/mapping.md` §6, "may be enabled"); these fixtures pin it enabled, so if
|
||||
an implementation leaves it off the warning suite — not the hard-error corpus —
|
||||
is what must be revisited.
|
||||
|
||||
Runtime (`tests/negative/runtime/*.mq.md`):
|
||||
Runtime (`tests/negative/runtime/*.mq.md`, 21 fixtures):
|
||||
|
||||
```json
|
||||
{"function": "main", "args": {}, "codes": ["runtime.division_by_zero"]}
|
||||
```
|
||||
|
||||
These documents compile, then must fail at runtime with the expected stable
|
||||
error code. Optional keys: `"grants": ["foreign"]` and `"stack_limit": 24`
|
||||
(used for the recursion-depth fixture so the budget — not the host process
|
||||
stack — is what fails).
|
||||
error code. Sources were migrated to the current syntax (explicit `## @exec`
|
||||
functions, `params(...)` where a function has arguments, payload calls and
|
||||
explicit `if`/`end`), but the genuine runtime expectations were preserved:
|
||||
arithmetic type/zero-division, index/field/memory bounds, `call.not_callable`,
|
||||
`call.arity` through a `ref` function value, non-Bool branch condition,
|
||||
capability (`permission.denied` for a foreign kernel in pure mode), unsupported
|
||||
math subset, recursion budget and the addressable-memory/collection errors.
|
||||
Optional keys: `"grants": ["foreign"]` and `"stack_limit": 24` (used for the
|
||||
recursion-depth fixture so the budget — not the host process stack — is what
|
||||
fails).
|
||||
|
||||
## CLI integration notes
|
||||
|
||||
@@ -374,13 +457,15 @@ stack — is what fails).
|
||||
|
||||
## Notes discovered while authoring (all since fixed)
|
||||
|
||||
The fixtures initially pinned three observations that were reported and then
|
||||
fixed in the implementation; the goldens below reflect the fixed behaviour:
|
||||
Two observations were reported and then fixed in the implementation; the
|
||||
goldens reflect the fixed behaviour:
|
||||
|
||||
* wire floats round-trip exactly (`serde_json/float_roundtrip` is enabled), so
|
||||
Python `math.pi * 9` keeps `28.274333882308138`;
|
||||
* the default interpreter stack budget is 128 frames so a deeply recursive
|
||||
document returns a structured `resource.exhausted` instead of exhausting the
|
||||
native debug-build stack (`--stack` can raise it deliberately);
|
||||
* an external-link call form (`> [x](https://example.com)()`) is rejected with
|
||||
`ref.unresolved`, the same code used for other unresolvable call targets.
|
||||
native debug-build stack (`--stack` can raise it deliberately).
|
||||
|
||||
The old link-form block-quote call (`> [x](https://example.com)()`) no longer
|
||||
exists: a Markdown link is a static reference, so a call is now an ordinary
|
||||
expression payload (`spec/references.md` §6.2).
|
||||
@@ -1,3 +1,3 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*1 + 2*
|
||||
*return 1 + 2*
|
||||
@@ -1,3 +1,3 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*"你好,Marqdo"*
|
||||
*return "你好,Marqdo"*
|
||||
@@ -1,3 +1,3 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*1.5 * 2.0*
|
||||
`return 1.5 * 2.0`
|
||||
@@ -1,3 +1,3 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*123456789012345678901234567890 * 10*
|
||||
`return 123456789012345678901234567890 * 10`
|
||||
@@ -1,13 +1,15 @@
|
||||
# 数学
|
||||
# @knowledge 数学
|
||||
|
||||
## 阶乘
|
||||
## @exec 阶乘
|
||||
|
||||
1. `n <= 1`
|
||||
`if n <= 1`
|
||||
|
||||
*1*
|
||||
`return 1`
|
||||
|
||||
2. `n > 1`
|
||||
`else`
|
||||
|
||||
**结果 = n * 阶乘(n=n-1)**
|
||||
`结果 = n * 阶乘(n=n-1)`
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
|
||||
`end`
|
||||
@@ -1,11 +1,13 @@
|
||||
## 斐波那契
|
||||
## @exec 斐波那契
|
||||
|
||||
1. `n < 2`
|
||||
`if n < 2`
|
||||
|
||||
*n*
|
||||
`return n`
|
||||
|
||||
2. `n >= 2`
|
||||
`else`
|
||||
|
||||
**结果 = 斐波那契(n=n-1) + 斐波那契(n=n-2)**
|
||||
`结果 = 斐波那契(n=n-1) + 斐波那契(n=n-2)`
|
||||
|
||||
*结果*
|
||||
`return 结果`
|
||||
|
||||
`end`
|
||||
@@ -1,15 +1,17 @@
|
||||
## 最大公约数
|
||||
## @exec 最大公约数
|
||||
|
||||
**a = 甲**
|
||||
`a = 甲`
|
||||
|
||||
**b = 乙**
|
||||
`b = 乙`
|
||||
|
||||
- `b > 0`
|
||||
`while b > 0`
|
||||
|
||||
**t = b**
|
||||
`t = b`
|
||||
|
||||
**b = a % b**
|
||||
`b = a % b`
|
||||
|
||||
**a = t**
|
||||
`a = t`
|
||||
|
||||
*a*
|
||||
`end`
|
||||
|
||||
`return a`
|
||||
@@ -1,13 +1,15 @@
|
||||
## 求和
|
||||
## @exec 求和
|
||||
|
||||
**i = 1**
|
||||
`i = 1`
|
||||
|
||||
**total = 0**
|
||||
`total = 0`
|
||||
|
||||
- `i <= n`
|
||||
`while i <= n`
|
||||
|
||||
**total = total + i**
|
||||
`total = total + i`
|
||||
|
||||
**i = i + 1**
|
||||
`i = i + 1`
|
||||
|
||||
*total*
|
||||
`end`
|
||||
|
||||
`return total`
|
||||
@@ -1,19 +1,23 @@
|
||||
## 嵌套
|
||||
## @exec 嵌套
|
||||
|
||||
**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*
|
||||
**total = 0**
|
||||
|
||||
`end`
|
||||
|
||||
*return total*
|
||||
@@ -1,9 +1,9 @@
|
||||
## 加法
|
||||
## @exec 加法
|
||||
|
||||
`(a: Int, b: Int)`
|
||||
`params(a: Int, b: Int)`
|
||||
|
||||
*a + b*
|
||||
`return a + b`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*加法(2, 3)*
|
||||
`return 加法(2, 3)`
|
||||
@@ -1,9 +1,9 @@
|
||||
## 默认
|
||||
## @exec 默认
|
||||
|
||||
`(x: Int, y: Int = 10)`
|
||||
`params(x: Int, y: Int = 10)`
|
||||
|
||||
*x + y*
|
||||
`return x + y`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*默认(x=2)*
|
||||
`return 默认(x=2)`
|
||||
@@ -1,9 +1,9 @@
|
||||
## 减法
|
||||
## @exec 减法
|
||||
|
||||
`(a: Int, b: Int)`
|
||||
`params(a: Int, b: Int)`
|
||||
|
||||
*a - b*
|
||||
`return a - b`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*减法(b=3, a=10)*
|
||||
`return 减法(b=3, a=10)`
|
||||
@@ -1,11 +1,11 @@
|
||||
## 加一
|
||||
## @exec 加一
|
||||
|
||||
**n = n + 1**
|
||||
`n = n + 1`
|
||||
|
||||
*n*
|
||||
`return n`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
**f = ref("#加一")**
|
||||
`f = ref("#加一")`
|
||||
|
||||
*f(n=41)*
|
||||
`return f(n=41)`
|
||||
@@ -1,9 +1,9 @@
|
||||
## 加一
|
||||
## @exec 加一
|
||||
|
||||
**n = n + 1**
|
||||
`n = n + 1`
|
||||
|
||||
*n*
|
||||
`return n`
|
||||
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*ref("#加一")*
|
||||
`return ref("#加一")`
|
||||
@@ -1,3 +1,3 @@
|
||||
## main
|
||||
## @exec main
|
||||
|
||||
*{"长度": 长度("你好"), "文本": 文本(42)}*
|
||||
`return {"长度": 长度("你好"), "文本": 文本(42)}`
|
||||
Loaded 100 of 375 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user