diff --git a/docs/adr/0067-structured-control-flow.md b/docs/adr/0067-structured-control-flow.md new file mode 100644 index 0000000..f158016 --- /dev/null +++ b/docs/adr/0067-structured-control-flow.md @@ -0,0 +1,42 @@ +# ADR-0067 — Multi-arm branches and nearest-loop control + +Status: Accepted for development. Release inclusion requires a maintainer +decision and the applicable same-SHA release gates. + +Implements stage A of [RFC-CTRL-0005](https://git.cflmy.cn/cflmy/marqdo-cli/issues/7) +as an amendment to [RFC-LANG-0002](../architecture/RFC-LANG-0002-unified-semantics.md) +and the existing [mapping](../../spec/mapping.md) and +[grammar](../../spec/expression.ebnf). Follow the frontend → IR → interpreter +boundary in the [development blueprint](../DEVELOPMENT_BLUEPRINT.md#7-rust-独立解释器ir值系统与执行内核). + +## Language and execution + +An `else if` carrier adds an arm to the existing Branch IR. Condition +evaluation is ordered and short-circuited. A separate `else` carrier followed +by `if` keeps its nested meaning. The frontend owns pairing, heading +boundaries, and diagnostics. The Markdown profile and carrier mapping stay +the same. + +A complete `break` or `continue` payload is contextual loop control. Existing +names in functions, parameters, fields, calls and expressions stay valid. +The ambiguous case is a standalone identifier read, which can be written +with parentheses. The runtime propagates a structured result to the nearest +loop, with the usual statement and iteration budgets. The loop consumes that +result within the current function. Static binding analysis only merges +reachable exits and keeps the function's initial loop-entry binding rules. + +## Public projections + +Branch arms fit Analysis v2. A project containing a loop transfer requires +Analysis v3, which preserves the envelope and adds the statement kinds +`break` and `continue`. The writer selects the required version from the +project. A v2 reader can keep reading existing output and rejects v3 at the +envelope. Trace v2 adds `control.break` and `control.continue` to its open +event vocabulary. Execution Events v1 adds the corresponding events, carrying +only the existing frame/module/span fields. The Trace digest binds to the +automatically selected Analysis document. Markdown, ABI and Host operation +versions are independent of this change. + +Stage B List iteration requires a separate decision on snapshot and binding +semantics. Release approval and ecosystem adoption are tracked outside this +implementation. diff --git a/docs/architecture/RFC-LANG-0002-unified-semantics.md b/docs/architecture/RFC-LANG-0002-unified-semantics.md index f3cf91f..9bc5bb8 100644 --- a/docs/architecture/RFC-LANG-0002-unified-semantics.md +++ b/docs/architecture/RFC-LANG-0002-unified-semantics.md @@ -604,7 +604,7 @@ import: `return x` ```` -规范语义:条件计算一次,必须是 Bool;为真执行 `if` 和 `else` 之间的载荷,否则执行 `else` 和 `end` 之间的载荷。**不能两个分支都执行。** `else` 可以省略;但 `end` 不能省略。 +各条件必须返回 Bool,每个条件在轮到该臂时求值一次。执行第一个为真的臂,或在所有条件为假时执行末尾的 `else`。没有匹配臂也没有 `else` 时直接继续。每组需要一个 `end`。 **将它排成有序列表也完全合法**: @@ -675,7 +675,9 @@ import: 匹配规则:每个 `else` 只作用于**栈顶尚未结束的 `if`**;每个 `end` 关闭最近的 `if` 或 `while`。这是一套确定的编译期配对规则,不靠缩进/列表种类/解释器猜测。 -**不支持 `else if` 专用写法(本期)**:若需要多路判断,可在 `else` 内另写一个嵌套 `if ... end`,按上述栈规则执行。若未来证明有显著可读性需求,再独立讨论 `elif`,不能开发者自行在 Parser 中宽容接受。 +多臂条件采用同一载荷内的 `else if `,允许零至多个条件臂和一个末尾 +`else`。整组由一个 `end` 闭合,各条件从左到右按需求值。两个独立载荷 +`else` 与 `if` 仍表示嵌套分支。详见 [RFC-CTRL-0005 的采纳记录](../adr/0067-structured-control-flow.md)。 ## 4.5 `while` / `end`:不依赖 bullet List 的循环 @@ -720,9 +722,10 @@ import: 严格规则: -- 每一个 `if` 恰有一个匹配的 `end`;`else` 可选且最多一个。 +- 每一个 `if` 恰有一个匹配的 `end`。可有多个 `else if` 和一个末尾 `else`。 - 每一个 `while` 恰有一个匹配的 `end`。 -- `else` 不能独立出现;不能对应 `while`;一个 `if` 不能有两个 `else`。 +- `else if` 和 `else` 只能配对栈顶的 `if`。 +- 独占载荷的 `break` 结束同一标题执行段中的最近循环,`continue` 跳至该循环的下一次条件检查。 - `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。 - 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。 - `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。 @@ -755,7 +758,7 @@ V2 推荐显式声明: | `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) | | `end if` | 语法错误 | `end` | | `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` | -| `break`、`continue`、`try` | 未纳入首版语法 | 首版不承诺 | +| `try` | 不属于当前语法 | — | | `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API | | `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 | | 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` | @@ -784,7 +787,10 @@ V2 推荐显式声明: ```ebnf (* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *) carrier_statement = "if", required_space, expr, EOF + | "else", whitespace, "if", whitespace, Expr, EOF | "else", EOF + | "break", EOF + | "continue", EOF | "while", required_space, expr, EOF | "end", EOF | "return", required_space, expr, EOF @@ -799,7 +805,7 @@ carrier_statement = "if", required_space, expr, EOF **词法必须考虑完整单词边界**:`ifdef()`、`returning()` 不是 `if`、`return` 控制语句;反之,单独的 `if`、`else` 等当作标识符使用应明确报保留字错误。为了避免自相矛盾,Tokeniser 和 Parser 均应对关键字使用同一套保留字定义。 - `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。 -- `else`、`end` 后不允许额外词元,`end if`、`else x` 均硬错误。 +- `else if` 后必须有条件;独立的 `else` 和 `end` 后无额外词元。 - `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。 - `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。 - 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。 diff --git a/spec/expression.ebnf b/spec/expression.ebnf index 089f1c0..8e84bdb 100644 --- a/spec/expression.ebnf +++ b/spec/expression.ebnf @@ -7,17 +7,18 @@ it lives; this grammar decides what that payload means. No second parser and no per-file syntax selector exists. - Implementation state: the Rust expression parser still implements the - previous, control-free grammar; this file is the target contract. See - docs/STATUS.md. + See docs/STATUS.md for implementation and release status. *) (* One payload is exactly one statement and must consume the whole payload. *) payload = statement , EOF ; statement = if_stmt + | else_if_stmt | else_stmt | while_stmt + | break_stmt + | continue_stmt | end_stmt | return_stmt | params_stmt @@ -25,28 +26,27 @@ statement = if_stmt | expression ; if_stmt = "if" , space_required , expression ; +else_if_stmt = "else" , space_required , "if" , space_required , expression ; else_stmt = "else" ; while_stmt = "while" , space_required , expression ; +break_stmt = "break" ; +continue_stmt = "continue" ; end_stmt = "end" ; return_stmt = "return" , space_required , expression ; params_stmt = "params" , "(" , [ parameter_list ] , ")" ; -(* `if`, `else`, `while`, `end`, `return` and `params` are reserved statement - words only when they are the complete first token of a payload. - `ifdef(x)` and `returning(x)` are ordinary identifiers; a bare `if` used as - an identifier is a reserved-word error. `else`/`end` take no additional - tokens: `else x` and `end if` are syntax errors. No trailing colon: - `if x > 0:` is a syntax error. No `elif`, `for`, `break`, `continue`, - `try`, empty `return`, `end if`, or semicolon-separated multi-statement - payload exists in this revision. +(* `if`, `else`, `while`, `end`, `return` and `params` are reserved words. + `break` and `continue` are contextual: a complete payload of exactly that + identifier takes precedence over the ordinary expression production. + Calls, assignments and uses inside expressions retain their identifier + meaning. Neither loop-control statement takes operands or a label. + No trailing colon, `elif`, `for`, `try`, empty `return`, `end if`, or + semicolon-separated multi-statement payload is supported. - Control pairing is not part of this grammar; it is a separate compile-time - stack in the frontend: - - every `if` has exactly one closing `end`; - - `else` is optional and at most one per `if`; - - every `while` has exactly one closing `end`; - - `else` must bind the top-of-stack `if`; `end` closes the top frame; - - a frame must close inside the same heading's direct body. + The frontend pairs statements inside each heading execution segment. + Each `if` takes zero or more `else if` arms and at most one final `else`. + Each `if` and `while` takes one closing `end`. A loop control statement + requires an open `while` in the same segment. See mapping.md. *) (* Function parameter declaration. It is legal only as the first direct diff --git a/spec/mapping.md b/spec/mapping.md index daab48b..8ea884b 100644 --- a/spec/mapping.md +++ b/spec/mapping.md @@ -23,8 +23,8 @@ Markdown→program mapping changes. 3. **Closed carriers carry one statement each.** In an Exec scope, `Strong`, `Emph` and inline `Code` are interchangeable carriers of one payload. They no longer mean execute/return/lazy respectively. -4. **Keywords inside the payload decide the operation.** `if`, `else`, `while`, - `end`, `return`, `params(...)`, assignment and expression statements. Lists, +4. **Keywords inside the payload decide the operation.** `if`, `else if`, `else`, `while`, `break`, + `continue`, `end`, `return`, `params(...)`, assignment and expression statements. Lists, block quotes and paragraphs are document containers only. 5. **Errors never fall back to prose.** Once a payload is extracted from an Exec scope it must parse fully; a failure is a diagnostic. @@ -217,8 +217,9 @@ Each extracted payload is exactly one statement, defined by `spec/expression.ebnf`: ```text -if else while end -return params(...) assignment expression +if else if else end +while break continue +return params(...) assignment expression ``` Lexical details: @@ -226,13 +227,16 @@ Lexical details: * Keywords are recognized only as complete first tokens: `ifdef(...)` and `returning` are ordinary identifiers; a bare `if`/`else` used as an identifier is a reserved-keyword error. -* `if`, `while` and `return` require a non-empty expression that consumes the - whole payload (to EOF). Trailing characters are errors. -* `else` and `end` accept no additional tokens; `else x` and `end if` are - `sem.syntax`. -* No trailing colon: `if x > 0:` is `sem.syntax`. No `elif`, `for`, `break`, - `continue`, `try`, `end if` or semicolon-separated statements in this - version. +* `if`, `else if`, `while` and `return` require whitespace followed by an + expression that consumes the whole payload. Trailing colons are + `sem.syntax`. `else` and `end` take no arguments. +* `break` and `continue` are loop control only when the complete payload is + the single identifier. `break 2` and `continue label` are syntax errors. + `break(1)`, `continue = 1` and `return break` retain their ordinary call, + assignment and expression meanings. To read a variable named `break` or + `continue` as an expression statement, parenthesize the identifier. +* `elif`, `for`, `try` and semicolon-separated statements are outside this + grammar. * `return` always requires an expression; falling off the end of a function still returns `Unit`. Explicit `return None` is available when `None` is the intended value. @@ -244,33 +248,29 @@ Lexical details: ## 5. Control-stack lowering -Within one execution segment, payloads form a token stream. Lower it with one -explicit stack: +Within one execution segment, payloads form an ordered statement stream. +The innermost open control block owns its body. -```text -open_if(cond) -> push IfFrame(cond, then=[], else=None) -statement -> append to the innermost active body -else -> require top is IfFrame with else=None; switch to else body -open_while(cond)-> push WhileFrame(cond, body=[]) -end -> require a non-empty stack; pop the top frame and lower it -at_segment_end -> require the stack to be empty -``` - -Rules: - -* `else` pairs with the top-of-stack `IfFrame` only. It may not skip an open - `while` or an inner `if`. -* At most one `else` per `if`; `else` with no open `if` is - `sem.unmatched_else`; a second `else` is `sem.duplicate_else`. -* `end` closes exactly the most recent open `if`/`while`; no match is - `sem.unmatched_end`. -* Reaching a segment boundary with an open frame is `sem.unclosed_control`, - with a related span on the opener. The compiler must not synthesize an `end`. -* `if` lower to the existing `Branch` IR; the optional `else` may lower to a - final unconditional arm while preserving left-to-right short-circuit - evaluation and executing at most one arm. `while` lowers to `Loop`; `return` - lowers to `Return` and unwinds the whole H2 function. `else`/`end` generate no - runtime instruction of their own. +* `if` opens a branch with zero or more subsequent `else if` arms and one + optional final `else`. Each arm starts in its own carrier. Two carriers + containing `else` and `if` still open a nested branch and require separate + closing `end` statements. An empty arm is legal. +* `else if` and `else` must bind the innermost open block, which must be an + `if`. A second `else` or an `else if` after `else` is a hard error. +* `end` closes the innermost open `if` or `while`. Reaching a segment + boundary with an open block is a hard error on the opener. +* All conditional arms lower to one ordered `Branch`. Evaluate conditions + left to right and execute only the first matching arm. If all are false, + execute the optional `else` body or proceed to the next statement. + Each conditional arm has its own source span. +* `while` lowers to `Loop`. `break` exits the nearest open loop and + `continue` skips the rest of its body and rechecks its condition. Both + require a loop in the same function and heading execution segment. + `return` exits the whole function, including from inside a loop. +* 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. ## 6. Functions, signatures and calls @@ -333,6 +333,10 @@ Stable machine-readable codes (the human `message`/`hint` text may change): | `sem.empty_payload` | an empty carrier in an Exec scope | | `sem.syntax` | malformed statement, missing condition/value, trailing tokens, colon, unsupported keyword | | `sem.unmatched_else` | `else` with no open `if` at the top of the stack | +| `sem.unmatched_else_if` | `else if` with no open `if` at the top of the stack | +| `sem.else_if_after_else` | `else if` after the final `else` of the same `if` | +| `sem.break_outside_loop` | `break` with no open loop in this heading segment | +| `sem.continue_outside_loop` | `continue` with no open loop in this heading segment | | `sem.duplicate_else` | a second `else` for the same `if` | | `sem.unmatched_end` | `end` with no open control frame | | `sem.unclosed_control` | an open `if`/`while` at a heading/function/file boundary |