From 1dc088b602385b2af40994eb60d5dee76f28a495 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 19:51:12 +0800 Subject: [PATCH] Verify control-flow invariants and document the development contract --- .woodpecker/main.yml | 6 +++ CHANGELOG.md | 12 ++++++ COMPATIBILITY.md | 14 +++++- README.md | 12 +++--- crates/cli/tests/analysis_trace.rs | 1 + crates/cli/tests/properties.rs | 32 ++++++++++++++ crates/marqdo-frontend/src/infer.rs | 43 ++++++++++++------- crates/marqdo-frontend/src/map.rs | 15 +++---- crates/marqdo-runtime/src/interpreter.rs | 17 ++++---- docs/STATUS.md | 15 +++++++ docs/adr/README.md | 3 +- docs/architecture/CURRENT.md | 7 +++ .../RFC-LANG-0002-unified-semantics.md | 26 ++++++++--- docs/contributor-guide.md | 1 + docs/developers/analysis-trace.md | 24 +++++++---- docs/developers/quickstart.md | 12 ++++-- docs/developers/tools.md | 5 ++- examples/control-flow.mq.md | 35 +++++++++++++++ spec/evaluation.md | 40 ++++++++--------- spec/mapping.md | 3 +- ...continue-backedge-assignment.expected.json | 5 +++ ...control-continue-backedge-assignment.mq.md | 21 +++++++++ 22 files changed, 269 insertions(+), 80 deletions(-) create mode 100644 examples/control-flow.mq.md create mode 100644 tests/negative/control-continue-backedge-assignment.expected.json create mode 100644 tests/negative/control-continue-backedge-assignment.mq.md diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index e4a6691..3849559 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -23,6 +23,12 @@ steps: # validated by the independent Python consumer and the public schema. - cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl - python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl + - ./target/debug/marqdo check examples/control-flow.mq.md --emit /tmp/control-analysis.json + - ./target/debug/marqdo run examples/control-flow.mq.md --event-stream jsonl --trace-file /tmp/control-trace.json > /tmp/control-events.jsonl + - python3 tests/consumers/analysis_v3_consumer.py /tmp/control-analysis.json + - python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-trace.json examples/tool-unknown-name/tool.json + - python3 tests/consumers/trace_consumer.py /tmp/control-analysis.json /tmp/control-trace.json + - python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl - cargo test -p marqdo-cli --test docs_consistency - cargo test -p marqdo-cli --test architecture_boundaries - python3 -m unittest discover -s tools/ci -p "test_*.py" diff --git a/CHANGELOG.md b/CHANGELOG.md index 9db6034..d225076 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,6 +173,18 @@ items are in ## Unreleased (post-beta) +### Structured control flow (RFC-CTRL-0005) + +- Added ordered `else if` arms and nearest-loop `break` and `continue`. + Bare keyword carriers take the control meaning. Calls, bindings and + identifiers within expressions retain their existing syntax. +- Inferred signatures now use reachable reads and merge assignments on + reachable control exits. A parameter inferred only from unreachable + statements may disappear. +- Analysis v3 represents loop transfers. Projects without transfers still emit + v2. Trace v2 and Execution Events v1 report the two explicit control events. +- Release inclusion remains a maintainer decision. + ### Planned changes - Fixes collected from the first beta users; see `docs/MARQDO_3_0_PRERELEASE_PLAN.md` diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 077d93f..3069e13 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -65,6 +65,18 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid | Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`, Analysis v3 or sidecar exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. | | Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. | +## Structured control flow (RFC-CTRL-0005, unreleased) + +The development branch reserves `break` and `continue` only as complete +payloads. An existing standalone identifier read can be written as +`(break)` or `(continue)`. Calls, bindings, fields and identifiers within +expressions retain their meaning. Two separate carriers containing `else` and +`if` still require two closing `end` statements. + +Parameter inference ignores reads after a definite transfer. When upgrading +a caller that passed an argument inferred solely from unreachable code, +remove the argument or keep it through an explicit `params(...)` declaration. + ## Public protocol versions | Surface | Version | Compatibility rule | @@ -72,7 +84,7 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid | Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. | | Language / CLI | `3.0.0-rc.1` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. | | `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). | -| Analysis | v2 | Consumers reject unknown majors; incompatible field changes require v3. | +| Analysis | v2/v3 on the RFC-CTRL-0005 development branch | Projects with loop transfers emit v3. Other projects emit v2. Consumers reject unknown majors. | | Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. | | Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). | | CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. | diff --git a/README.md b/README.md index e8b8e75..30dd015 100644 --- a/README.md +++ b/README.md @@ -114,10 +114,11 @@ executes anything. The Markdown profile is unchanged by the semantic rewrite. * **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`, `*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans for expressions containing `*` or `**`. -* **Statements are explicit.** `if `, `else`, `while `, `end`, - `return `, `params(n: Int)`, assignment, or an expression call. Each - carrier holds exactly one statement; every `if`/`while` is closed by `end` - inside the same heading body. +* **Statements are explicit.** An `if` may have multiple `else if` arms and + a final `else`. `while` repeats while its condition is true. `break` exits the + nearest loop and `continue` rechecks its condition. Each carrier holds one + statement and every `if` or `while` closes with `end` in the same heading + body. See the [control-flow example](examples/control-flow.mq.md). * **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the document. `> print(1)` is prose; `> **print(1)**` contains a call. * **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is @@ -231,7 +232,7 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md target-triple + sha256 artifact verification, native and isolated worker transports, brokered `fs.read`, and explicitly trusted in-process calls (`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox. -* **Public protocols** — Analysis v2 and Trace v2 with JSON Schemas and +* **Public protocols** — Analysis [v2](spec/analysis-v2.md)/[v3](spec/analysis-v3.md) and Trace v2 with JSON Schemas and independent Python consumers; Tool Protocol v1 with arbitrary command names, SemVer negotiation and whole-bundle digest verification; **Execution Events v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and @@ -373,6 +374,7 @@ tests/ conformance/negative corpus (see tests/README.md) ```bash marqdo run examples/hello.mq.md +marqdo call examples/control-flow.mq.md main marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5 marqdo run examples/multi-module/index.mq.md marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node diff --git a/crates/cli/tests/analysis_trace.rs b/crates/cli/tests/analysis_trace.rs index 764bb3e..3e4acfd 100644 --- a/crates/cli/tests/analysis_trace.rs +++ b/crates/cli/tests/analysis_trace.rs @@ -437,6 +437,7 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() { "`if 数值 < 0`", "**else if 数值 == 0**", "*else if 数值 == 1*", + "`else`", ]) { let start = source.find(carrier).unwrap(); let expected = serde_json::json!({"start": start, "end": start + carrier.len()}); diff --git a/crates/cli/tests/properties.rs b/crates/cli/tests/properties.rs index 91a42d1..756a5ad 100644 --- a/crates/cli/tests/properties.rs +++ b/crates/cli/tests/properties.rs @@ -429,3 +429,35 @@ fn narration_removal_preserves_execution() { ); assert_eq!(values[0], marqdo_value::Value::int(120)); } + +#[test] +fn control_flow_ir_is_independent_of_lists_quotes_and_prose() { + let statements = [ + "`i = 0`", + "`while true`", + "`i = i + 1`", + "`if i == 1`", + "`continue`", + "`else if i == 2`", + "`break`", + "`end`", + "`end`", + "`return i`", + ]; + let plain = format!("## @exec main\n\n{}\n", statements.join("\n\n")); + let adorned = statements + .iter() + .enumerate() + .map(|(index, statement)| match index % 3 { + 0 => format!("1. {statement} Ordinary prose follows the carrier."), + 1 => format!("> {statement}"), + _ => format!("- {statement}"), + }) + .collect::>() + .join("\n\n"); + let decorated = format!("## @exec main\n\n{adorned}\n"); + assert_eq!( + executable_projection(&plain), + executable_projection(&decorated) + ); +} diff --git a/crates/marqdo-frontend/src/infer.rs b/crates/marqdo-frontend/src/infer.rs index 27aead4..bc63285 100644 --- a/crates/marqdo-frontend/src/infer.rs +++ b/crates/marqdo-frontend/src/infer.rs @@ -87,7 +87,7 @@ struct Analyzer<'a> { known: Option<&'a BTreeSet>, reads: BTreeMap, diagnostics: Vec, - ambiguous_reported: BTreeSet, + ambiguous_reads: BTreeMap, unknown_reported: BTreeSet, } @@ -97,7 +97,7 @@ impl<'a> Analyzer<'a> { known, reads: BTreeMap::new(), diagnostics: Vec::new(), - ambiguous_reported: BTreeSet::new(), + ambiguous_reads: BTreeMap::new(), unknown_reported: BTreeSet::new(), } } @@ -107,19 +107,7 @@ impl<'a> Analyzer<'a> { return; } if state.may.contains(name) { - if !self.ambiguous_reported.contains(name) { - self.ambiguous_reported.insert(name.to_string()); - self.diagnostics.push( - Diagnostic::error( - codes::SYMBOL_UNINITIALIZED, - Some(span), - format!("`{name}` may be read before it is assigned"), - ) - .with_hint( - "assign it on every path before this read, or pass it in as a parameter", - ), - ); - } + self.ambiguous_reads.entry(name.to_string()).or_insert(span); return; } if let Some(known) = self.known { @@ -326,6 +314,22 @@ pub fn infer( } }); analyzer.analyze_stmts(stmts, initial); + for (name, span) in analyzer.ambiguous_reads { + // A reachable free read makes the name an entry parameter throughout + // an inferred function, including before or after a local rebinding. + if !analyzer.reads.contains_key(&name) { + analyzer.diagnostics.push( + Diagnostic::error( + codes::SYMBOL_UNINITIALIZED, + Some(span), + format!("`{name}` may be read before it is assigned"), + ) + .with_hint( + "assign it on every path before this read, or pass it in as a parameter", + ), + ); + } + } let mut params: Vec = analyzer .reads .iter() @@ -422,7 +426,14 @@ mod tests { }, ret("n"), ]; - assert_eq!(params(&stmts), vec!["n".to_string()]); + let inference = infer(&stmts, None, &BTreeSet::new()); + assert_eq!(inference.params[0].name, "n"); + assert_eq!(inference.params.len(), 1); + assert!( + inference.diagnostics.is_empty(), + "{:?}", + inference.diagnostics + ); } #[test] diff --git a/crates/marqdo-frontend/src/map.rs b/crates/marqdo-frontend/src/map.rs index 1b779ed..882a16e 100644 --- a/crates/marqdo-frontend/src/map.rs +++ b/crates/marqdo-frontend/src/map.rs @@ -404,20 +404,19 @@ impl Mapper { span: raw.span, }); } - if matches!( - nodes.get(*position).map(|raw| &raw.payload), - Some(Payload::Else) - ) { + if let Some(raw) = nodes + .get(*position) + .filter(|raw| matches!(raw.payload, Payload::Else)) + { *position += 1; let body = self.sequence(nodes, position, ArmContext::Default, in_loop); - // Preserve the v2 projection and observation of the fallback arm. - // An empty fallback has the same effect as ordinary fallthrough. + // An empty fallback is ordinary fallthrough. if !body.is_empty() { arms.push(BranchArm { condition: Expr::Bool(true), - condition_span: span, + condition_span: raw.span, body, - span, + span: raw.span, }); } } diff --git a/crates/marqdo-runtime/src/interpreter.rs b/crates/marqdo-runtime/src/interpreter.rs index 057f2c0..c7ce55e 100644 --- a/crates/marqdo-runtime/src/interpreter.rs +++ b/crates/marqdo-runtime/src/interpreter.rs @@ -72,7 +72,8 @@ struct BoundArgs { enum Flow { Next, Return(Value), - LoopTransfer(LoopTransfer, Span), + Break(Span), + Continue(Span), } /// Marqdo tree-walk interpreter. @@ -232,7 +233,7 @@ impl<'a> Interpreter<'a> { .and_then(|flow| match flow { Flow::Next => Ok(None), Flow::Return(value) => Ok(Some(value)), - Flow::LoopTransfer(_, span) => Err(RuntimeError::new( + Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new( ErrorCategory::Internal, Some(span), "loop control escaped its enclosing function", @@ -421,10 +422,10 @@ impl<'a> Interpreter<'a> { self.eval_expr(expr, frame)?; } Stmt::Break { span } | Stmt::Continue { span } => { - let transfer = if matches!(stmt, Stmt::Break { .. }) { - LoopTransfer::Break + let (flow, transfer) = if matches!(stmt, Stmt::Break { .. }) { + (Flow::Break(*span), LoopTransfer::Break) } else { - LoopTransfer::Continue + (Flow::Continue(*span), LoopTransfer::Continue) }; let module = frame.function.module.canonical(); self.host.record_semantic( @@ -443,7 +444,7 @@ impl<'a> Interpreter<'a> { span: *span, })?; } - return Ok(Flow::LoopTransfer(transfer, *span)); + return Ok(flow); } Stmt::Return { value, span } => { let value = self.eval_expr(value, frame)?; @@ -538,8 +539,8 @@ impl<'a> Interpreter<'a> { break; } match self.exec_stmts(program, body, frame)? { - Flow::Next | Flow::LoopTransfer(LoopTransfer::Continue, _) => {} - Flow::LoopTransfer(LoopTransfer::Break, _) => break, + Flow::Next | Flow::Continue(_) => {} + Flow::Break(_) => break, flow @ Flow::Return(_) => return Ok(flow), } }, diff --git a/docs/STATUS.md b/docs/STATUS.md index 335d928..c49f401 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -264,6 +264,21 @@ digests. The external lane ran from a temporary fixture checkout with Cargo absent from PATH. Archive SHA-256 is `8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`. +## 0.8 Structured control flow — RFC-CTRL-0005 (unreleased) + +[ADR-0067](adr/0067-structured-control-flow.md) covers the phase A implementation. +An `else if` carrier adds a condition arm to the existing branch IR. +`break` and `continue` transfer to the nearest loop in the same heading +execution segment. Binding inference joins only reachable control exits. +The [runnable example](../examples/control-flow.mq.md) uses ordinary Markdown +list containers. + +[Analysis v3](../spec/analysis-v3.md) represents the loop transfer statements. +Other documents continue to emit v2. Trace v2 and Execution Events v1 expose +the new control events. The published beta evidence applies to its original +SHA. Maintainers decide when to include phase A in a release. List iteration +is a follow-up design. + ## 1. Historical: pre-beta remote baseline and evidence > **Historical record.** Everything in §1 onward was executed before the diff --git a/docs/adr/README.md b/docs/adr/README.md index 35b767b..61495e4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -64,4 +64,5 @@ Files: `0001`–`0050`, plus: * [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful operations and child resources; * [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded - communication and cancellation. + communication and cancellation; +* [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index ebc38fc..d33bbd4 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -55,6 +55,13 @@ replace `spec/` or a recorded test log. > [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed. > See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased). +> **Structured control flow (RFC-CTRL-0005).** +> [ADR-0067](../adr/0067-structured-control-flow.md) extends the payload parser +> and branch mapper, adds nearest-loop execution transfers and makes binding +> inference path-sensitive. Analysis chooses v2 or v3 according to the +> statements it emits. The interpreter owns the transfers and reports them +> through the existing observation facade. + ## 1. Four state dimensions A claim is stated in exactly one of these dimensions. "Exists in the tree" is not diff --git a/docs/architecture/RFC-LANG-0002-unified-semantics.md b/docs/architecture/RFC-LANG-0002-unified-semantics.md index 9bc5bb8..9ae85d8 100644 --- a/docs/architecture/RFC-LANG-0002-unified-semantics.md +++ b/docs/architecture/RFC-LANG-0002-unified-semantics.md @@ -526,8 +526,11 @@ import: | 关键字 | 语法 | 含义 | 是否新增计算原语 | |---|---|---|---| | `if` | `if ` | 开始条件分支 | 否,映射已有 `Branch` | +| `else if` | `else if ` | 添加同一分支组的条件臂 | 否,复用 `Branch` | | `else` | `else` | 切换至当前 if 的否则分支 | 否 | | `while` | `while ` | 开始循环 | 否,映射已有 `Loop` | +| `break` | `break` | 退出最近一层循环 | 否,结构化控制转移 | +| `continue` | `continue` | 重新检查最近一层循环的条件 | 否,结构化控制转移 | | `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 | | `return` | `return ` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` | | `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 | @@ -823,14 +826,23 @@ TokenStream = [StatementToken(payload, span, carrier_kind, owner_unit), ...] ```text open_if(condition): - push IfFrame(cond, then=[], else=None) + push IfFrame(arms=[(condition, [])], has_else=false) on_statement(stmt): append stmt to the current innermost active body +on_else_if(condition): + require stack.top == IfFrame and not frame.has_else + append and activate a new conditional arm + on_else: - require stack.top == IfFrame and frame.else is None - switch frame active branch from then to else + require stack.top == IfFrame and not frame.has_else + append and activate the final arm + set frame.has_else + +on_break_or_continue: + require an open WhileFrame in the current segment + append the transfer to the current innermost active body open_while(condition): push WhileFrame(cond, body=[]) @@ -848,10 +860,10 @@ at_segment_end: 该算法可以保证: -- `else` 配对最近尚未结束、且位于栈顶的 `if`;不得跳过未关闭的 `while` 寻找更外层 `if`。 +- `else if` 和 `else` 配对栈顶的 `if`,且只能出现在末尾 `else` 之前;不得跳过未关闭的 `while` 寻找更外层 `if`。 - `end` 只关闭栈顶最近的一层 if/while,没有匹配结构时报错。 - `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。 -- `else` 不会成为单独一条 Runtime 指令;它只是 IR `Branch` 的分支边界。 +- `else if` 和 `else` 是 `Branch` 的臂边界。解释器将 `break` 和 `continue` 传递到最近的循环。 - 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。 **一个实现注意点**:现有 `Branch` IR 的每个 arm 带 `condition`,没有专用可选 else;首版可以将兜底 else 降为最后一个 `true` arm,并明确保持既有“从左到右找第一匹配”的短路求值。如果未来 IR 引入更明确的 `else_body`,必须同步更改 IR schema、Trace 规范和**全部下游消费者及测试**;不能在本轮暗改行为。 @@ -975,6 +987,10 @@ R(IR, imports) = ExecutableProgram or Diagnostics | `## @exec` | 缺少标题名称 | `sem.empty_unit_name` | | `**if x >**` | 语法错误,不降级文档 | `sem.syntax` | | `**else**`(无 if) | 无匹配分支 | `sem.unmatched_else` | +| `**else if true**`(无 if) | 无匹配分支 | `sem.unmatched_else_if` | +| `**else if true**`(位于末尾 else 后) | 条件臂位置非法 | `sem.else_if_after_else` | +| `**break**`(循环外) | 无匹配循环 | `sem.break_outside_loop` | +| `**continue**`(循环外) | 无匹配循环 | `sem.continue_outside_loop` | | `**else**`(重复 else) | 重复,否则分支只允许一个 | `sem.duplicate_else` | | `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` | | `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` | diff --git a/docs/contributor-guide.md b/docs/contributor-guide.md index 9276b2c..0553e04 100644 --- a/docs/contributor-guide.md +++ b/docs/contributor-guide.md @@ -49,6 +49,7 @@ marqdo-cli/ │ ├── foreign.md Python/Node kernel protocol │ ├── tool-v1.md generic external Tool Protocol v1 │ ├── analysis-v2.md public Analysis v2 projection (v1 historical) +│ ├── analysis-v3.md projection for projects with loop transfers │ ├── trace-v2.md public Trace v2 projection (v1 historical) │ └── trace-v1.md public Trace v1 event stream ├── crates/ diff --git a/docs/developers/analysis-trace.md b/docs/developers/analysis-trace.md index 1f8590b..62c930d 100644 --- a/docs/developers/analysis-trace.md +++ b/docs/developers/analysis-trace.md @@ -1,9 +1,9 @@ -# Analysis v2 and Trace v2 consumers +# Analysis and Trace v2 consumers Both are public, versioned JSON artifacts. A consumer must read them as files, never link Marqdo's Rust internals or depend on `inspect --ir`. -## Analysis v2 (static) +## Analysis v2 and v3 (static) ```bash marqdo check index.mq.md --emit ./analysis.json @@ -13,7 +13,10 @@ marqdo check index.mq.md --emit ./analysis.json independent Markdown-link check and can make `check` fail; on failure the emit target is removed. Do not generate a consumer artifact with `check --refs --emit` without checking the exit code. -- `schema: "marqdo.analysis"`, `schema_version: 2`. +- `schema: "marqdo.analysis"`. The writer emits `schema_version: 2` for + projects without loop transfers and `3` when a function body contains + `break` or `continue`. Check the version before walking function bodies. + Both versions encode `else if` in the ordered `branch.arms` array. - Top level: `producer` (`name`, `version` = product version, `markdown_profile`), `project`, `modules`, `diagnostics`. - `project`: `root_id` (`root:@` for manifest projects), @@ -26,9 +29,10 @@ marqdo check index.mq.md --emit ./analysis.json instance ids, never absolute paths. - `check` does not load plugin libraries, start kernels/providers or execute the program. -- Schemas: `spec/schemas/analysis-v2.schema.json`; contract: - `spec/analysis-v2.md`; consumers: `tests/consumers/analysis_consumer.py`, - `tests/consumers/validate_protocols.py`. +- Contracts: [Analysis v2](../../spec/analysis-v2.md) and + [Analysis v3](../../spec/analysis-v3.md). Each links to its schema. + The independent consumers in `tests/consumers/` check the version and + decode the public nodes. View must render the **original Markdown** and use Analysis only to correlate source offsets/heading units/callable mapping. Knowledge must use heading @@ -50,7 +54,8 @@ marqdo run index.mq.md --trace-file ./trace.json stale; do not bind it to the new source. `run --trace-file` does not emit Analysis itself. - Event kinds: `call.enter`, `call.exit`, `branch.eval`, `loop.iteration`, - `return`, `effect`, and possibly `trace.truncated`. Sourced events carry a + `control.break`, `control.continue`, `return`, `effect` and possibly + `trace.truncated`. Sourced events carry a module id and a UTF-8 span. - Defaults are 100,000 events / 32 MiB; `--trace-max-events` and `--trace-max-bytes` adjust them (`0` = unlimited). A consumer must tolerate @@ -80,10 +85,11 @@ marqdo run index.mq.md --event-stream jsonl --trace-file ./trace.json a complete stream. An EOF without a terminal event is `incomplete` (SIGKILL/crash/broken pipe); never synthesize success. - `run.started.source` contains `root_id` and the `sha256:` digest of the exact - Analysis v2 bytes. `--trace-file` may be combined; both writers share one + Analysis bytes. `--trace-file` may be combined; both writers share one opaque run id, and Trace v2 remains atomic and value-free. - Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`), - `return`, `branch.eval`, `loop.iteration`, `effect`. Frames identify call + `return`, `branch.eval`, `loop.iteration`, `control.break`, + `control.continue` and `effect`. Frames identify call instances, not functions; a failed argument binding creates no frame. - Values are off by default (`value_state: not_requested`). `--observe-variable NAME` and `--observe-parameter NAME` are exact-name diff --git a/docs/developers/quickstart.md b/docs/developers/quickstart.md index 558c8fe..2dc56cd 100644 --- a/docs/developers/quickstart.md +++ b/docs/developers/quickstart.md @@ -58,9 +58,15 @@ stdout and diagnostics. documentation. Unmarked headings inherit the nearest ancestor mode. - `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of one statement each. -- Control flow uses keywords: `if`/`else`/`while`/`end`, plus `params(...)` and - `return`. -- Lists, block quotes and paragraphs are presentation only. +- A branch has an `if`, any number of `else if` arms and an optional + final `else`, followed by one `end`. Each condition is evaluated in order. +- A `while` loop ends at `end`. Inside its body, `break` exits the nearest + loop and `continue` skips to its next condition check. `return` exits + the function. See the [runnable example](../../examples/control-flow.mq.md). +- Lists, block quotes and paragraphs organize the source view. For review or + linting, put each branch head at the start of an ordered list item and + place the loop head at the start of a bullet item. Nest the body visually + and close each group with its own `end` carrier. - The normative contract is [`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md), [`../../spec/mapping.md`](../../spec/mapping.md) and diff --git a/docs/developers/tools.md b/docs/developers/tools.md index aa287db..6a25e18 100644 --- a/docs/developers/tools.md +++ b/docs/developers/tools.md @@ -44,7 +44,8 @@ marqdo-view/ rejects a mismatched range at install and dispatch time with a `requires marqdo …` diagnostic. - `analysis`/`trace` are declared only if the tool consumes them; the current - core provides Analysis v2 and Trace v2. + development branch provides Analysis v2/v3 and Trace v2. Declare + `analysis: [2, 3]` when the reader handles both versions. - `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`, `remove`, `lock`, `sync`, `tool`, `help`). @@ -72,7 +73,7 @@ The tool receives: |---|---| | `MARQDO_BIN` | absolute path of the running `marqdo` executable | | `MARQDO_TOOL_PROTOCOL` | `1` | -| `MARQDO_PROTOCOL_ANALYSIS` | `2` when Analysis v2 was negotiated | +| `MARQDO_PROTOCOL_ANALYSIS` | Highest shared Analysis version. Read the artifact envelope for its actual version. | | `MARQDO_PROTOCOL_TRACE` | `2` when Trace v2 was negotiated | Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`. diff --git a/examples/control-flow.mq.md b/examples/control-flow.mq.md new file mode 100644 index 0000000..3a6e9c2 --- /dev/null +++ b/examples/control-flow.mq.md @@ -0,0 +1,35 @@ +# @knowledge 筛选读数 + +跳过无效读数,遇到停止标记时结束扫描,返回已接收读数的总和。 + +## @exec main + +`读数 = [2, -1, 3, 0, 9]` + +`位置 = 0` + +`合计 = 0` + +- `while 位置 < 长度(读数)`:逐项读取。 + + `当前 = 读数[位置]` + + `位置 = 位置 + 1` + + 1. `if 当前 < 0`:跳过无效读数。 + + `continue` + + 2. `else if 当前 == 0`:遇到停止标记。 + + `break` + + 3. `else`:累计有效读数。 + + `合计 = 合计 + 当前` + + `end` + + `end` + +`return 合计` diff --git a/spec/evaluation.md b/spec/evaluation.md index e114d5a..91da89c 100644 --- a/spec/evaluation.md +++ b/spec/evaluation.md @@ -84,12 +84,14 @@ implicit string↔number conversions; conversion builtins must be called. * `Return` — written as the `return ` statement in an executable payload — unwinds through any number of branch/loop bodies to the enclosing H2 function frame. A function that falls off the end still returns `Unit`. -* `Branch` comes from an `if`/`else`/`end` group: the condition is evaluated - once, must be `Bool`, and exactly one arm executes (the `else` arm when - present and the condition is false, otherwise the then arm). `Loop` comes - from a `while`/`end` group and re-evaluates its `Bool` condition before each - iteration. The control stack is compile-time only (`spec/mapping.md` §5); - neither `end` nor `else` is a runtime instruction. +* `Branch` evaluates `if` and `else if` conditions in order. Each reached + condition is evaluated once and must be `Bool`. At most one arm executes. + When all conditions are false, the optional `else` arm executes. +* A `while` loop evaluates its `Bool` condition before each iteration. + `Break` exits the nearest loop. `Continue` immediately returns to the + nearest loop's condition check. Both are charged as statements and + preserve the loop's budget checks. Pairing and legality are checked + within each heading execution segment (see [mapping](mapping.md)). * Imported modules only register definitions for the importing document; they have no initialization side effects and their `main` is never started. * Function calls recurse; recursion depth is bounded by the stack budget. @@ -293,22 +295,18 @@ and `resource.exhausted` (region or run budget). ## 5. Parameter inference (static, name based) -Parameters are discovered by definite-assignment data-flow analysis over the -function's control-flow graph, never from prose: +Definite-assignment analysis uses the function's structured control flow. +First-entry arguments are bound before the body executes. A read on a +reachable path with no possible prior assignment can establish an inferred +parameter. A partially assigned name without an entry binding is ambiguous +and raises `symbol.uninitialized`. With an explicit signature, unresolved +names raise `symbol.unknown`. Builtins and imported aliases are excluded +from parameter inference. -1. Build the CFG of the function body in AST order, with branch and loop - edges. Loop bodies may execute zero times. -2. Compute the set of variables *definitely assigned* on every path from the - function entry. -3. Every read of a variable that is not definitely assigned at that point and - that has no assignment anywhere in the function is a **candidate - parameter** (sorted by canonical name). -4. If a variable is assigned on some paths but read before that assignment on - others, its identity is ambiguous: emit `symbol.uninitialized` (S-04) - instead of inventing a parameter. -5. Exclude builtins, imported aliases and reserved names from inference. -6. A read that is not explained by a parameter, a local, a builtin or an - import is `symbol.unknown` with a hint (typo protection). +An unconditional transfer stops the current sequence. A branch joins only +the arms that reach its next statement. A loop may skip the body if its +condition can be false. Its normal and `continue` backedges lead to the +condition check and its `break` paths join the loop exit. Consequences: `**结果 = n * 阶乘(n=n-1)**` infers `n`; `**n = 3**` followed by reads makes `n` a local. Inferred parameters are named arguments only; an diff --git a/spec/mapping.md b/spec/mapping.md index 8ea884b..dde76ee 100644 --- a/spec/mapping.md +++ b/spec/mapping.md @@ -270,7 +270,8 @@ The innermost open control block owns its body. * Definite-assignment inference merges reachable fallthrough paths. Loop exits include condition-failure and `break` paths. `continue` and ordinary body fallthrough lead back to the condition. An abrupt transfer - stops inference from its remaining sequence. + stops inference from its remaining sequence. A reachable free read of an + inferred parameter establishes its entry binding before any reassignment. ## 6. Functions, signatures and calls diff --git a/tests/negative/control-continue-backedge-assignment.expected.json b/tests/negative/control-continue-backedge-assignment.expected.json new file mode 100644 index 0000000..b08cfd9 --- /dev/null +++ b/tests/negative/control-continue-backedge-assignment.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "symbol.uninitialized" + ] +} diff --git a/tests/negative/control-continue-backedge-assignment.mq.md b/tests/negative/control-continue-backedge-assignment.mq.md new file mode 100644 index 0000000..8cb39de --- /dev/null +++ b/tests/negative/control-continue-backedge-assignment.mq.md @@ -0,0 +1,21 @@ +## @exec main + +`params(位置: Int)` + +`while true` + +`if 位置 > 0` + +`break` + +`end` + +`结果 = 1` + +`位置 = 位置 + 1` + +`continue` + +`end` + +`return 结果`