Implement nearest-loop transfers and reachable binding analysis

This commit is contained in:
Codex committed 2026-11-23 19:41:01 +08:00
1 parent 095eef1370
commit 69c5dc8d20
40 files changed
+953 -110

No files matched your search

+26 -3
View File
@@ -1,4 +1,4 @@
//! Public Analysis v2 projection (spec/analysis-v2.md).
//! Public Analysis projection (spec/analysis-v2.md and spec/analysis-v3.md).
//!
//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node
//! kinds are the public contract, while internal Rust types may change. The
@@ -17,13 +17,24 @@ use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.analysis";
pub const SCHEMA_VERSION: u32 = 2;
pub const BASE_VERSION: u32 = 2;
/// First schema version with structured loop transfers.
pub const LOOP_CONTROL_VERSION: u32 = 3;
/// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value {
let mut modules = Vec::new();
let mut version = BASE_VERSION;
for (module_id, file) in &project.files {
let module = &file.analysis.module;
if version == BASE_VERSION
&& module
.functions
.iter()
.any(|function| has_loop_control(&function.body))
{
version = LOOP_CONTROL_VERSION;
}
modules.push(json!({
"id": module_id.to_string(),
"package_instance_id": module_id.instance,
@@ -49,7 +60,7 @@ pub fn build(project: &LoadedProject) -> Value {
});
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"schema_version": version,
"producer": {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
@@ -70,6 +81,15 @@ pub fn build(project: &LoadedProject) -> Value {
})
}
fn has_loop_control(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match stmt {
Stmt::Break { .. } | Stmt::Continue { .. } => true,
Stmt::Branch { arms, .. } => arms.iter().any(|arm| has_loop_control(&arm.body)),
Stmt::Loop { body, .. } => has_loop_control(body),
Stmt::Assign { .. } | Stmt::Eval { .. } | Stmt::Return { .. } => false,
})
}
/// Encode exactly the bytes written by `check --emit`.
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(&build(project))
@@ -293,6 +313,8 @@ fn stmt_json(stmt: &Stmt) -> Value {
"body": body.iter().map(stmt_json).collect::<Vec<_>>(),
"span": span_json(*span),
}),
Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}),
Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}),
Stmt::Return { value, span } => json!({
"kind": "return",
"value": expr_json(value),
@@ -523,6 +545,7 @@ fn collect_calls(
expr_calls(project, module, function, condition, calls);
collect_calls(project, module, function, body, calls);
}
Stmt::Break { .. } | Stmt::Continue { .. } => {}
}
}
}
+1
View File
@@ -648,6 +648,7 @@ fn collect_identifiers_stmts(stmts: &[Stmt], names: &mut std::collections::BTree
collect_identifiers_expr(condition, names);
collect_identifiers_stmts(body, names);
}
Stmt::Break { .. } | Stmt::Continue { .. } => {}
}
}
}
+38 -2
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 if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an
//! (`if`/`else if`/`else`/`while`/`break`/`continue`/`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.
@@ -28,6 +28,10 @@ pub enum PayloadStatement {
Else,
/// `while <expr>`
While(Expr),
/// Exit the closest enclosing loop.
Break,
/// Recheck the closest enclosing loop condition.
Continue,
/// `end` (no expression)
End,
/// `return <expr>`
@@ -67,7 +71,12 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
let tokens = lexer::tokenize(trimmed)?;
let first = tokens.first().expect("tokenize always returns EOF");
match first.kind {
match &first.kind {
TokenKind::Ident(name) if matches!(tokens[1].kind, TokenKind::Eof) => match name.as_str() {
"break" => Ok(PayloadStatement::Break),
"continue" => Ok(PayloadStatement::Continue),
_ => parse_statement(trimmed).map(PayloadStatement::Ordinary),
},
TokenKind::If => {
let expr = control_expression(trimmed, first.span, "if")?;
Ok(PayloadStatement::If(expr))
@@ -184,6 +193,33 @@ mod tests {
}
}
#[test]
fn loop_control_keywords_are_contextual() {
assert_eq!(
parse_payload_statement("break").unwrap(),
PayloadStatement::Break
);
assert_eq!(
parse_payload_statement("continue").unwrap(),
PayloadStatement::Continue
);
for source in [
"break(1)",
"continue = 1",
"(break)",
"break + continue",
"continue_work()",
] {
assert!(matches!(
parse_payload_statement(source).unwrap(),
PayloadStatement::Ordinary(_)
));
}
for source in ["break 2", "continue outer", "break if true"] {
assert!(parse_payload_statement(source).is_err(), "{source}");
}
}
#[test]
fn control_expressions_must_consume_the_payload() {
assert!(parse_payload_statement("if x > 0:").is_err());
+5 -1
View File
@@ -213,7 +213,10 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
}
}
Stmt::Loop { body, .. } => collect_assigned(body, out),
Stmt::Eval { .. } | Stmt::Return { .. } => {}
Stmt::Eval { .. }
| Stmt::Return { .. }
| Stmt::Break { .. }
| Stmt::Continue { .. } => {}
}
}
}
@@ -257,6 +260,7 @@ impl<'a> Binder<'a> {
self.expr(condition);
self.stmts(body);
}
Stmt::Break { .. } | Stmt::Continue { .. } => {}
}
}
}
+124 -86
View File
@@ -3,16 +3,12 @@
//! Parameters come only from free reads of executable expressions. Prose,
//! headings, inert code spans and natural language never introduce parameters.
//!
//! The analysis tracks, for every program point:
//! * `must` – variables definitely assigned on every path from entry;
//! * `may` – variables assigned on at least one path;
//! * `ambiguous` – variables that may have been assigned before the read on
//! some path but not on all paths, which makes the variable's identity
//! ambiguous (blueprint S-04) rather than silently inventing a parameter.
//! Each reachable path tracks definite and possible assignments. Sequences
//! merge fallthrough, break and continue separately, so a transfer never
//! contributes bindings from the statements it skips. A return ends the path.
//!
//! Loop bodies get special treatment: their first iteration starts from the
//! pre-loop state, so a read of an entry variable inside a loop is a parameter
//! candidate even though the body also assigns it (the classic counter case).
//! The first iteration starts from the pre-loop state. A first read before a
//! body assignment can therefore still be a parameter (the counter case).
use std::collections::{BTreeMap, BTreeSet};
@@ -45,7 +41,6 @@ pub struct ParamCandidate {
struct State {
must: BTreeSet<String>,
may: BTreeSet<String>,
ambiguous: BTreeSet<String>,
}
impl State {
@@ -53,11 +48,39 @@ impl State {
State {
must: self.must.intersection(&other.must).cloned().collect(),
may: self.may.union(&other.may).cloned().collect(),
ambiguous: self.ambiguous.union(&other.ambiguous).cloned().collect(),
}
}
}
/// Join only reachable paths. An absent path contributes no assignments.
fn merge_paths(left: &mut Option<State>, right: Option<State>) {
if let Some(right) = right {
*left = Some(match left.take() {
Some(left) => left.join(&right),
None => right,
});
}
}
#[derive(Default)]
struct Flow {
next: Option<State>,
breaks: Option<State>,
continues: Option<State>,
}
impl Flow {
fn merge(&mut self, other: Self) {
merge_paths(&mut self.next, other.next);
self.merge_loop_transfers(other.breaks, other.continues);
}
fn merge_loop_transfers(&mut self, breaks: Option<State>, continues: Option<State>) {
merge_paths(&mut self.breaks, breaks);
merge_paths(&mut self.continues, continues);
}
}
struct Analyzer<'a> {
/// Names that are parameters/locals/builtins/imports and therefore never
/// reported as unknown; used for explicit signatures.
@@ -83,7 +106,7 @@ impl<'a> Analyzer<'a> {
if state.must.contains(name) {
return;
}
if state.ambiguous.contains(name) {
if state.may.contains(name) {
if !self.ambiguous_reported.contains(name) {
self.ambiguous_reported.insert(name.to_string());
self.diagnostics.push(
@@ -169,107 +192,104 @@ impl<'a> Analyzer<'a> {
}
}
fn assign(&self, name: &str, state: &mut State) {
state.must.insert(name.to_string());
state.may.insert(name.to_string());
state.ambiguous.insert(name.to_string());
}
fn analyze_stmts(&mut self, stmts: &[Stmt], mut state: State) -> State {
fn analyze_stmts(&mut self, stmts: &[Stmt], state: State) -> Flow {
let mut flow = Flow {
next: Some(state),
..Flow::default()
};
for stmt in stmts {
state = match stmt {
let Some(mut state) = flow.next.take() else {
break;
};
flow.next = match stmt {
Stmt::Assign { target, value, .. } => {
match target {
PlaceTarget::Local { name, .. } => {
// Preserve v1 order: the RHS is read before the
// local rebinding makes the name definitely
// assigned.
self.read_expr(value, &state);
self.assign(name, &mut state);
state.must.insert(name.clone());
state.may.insert(name.clone());
}
PlaceTarget::Index { base, index, .. } => {
// Runtime order for an index place is base, index,
// RHS; reads in the place are free reads like any
// other.
// Keep the runtime's evaluation order.
self.read_expr(base, &state);
self.read_expr(index, &state);
self.read_expr(value, &state);
}
}
state
Some(state)
}
Stmt::Eval { expr, .. } => {
self.read_expr(expr, &state);
state
Some(state)
}
Stmt::Return { value, .. } => {
self.read_expr(value, &state);
state
None
}
Stmt::Break { .. } => {
merge_paths(&mut flow.breaks, Some(state));
None
}
Stmt::Continue { .. } => {
merge_paths(&mut flow.continues, Some(state));
None
}
Stmt::Branch { arms, .. } => {
let branch = self.analyze_branch(arms, state);
flow.merge_loop_transfers(branch.breaks, branch.continues);
branch.next
}
Stmt::Branch { arms, .. } => self.analyze_branch(arms, state),
Stmt::Loop {
condition, body, ..
} => {
self.read_expr(condition, &state);
// First iteration starts from the pre-loop state: body
// assignments must not flag pre-loop reads as ambiguous.
let body_out = self.analyze_stmts(
body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
State {
must: state.must.clone(),
may: body_out
.may
.union(&state.may)
.cloned()
.collect::<BTreeSet<_>>(),
ambiguous: body_out
.ambiguous
.union(&state.ambiguous)
.cloned()
.collect::<BTreeSet<_>>(),
}
}
} => self.analyze_loop(condition, body, state),
};
}
state
flow
}
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> State {
// Conditions are evaluated in order against the incoming state.
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> Flow {
let mut flow = Flow::default();
for arm in arms {
// Only earlier false conditions lead to this arm. Conditions do
// not change the assignment state of the current frame.
self.read_expr(&arm.condition, &state);
if arm.condition != Expr::Bool(false) {
flow.merge(self.analyze_stmts(&arm.body, state.clone()));
}
if arm.condition == Expr::Bool(true) {
return flow;
}
}
// The branch may match no arm, so the incoming state joins every arm's
// state; variables assigned only inside an arm stay "may assigned".
let mut joined: Option<State> = Some(State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
});
for arm in arms {
let arm_out = self.analyze_stmts(
&arm.body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
joined = Some(match joined {
None => arm_out,
Some(previous) => previous.join(&arm_out),
});
merge_paths(&mut flow.next, Some(state));
flow
}
fn analyze_loop(&mut self, condition: &Expr, body: &[Stmt], state: State) -> Option<State> {
self.read_expr(condition, &state);
if *condition == Expr::Bool(false) {
return Some(state);
}
match joined {
Some(joined) => joined,
None => state,
let Flow {
mut next,
mut breaks,
continues,
} = self.analyze_stmts(body, state.clone());
merge_paths(&mut next, continues);
// A later break can inherit assignments from an earlier iteration.
// It can also occur on the first, so only "may" gains those bindings.
if let (Some(breaks), Some(backedge)) = (&mut breaks, &next) {
breaks.may.extend(backedge.may.iter().cloned());
}
if *condition == Expr::Bool(true) {
return breaks;
}
// A false condition may be seen before any iteration or after a
// backedge. A break exits directly and a return never reaches here.
merge_paths(&mut next, Some(state));
merge_paths(&mut next, breaks);
next
}
}
@@ -294,7 +314,18 @@ pub fn infer(
names
});
let mut analyzer = Analyzer::new(known.as_ref());
analyzer.analyze_stmts(stmts, State::default());
let initial = signature.map_or_else(State::default, |signature| {
let bound: BTreeSet<_> = signature
.params
.iter()
.map(|param| param.name.clone())
.collect();
State {
must: bound.clone(),
may: bound,
}
});
analyzer.analyze_stmts(stmts, initial);
let mut params: Vec<ParamCandidate> = analyzer
.reads
.iter()
@@ -399,7 +430,7 @@ mod tests {
let stmts = vec![
Stmt::Branch {
arms: vec![BranchArm {
condition: parse_expression("true").unwrap(),
condition: parse_expression("flag").unwrap(),
condition_span: Span::new(0, 0),
body: vec![assign("x", "1")],
span: Span::new(0, 0),
@@ -409,7 +440,14 @@ mod tests {
ret("x"),
];
let inference = infer(&stmts, None, &BTreeSet::new());
assert!(inference.params.is_empty());
assert_eq!(
inference
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>(),
["flag"]
);
assert!(inference
.diagnostics
.iter()
+31 -6
View File
@@ -139,7 +139,7 @@ impl Mapper {
self.extract(block, &mut raw, true);
}
let mut position = 0;
let stmts = self.sequence(&raw, &mut position, ArmContext::Outside);
let stmts = self.sequence(&raw, &mut position, ArmContext::Outside, false);
if let Some(node) = raw.get(position) {
// The only delimiter that can stop the segment is a stray `end`.
self.error(
@@ -251,6 +251,7 @@ impl Mapper {
nodes: &[RawPayload],
position: &mut usize,
arm: ArmContext,
in_loop: bool,
) -> Vec<Stmt> {
let mut out = Vec::new();
while let Some(raw) = nodes.get(*position) {
@@ -278,12 +279,12 @@ impl Mapper {
Payload::End => break,
Payload::If(_) => {
self.executed = true;
out.push(self.branch(nodes, position));
out.push(self.branch(nodes, position, in_loop));
}
Payload::While(condition) => {
self.executed = true;
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Outside);
let body = self.sequence(nodes, position, ArmContext::Outside, true);
self.close_block(nodes, position, raw.span, "while");
out.push(Stmt::Loop {
condition: condition.clone(),
@@ -292,6 +293,30 @@ impl Mapper {
span: raw.span,
});
}
Payload::Break | Payload::Continue => {
self.executed = true;
let span = raw.span;
let (statement, code, keyword) = match raw.payload {
Payload::Break => {
(Stmt::Break { span }, codes::SEM_BREAK_OUTSIDE_LOOP, "break")
}
_ => (
Stmt::Continue { span },
codes::SEM_CONTINUE_OUTSIDE_LOOP,
"continue",
),
};
if in_loop {
out.push(statement);
} else {
self.error(
code,
Some(span),
format!("`{keyword}` requires an open loop in this heading segment"),
);
}
*position += 1;
}
Payload::Return(value) => {
self.executed = true;
out.push(Stmt::Return {
@@ -362,7 +387,7 @@ impl Mapper {
out
}
fn branch(&mut self, nodes: &[RawPayload], position: &mut usize) -> Stmt {
fn branch(&mut self, nodes: &[RawPayload], position: &mut usize, in_loop: bool) -> Stmt {
let span = nodes[*position].span;
let mut arms = Vec::new();
while let Some(raw) = nodes.get(*position) {
@@ -371,7 +396,7 @@ impl Mapper {
_ => break,
};
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Conditional);
let body = self.sequence(nodes, position, ArmContext::Conditional, in_loop);
arms.push(BranchArm {
condition: condition.clone(),
condition_span: raw.span,
@@ -384,7 +409,7 @@ impl Mapper {
Some(Payload::Else)
) {
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Default);
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.
if !body.is_empty() {
+16 -4
View File
@@ -285,11 +285,11 @@ pub enum Stmt {
/// Span of the whole statement.
span: Span,
},
/// `if`/`else` group: the first true arm wins.
/// `if`/`else if`/`else` group: the first true arm wins.
Branch {
/// Arms in AST order.
arms: Vec<BranchArm>,
/// Span of the list node.
/// Span of the opening `if` carrier.
span: Span,
},
/// `while`/`end` group.
@@ -303,6 +303,16 @@ pub enum Stmt {
/// Span of the whole `while` statement.
span: Span,
},
/// Exit the nearest loop in the enclosing function.
Break {
/// Span of the carrier.
span: Span,
},
/// Resume at the nearest loop condition in the enclosing function.
Continue {
/// Span of the carrier.
span: Span,
},
/// Return from the enclosing function (`return` statement).
Return {
/// Returned expression.
@@ -320,12 +330,14 @@ impl Stmt {
| Stmt::Eval { span, .. }
| Stmt::Branch { span, .. }
| Stmt::Loop { span, .. }
| Stmt::Break { span }
| Stmt::Continue { span }
| Stmt::Return { span, .. } => *span,
}
}
}
/// One arm of an `if`/`else` group.
/// One arm of an `if`/`else if`/`else` group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BranchArm {
/// Boolean condition expression.
@@ -334,7 +346,7 @@ pub struct BranchArm {
pub condition_span: Span,
/// Statements executed when the condition is true.
pub body: Vec<Stmt>,
/// Span of the whole list item.
/// Span of the branch carrier.
pub span: Span,
}
+22 -8
View File
@@ -71,6 +71,8 @@ struct BoundArgs {
enum Flow {
Next,
Return(Value),
Break(Span),
Continue(Span),
}
/// Marqdo tree-walk interpreter.
@@ -225,11 +227,21 @@ impl<'a> Interpreter<'a> {
id: frame_id,
};
self.depth += 1;
let result = self.exec_stmts(program, &function.body, &mut frame);
let result = self
.exec_stmts(program, &function.body, &mut frame)
.and_then(|flow| match flow {
Flow::Next => Ok(None),
Flow::Return(value) => Ok(Some(value)),
Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
"loop control escaped its enclosing function",
)),
});
self.depth -= 1;
let status = match &result {
Ok(Flow::Next) => "ok",
Ok(Flow::Return(_)) => "return",
Ok(None) => "ok",
Ok(Some(_)) => "return",
Err(error) => error.code(),
};
self.host.record_semantic(
@@ -246,8 +258,7 @@ impl<'a> Interpreter<'a> {
close?;
}
match result {
Ok(Flow::Next) => Ok(Value::Unit),
Ok(Flow::Return(value)) => Ok(value),
Ok(value) => Ok(value.unwrap_or(Value::Unit)),
Err(mut error) => {
error.attribute_module(function.id.module.canonical());
error.push_frame(
@@ -409,6 +420,8 @@ impl<'a> Interpreter<'a> {
Stmt::Eval { expr, .. } => {
self.eval_expr(expr, frame)?;
}
Stmt::Break { span } => return Ok(Flow::Break(*span)),
Stmt::Continue { span } => return Ok(Flow::Continue(*span)),
Stmt::Return { value, span } => {
let value = self.eval_expr(value, frame)?;
let module = frame.function.module.canonical();
@@ -461,7 +474,7 @@ impl<'a> Interpreter<'a> {
if condition {
match self.exec_stmts(program, &arm.body, frame)? {
Flow::Next => break,
Flow::Return(value) => return Ok(Flow::Return(value)),
flow => return Ok(flow),
}
}
}
@@ -502,8 +515,9 @@ impl<'a> Interpreter<'a> {
break;
}
match self.exec_stmts(program, body, frame)? {
Flow::Next => {}
Flow::Return(value) => return Ok(Flow::Return(value)),
Flow::Next | Flow::Continue(_) => {}
Flow::Break(_) => break,
flow @ Flow::Return(_) => return Ok(flow),
}
},
}
+4
View File
@@ -35,6 +35,10 @@ pub mod codes {
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 `break` appears outside a loop in its heading segment.
pub const SEM_BREAK_OUTSIDE_LOOP: &str = "sem.break_outside_loop";
/// A `continue` appears outside a loop in its heading segment.
pub const SEM_CONTINUE_OUTSIDE_LOOP: &str = "sem.continue_outside_loop";
/// A second `else` appears for one `if`.
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
/// `end` closes no open frame.