Lower else-if chains to ordered branch arms

This commit is contained in:
Codex committed 2026-11-23 19:36:29 +08:00
1 parent c582451a5f
commit 095eef1370
29 files changed
+385 -95

No files matched your search

+67
View File
@@ -393,3 +393,70 @@ fn trace_records_calls_effects_and_status_without_secrets() {
serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap();
assert_eq!(trace["run"]["status"], "runtime.division_by_zero");
}
#[test]
fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
let dir = TempDir::new("else-if");
let source = r#"## @exec 分类
`params(数值: Int)`
1. `if 数值 < 0`
`return -1`
2. **else if 数值 == 0**
`return 0`
> *else if 数值 == 1*
>
> `return 1`
`else`
`return 2`
`end`
"#;
write(dir.path(), "index.mq.md", source);
let output = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(output.status.success(), "{output:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["producer"]["markdown_profile"], "marqdo.md.v1");
let branch = &analysis["modules"][0]["functions"][0]["body"][0];
assert_eq!(branch["kind"], "branch");
let arms = branch["arms"].as_array().unwrap();
assert_eq!(arms.len(), 4);
for (arm, carrier) in arms.iter().zip([
"`if 数值 < 0`",
"**else if 数值 == 0**",
"*else if 数值 == 1*",
]) {
let start = source.find(carrier).unwrap();
let expected = serde_json::json!({"start": start, "end": start + carrier.len()});
assert_eq!(arm["span"], expected);
assert_eq!(arm["condition_span"], expected);
}
for (input, expected) in [("-3", "-1"), ("0", "0"), ("1", "1"), ("9", "2")] {
let output = cli(
dir.path(),
&[
"call",
"index.mq.md",
"分类",
"--arg",
&format!("数值={input}"),
"--json",
],
);
assert!(output.status.success(), "{output:?}");
let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(result["value"]["decimal"], expected);
}
}
+21 -3
View File
@@ -2,7 +2,7 @@
//!
//! One Markdown carrier holds exactly one payload. This module is the only
//! place that decides whether that payload is a control statement
//! (`if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an
//! (`if`/`else if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an
//! ordinary assignment/expression. The frontend still owns pairing the control
//! words into blocks; this module owns their lexical recognition and the
//! expression grammar they embed.
@@ -22,6 +22,8 @@ use marqdo_span::Span;
pub enum PayloadStatement {
/// `if <expr>`
If(Expr),
/// `else if <expr>`
ElseIf(Expr),
/// `else` (no expression)
Else,
/// `while <expr>`
@@ -79,6 +81,11 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
Ok(PayloadStatement::Return(expr))
}
TokenKind::Else => {
if matches!(tokens[1].kind, TokenKind::If) {
let keyword = Span::new(first.span.start, tokens[1].span.end);
let expr = control_expression(trimmed, keyword, "else if")?;
return Ok(PayloadStatement::ElseIf(expr));
}
require_only_keyword(&tokens, "else")?;
Ok(PayloadStatement::Else)
}
@@ -128,6 +135,7 @@ mod tests {
fn expr_of(source: &str) -> Expr {
match parse_payload_statement(source).expect("valid payload") {
PayloadStatement::If(expr)
| PayloadStatement::ElseIf(expr)
| PayloadStatement::While(expr)
| PayloadStatement::Return(expr) => expr,
other => panic!("unexpected payload: {other:?}"),
@@ -136,7 +144,7 @@ mod tests {
#[test]
fn parses_control_statements_with_payload_relative_spans() {
for keyword in ["if", "while", "return"] {
for keyword in ["if", "else if", "while", "return"] {
let source = format!("{keyword} x > 0");
let expr = expr_of(&source);
assert_eq!(expr.span().start, keyword.len() + 1);
@@ -159,7 +167,16 @@ mod tests {
#[test]
fn keywords_require_whitespace_and_an_expression() {
for source in ["if", "while", "return", "if(x)", "while(1)", "return(x)"] {
for source in [
"if",
"else if",
"while",
"return",
"if(x)",
"else if(x)",
"while(1)",
"return(x)",
] {
assert!(
parse_payload_statement(source).is_err(),
"{source} must be rejected"
@@ -170,6 +187,7 @@ mod tests {
#[test]
fn control_expressions_must_consume_the_payload() {
assert!(parse_payload_statement("if x > 0:").is_err());
assert!(parse_payload_statement("else if x > 0:").is_err());
assert!(parse_payload_statement("if x y").is_err());
}
+104 -92
View File
@@ -8,7 +8,7 @@
use marqdo_expression::{
parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind,
};
use marqdo_ir::{PlaceTarget, Stmt};
use marqdo_ir::{BranchArm, PlaceTarget, Stmt};
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
@@ -100,10 +100,10 @@ struct Mapper {
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stop {
End,
Else,
Eof,
enum ArmContext {
Outside,
Conditional,
Default,
}
struct RawPayload {
@@ -139,14 +139,12 @@ impl Mapper {
self.extract(block, &mut raw, true);
}
let mut position = 0;
let (stmts, stop) = self.sequence(&raw, &mut position, false, false);
if stop != Stop::Eof {
// `sequence` leaves `position` on the stray `end` payload, so the
// diagnostic points at the keyword instead of the previous
// statement. A control frame may never close across a heading.
let stmts = self.sequence(&raw, &mut position, ArmContext::Outside);
if let Some(node) = raw.get(position) {
// The only delimiter that can stop the segment is a stray `end`.
self.error(
codes::SEM_UNMATCHED_END,
raw.get(position).map(|node| node.span),
Some(node.span),
"`end` has no open `if`/`while` in this heading segment",
);
}
@@ -215,7 +213,11 @@ impl Mapper {
return;
}
if let Some(mut payload) = self.parse_payload(&text, &segments) {
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload {
if let Payload::If(expr)
| Payload::ElseIf(expr)
| Payload::While(expr)
| Payload::Return(expr) = &mut payload
{
segments.rewrite_expr(expr);
}
out.push(RawPayload {
@@ -243,100 +245,51 @@ impl Mapper {
}
}
/// Read a body up to its next delimiter without consuming that delimiter.
fn sequence(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
stop_on_else: bool,
in_else_body: bool,
) -> (Vec<Stmt>, Stop) {
arm: ArmContext,
) -> Vec<Stmt> {
let mut out = Vec::new();
while *position < nodes.len() {
let raw = &nodes[*position];
while let Some(raw) = nodes.get(*position) {
match &raw.payload {
Payload::Else => {
if stop_on_else {
return (out, Stop::Else);
Payload::Else | Payload::ElseIf(_) => {
if arm == ArmContext::Conditional {
break;
}
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) => {
self.executed = true;
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
let (code, message) = match (&raw.payload, arm) {
(Payload::Else, ArmContext::Default) => {
(codes::SEM_DUPLICATE_ELSE, "`if` has more than one `else`")
}
other => other,
(Payload::Else, _) => {
(codes::SEM_UNMATCHED_ELSE, "`else` has no open `if`")
}
(_, ArmContext::Default) => (
codes::SEM_ELSE_IF_AFTER_ELSE,
"`else if` cannot follow the final `else`",
),
(_, _) => (codes::SEM_UNMATCHED_ELSE_IF, "`else if` has no open `if`"),
};
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 });
self.error(code, Some(raw.span), message);
*position += 1;
}
Payload::End => break,
Payload::If(_) => {
self.executed = true;
out.push(self.branch(nodes, position));
}
Payload::While(condition) => {
self.executed = true;
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;
}
let body = self.sequence(nodes, position, ArmContext::Outside);
self.close_block(nodes, position, raw.span, "while");
out.push(Stmt::Loop {
condition,
condition_span: span,
condition: condition.clone(),
condition_span: raw.span,
body,
span,
span: raw.span,
});
}
Payload::Return(value) => {
@@ -406,6 +359,65 @@ impl Mapper {
}
}
}
(out, Stop::Eof)
out
}
fn branch(&mut self, nodes: &[RawPayload], position: &mut usize) -> Stmt {
let span = nodes[*position].span;
let mut arms = Vec::new();
while let Some(raw) = nodes.get(*position) {
let condition = match &raw.payload {
Payload::If(condition) | Payload::ElseIf(condition) => condition,
_ => break,
};
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Conditional);
arms.push(BranchArm {
condition: condition.clone(),
condition_span: raw.span,
body,
span: raw.span,
});
}
if matches!(
nodes.get(*position).map(|raw| &raw.payload),
Some(Payload::Else)
) {
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Default);
// Preserve the v2 projection and observation of the fallback arm.
// An empty fallback has the same effect as ordinary fallthrough.
if !body.is_empty() {
arms.push(BranchArm {
condition: Expr::Bool(true),
condition_span: span,
body,
span,
});
}
}
self.close_block(nodes, position, span, "if");
Stmt::Branch { arms, span }
}
fn close_block(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
opener: Span,
keyword: &str,
) {
if matches!(
nodes.get(*position).map(|raw| &raw.payload),
Some(Payload::End)
) {
*position += 1;
} else {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(opener),
format!("`{keyword}` is not closed by `end`"),
);
}
}
}
+4
View File
@@ -31,6 +31,10 @@ pub mod codes {
pub const SEM_SYNTAX: &str = "sem.syntax";
/// `else` does not bind an open `if`.
pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else";
/// `else if` has no matching open `if`.
pub const SEM_UNMATCHED_ELSE_IF: &str = "sem.unmatched_else_if";
/// `else if` follows the final `else`.
pub const SEM_ELSE_IF_AFTER_ELSE: &str = "sem.else_if_after_else";
/// A second `else` appears for one `if`.
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
/// `end` closes no open frame.
@@ -1,5 +1,7 @@
## @exec 符号
Regression fixture for separate else and if carriers forming nested branches.
`if n < 0`
`return -1`
@@ -0,0 +1,14 @@
{
"args": {
"数值": {
"decimal": "2",
"type": "int"
}
},
"function": "分类",
"stdout": "",
"value": {
"decimal": "2",
"type": "int"
}
}
@@ -0,0 +1,21 @@
## @exec 分类
`params(数值: Int)`
1. `if 数值 < 0`
`return -1`
2. **else if 数值 == 2**
`return 2`
3. *else if 1 / 0 > 0*
`return 3`
4. `else`
`return 4`
`end`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "7",
"type": "int"
}
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else if false`
`end`
`return 7`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "5",
"type": "int"
}
}
@@ -0,0 +1,15 @@
## @exec main
`if false`
`else if true`
This selected arm contains prose only.
`else`
`return 9`
`end`
`return 5`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.duplicate_else"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else`
`else`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.else_if_after_else"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else`
`else if true`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.unmatched_end"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else if true`
`end`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.syntax"
]
}
@@ -0,0 +1,3 @@
## @exec main
`else if`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.unmatched_else_if"
]
}
@@ -0,0 +1,11 @@
## @exec main
`if false`
`while false`
`else if true`
`end`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.syntax"
]
}
@@ -0,0 +1,7 @@
## @exec main
`if false`
`else if true:`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.unclosed_control"
]
}
@@ -0,0 +1,5 @@
## @exec main
`if false`
`else if true`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.unmatched_else_if"
]
}
@@ -0,0 +1,3 @@
## @exec main
`else if true`
@@ -0,0 +1,7 @@
{
"function": "main",
"args": {},
"codes": [
"runtime.type"
]
}
@@ -0,0 +1,7 @@
## @exec main
`if false`
`else if 1`
`end`