diff --git a/crates/cli/src/analysis.rs b/crates/cli/src/analysis.rs index 08ed436..787f87b 100644 --- a/crates/cli/src/analysis.rs +++ b/crates/cli/src/analysis.rs @@ -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, 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::>(), "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 { .. } => {} } } } diff --git a/crates/cli/src/loader.rs b/crates/cli/src/loader.rs index c2a99f0..c0c0d17 100644 --- a/crates/cli/src/loader.rs +++ b/crates/cli/src/loader.rs @@ -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 { .. } => {} } } } diff --git a/crates/marqdo-expression/src/statement.rs b/crates/marqdo-expression/src/statement.rs index 6093727..3123e6a 100644 --- a/crates/marqdo-expression/src/statement.rs +++ b/crates/marqdo-expression/src/statement.rs @@ -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 ` While(Expr), + /// Exit the closest enclosing loop. + Break, + /// Recheck the closest enclosing loop condition. + Continue, /// `end` (no expression) End, /// `return ` @@ -67,7 +71,12 @@ pub fn parse_payload_statement(source: &str) -> Result 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()); diff --git a/crates/marqdo-frontend/src/calls.rs b/crates/marqdo-frontend/src/calls.rs index 38b8713..7f68adb 100644 --- a/crates/marqdo-frontend/src/calls.rs +++ b/crates/marqdo-frontend/src/calls.rs @@ -213,7 +213,10 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet) { } } 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 { .. } => {} } } } diff --git a/crates/marqdo-frontend/src/infer.rs b/crates/marqdo-frontend/src/infer.rs index 565a754..27aead4 100644 --- a/crates/marqdo-frontend/src/infer.rs +++ b/crates/marqdo-frontend/src/infer.rs @@ -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, may: BTreeSet, - ambiguous: BTreeSet, } 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, right: Option) { + if let Some(right) = right { + *left = Some(match left.take() { + Some(left) => left.join(&right), + None => right, + }); + } +} + +#[derive(Default)] +struct Flow { + next: Option, + breaks: Option, + continues: Option, +} + +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, continues: Option) { + 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::>(), - ambiguous: body_out - .ambiguous - .union(&state.ambiguous) - .cloned() - .collect::>(), - } - } + } => 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 = 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 { + 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 = 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::>(), + ["flag"] + ); assert!(inference .diagnostics .iter() diff --git a/crates/marqdo-frontend/src/map.rs b/crates/marqdo-frontend/src/map.rs index d6d7fbc..1b779ed 100644 --- a/crates/marqdo-frontend/src/map.rs +++ b/crates/marqdo-frontend/src/map.rs @@ -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 { 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() { diff --git a/crates/marqdo-ir/src/lib.rs b/crates/marqdo-ir/src/lib.rs index cc3b784..b315293 100644 --- a/crates/marqdo-ir/src/lib.rs +++ b/crates/marqdo-ir/src/lib.rs @@ -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, - /// 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, - /// Span of the whole list item. + /// Span of the branch carrier. pub span: Span, } diff --git a/crates/marqdo-runtime/src/interpreter.rs b/crates/marqdo-runtime/src/interpreter.rs index bf07d95..c931425 100644 --- a/crates/marqdo-runtime/src/interpreter.rs +++ b/crates/marqdo-runtime/src/interpreter.rs @@ -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), } }, } diff --git a/crates/marqdo-value/src/diagnostic.rs b/crates/marqdo-value/src/diagnostic.rs index 3100481..981cf14 100644 --- a/crates/marqdo-value/src/diagnostic.rs +++ b/crates/marqdo-value/src/diagnostic.rs @@ -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. diff --git a/spec/analysis-v2.md b/spec/analysis-v2.md index 41be4a3..d3b1a31 100644 --- a/spec/analysis-v2.md +++ b/spec/analysis-v2.md @@ -222,3 +222,7 @@ When that work ships (target `3.1.x`), it must use a new protocol version source digest and the exact Analysis bytes digest; it must not rewrite v2 `units[]`. Consumers that only know v2 must keep passing the existing schema/version contract, and must reject an unknown sidecar/v3 version rather than silently ignoring it. + +Projects containing structured loop transfers use [Analysis v3](analysis-v3.md). +A v2 projection never contains those transfer statements. Multiple conditional +arms use the existing ordered `branch.arms` array. diff --git a/spec/analysis-v3.md b/spec/analysis-v3.md new file mode 100644 index 0000000..d62d34a --- /dev/null +++ b/spec/analysis-v3.md @@ -0,0 +1,27 @@ +# Marqdo Analysis v3 + +Analysis v3 extends the public [Analysis v2](analysis-v2.md) contract with +structured loop control. Its envelope keeps `schema: "marqdo.analysis"` and +sets `schema_version: 3`. The writer emits v3 if any emitted function body +contains either new statement, including inside a nested body or an imported +module. Other projects still emit v2. Multi-arm branches fit both versions. + +## Statement additions + +```json +{"kind": "break", "span": {"start": 30, "end": 37}} +{"kind": "continue", "span": {"start": 39, "end": 49}} +``` + +Both spans are half-open UTF-8 byte ranges covering the carrier in the +containing module. Walk the enclosing statement bodies to find the nearest +loop. `break` transfers to the statement after that loop. `continue` +transfers to its condition. There are no operands, labels or call edges. +Call and resource projections retain their v2 shapes. + +Consumers check the major version before traversing any function body. A v2 +reader rejects v3, while a reader that accepts both versions can share its +v2 decoding and add two statement kinds. Trace v2 binds to the version +automatically emitted for the same input via `source.analysis_digest`. + +JSON Schema: [analysis-v3.schema.json](schemas/analysis-v3.schema.json). diff --git a/spec/schemas/analysis-v3.schema.json b/spec/schemas/analysis-v3.schema.json new file mode 100644 index 0000000..7d85a78 --- /dev/null +++ b/spec/schemas/analysis-v3.schema.json @@ -0,0 +1,376 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://marqdo.dev/schemas/analysis-v3.schema.json", + "title": "Marqdo Analysis v3", + "type": "object", + "required": [ + "schema", + "schema_version", + "producer", + "project", + "modules", + "diagnostics" + ], + "properties": { + "schema": { + "const": "marqdo.analysis" + }, + "schema_version": { + "const": 3 + }, + "producer": { + "type": "object", + "required": [ + "name", + "version", + "markdown_profile" + ], + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "markdown_profile": { + "const": "marqdo.md.v1" + } + }, + "additionalProperties": true + }, + "project": { + "type": "object", + "required": [ + "root_id", + "identity_kind", + "lock_digest" + ], + "properties": { + "root_id": { + "type": "string", + "minLength": 1, + "pattern": "^(root:|sha256:[0-9a-f]{64}$)" + }, + "identity_kind": { + "enum": [ + "manifest", + "workspace_snapshot" + ] + }, + "lock_digest": { + "type": "string", + "pattern": "^(sha256:[0-9a-f]{64})?$" + } + }, + "additionalProperties": true + }, + "modules": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "package_instance_id", + "relative_path", + "source_digest", + "units", + "functions", + "imports", + "references", + "calls", + "resources" + ], + "properties": { + "id": { + "type": "string", + "pattern": "::" + }, + "package_instance_id": { + "type": "string", + "minLength": 1 + }, + "relative_path": { + "type": "string", + "minLength": 1, + "pattern": "^(?!/)(?!.*\\.\\.)" + }, + "source_digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "units": { + "type": "array" + }, + "functions": { + "type": "array", + "items": { + "type": "object", + "required": [ + "body" + ], + "properties": { + "body": { + "$ref": "#/$defs/body" + } + } + } + }, + "imports": { + "type": "array" + }, + "references": { + "type": "array" + }, + "calls": { + "type": "array" + }, + "resources": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "module_id", + "unit_id", + "kind", + "span", + "content_digest" + ], + "properties": { + "id": { + "type": "string", + "pattern": "#resource:(formula|code)-[0-9]+$" + }, + "module_id": { + "type": "string", + "pattern": "::" + }, + "unit_id": { + "type": "string", + "minLength": 1 + }, + "kind": { + "enum": [ + "formula", + "code" + ] + }, + "span": { + "type": "object", + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "integer", + "minimum": 0 + }, + "end": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": true + }, + "content_digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "language": { + "type": [ + "string", + "null" + ] + }, + "display": { + "type": "boolean" + } + }, + "additionalProperties": true + } + } + }, + "additionalProperties": true + } + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "required": [ + "module", + "relative_path", + "severity", + "code", + "message" + ], + "properties": { + "module": { + "type": "string", + "pattern": "::" + }, + "relative_path": { + "type": "string", + "minLength": 1 + }, + "span": { + "type": [ + "object", + "null" + ], + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "integer", + "minimum": 0 + }, + "end": { + "type": "integer", + "minimum": 0 + } + } + }, + "line": { + "type": [ + "integer", + "null" + ], + "minimum": 1 + }, + "column": { + "type": [ + "integer", + "null" + ], + "minimum": 1 + }, + "severity": { + "enum": [ + "error", + "warning" + ] + }, + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string", + "minLength": 1 + }, + "hints": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": true + } + } + }, + "additionalProperties": true, + "$defs": { + "body": { + "type": "array", + "items": { + "$ref": "#/$defs/statement" + } + }, + "span": { + "type": "object", + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "integer", + "minimum": 0 + }, + "end": { + "type": "integer", + "minimum": 0 + } + } + }, + "statement": { + "type": "object", + "required": [ + "kind", + "span" + ], + "properties": { + "kind": { + "enum": [ + "assign", + "expression", + "branch", + "loop", + "return", + "break", + "continue" + ] + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "allOf": [ + { + "if": { + "properties": { + "kind": { + "const": "loop" + } + } + }, + "then": { + "required": [ + "body" + ], + "properties": { + "body": { + "$ref": "#/$defs/body" + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "branch" + } + } + }, + "then": { + "required": [ + "arms" + ], + "properties": { + "arms": { + "type": "array", + "items": { + "type": "object", + "required": [ + "body" + ], + "properties": { + "body": { + "$ref": "#/$defs/body" + } + } + } + } + } + } + } + ] + } + } +} diff --git a/tests/conformance/semantics/83-while-break.expected.json b/tests/conformance/semantics/83-while-break.expected.json new file mode 100644 index 0000000..215cd8a --- /dev/null +++ b/tests/conformance/semantics/83-while-break.expected.json @@ -0,0 +1,9 @@ +{ + "args": {}, + "function": "main", + "stdout": "", + "value": { + "decimal": "7", + "type": "int" + } +} diff --git a/tests/conformance/semantics/83-while-break.mq.md b/tests/conformance/semantics/83-while-break.mq.md new file mode 100644 index 0000000..96cf984 --- /dev/null +++ b/tests/conformance/semantics/83-while-break.mq.md @@ -0,0 +1,13 @@ +## @exec main + +- `while true` + + **结果 = 6** + + `break` + + `结果 = 未到达` + + `end` + +`return 结果 + 1` diff --git a/tests/conformance/semantics/84-while-continue.expected.json b/tests/conformance/semantics/84-while-continue.expected.json new file mode 100644 index 0000000..301b92e --- /dev/null +++ b/tests/conformance/semantics/84-while-continue.expected.json @@ -0,0 +1,9 @@ +{ + "args": {}, + "function": "main", + "stdout": "", + "value": { + "decimal": "3", + "type": "int" + } +} diff --git a/tests/conformance/semantics/84-while-continue.mq.md b/tests/conformance/semantics/84-while-continue.mq.md new file mode 100644 index 0000000..303fe27 --- /dev/null +++ b/tests/conformance/semantics/84-while-continue.mq.md @@ -0,0 +1,15 @@ +## @exec main + +`位置 = 0` + +`while 位置 < 3` + +`位置 = 位置 + 1` + +`continue` + +`return 未到达` + +`end` + +`return 位置` diff --git a/tests/conformance/semantics/85-nested-loop-control.expected.json b/tests/conformance/semantics/85-nested-loop-control.expected.json new file mode 100644 index 0000000..68d09b4 --- /dev/null +++ b/tests/conformance/semantics/85-nested-loop-control.expected.json @@ -0,0 +1,9 @@ +{ + "args": {}, + "function": "main", + "stdout": "", + "value": { + "decimal": "26", + "type": "int" + } +} diff --git a/tests/conformance/semantics/85-nested-loop-control.mq.md b/tests/conformance/semantics/85-nested-loop-control.mq.md new file mode 100644 index 0000000..e3df62a --- /dev/null +++ b/tests/conformance/semantics/85-nested-loop-control.mq.md @@ -0,0 +1,41 @@ +## @exec main + +`外 = 0` + +`合计 = 0` + +`while 外 < 3` + +`外 = 外 + 1` + +`内 = 0` + +`while 内 < 4` + +`内 = 内 + 1` + +`if 内 == 1` + +`continue` + +`else if 内 == 3` + +`break` + +`end` + +`合计 = 合计 + 外` + +`end` + +`if 外 == 2` + +`continue` + +`end` + +`合计 = 合计 + 10` + +`end` + +`return 合计` diff --git a/tests/conformance/semantics/86-loop-return-and-inert-text.expected.json b/tests/conformance/semantics/86-loop-return-and-inert-text.expected.json new file mode 100644 index 0000000..94f69d8 --- /dev/null +++ b/tests/conformance/semantics/86-loop-return-and-inert-text.expected.json @@ -0,0 +1,9 @@ +{ + "args": {}, + "function": "main", + "stdout": "", + "value": { + "decimal": "42", + "type": "int" + } +} diff --git a/tests/conformance/semantics/86-loop-return-and-inert-text.mq.md b/tests/conformance/semantics/86-loop-return-and-inert-text.mq.md new file mode 100644 index 0000000..8ff4a4a --- /dev/null +++ b/tests/conformance/semantics/86-loop-return-and-inert-text.mq.md @@ -0,0 +1,25 @@ +## @exec main + +The words continue and break in this sentence are ordinary prose. + +`while true` + +`if false` + +`break` + +`else if true` + +`return 42` + +`end` + +`continue` + +`end` + +`return 未到达` + +### @knowledge Control vocabulary + +`break` and **continue** and *else if* are examples of inert text here. diff --git a/tests/conformance/semantics/87-contextual-control-identifiers.expected.json b/tests/conformance/semantics/87-contextual-control-identifiers.expected.json new file mode 100644 index 0000000..c6e8339 --- /dev/null +++ b/tests/conformance/semantics/87-contextual-control-identifiers.expected.json @@ -0,0 +1,9 @@ +{ + "args": {}, + "function": "main", + "stdout": "", + "value": { + "decimal": "5", + "type": "int" + } +} diff --git a/tests/conformance/semantics/87-contextual-control-identifiers.mq.md b/tests/conformance/semantics/87-contextual-control-identifiers.mq.md new file mode 100644 index 0000000..8f009da --- /dev/null +++ b/tests/conformance/semantics/87-contextual-control-identifiers.mq.md @@ -0,0 +1,11 @@ +## @exec break + +`params(continue: Int)` + +`return continue + 1` + +## @exec main + +`continue = break(4)` + +`return continue` diff --git a/tests/negative/control-break-in-called-function.expected.json b/tests/negative/control-break-in-called-function.expected.json new file mode 100644 index 0000000..ab85c6a --- /dev/null +++ b/tests/negative/control-break-in-called-function.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.break_outside_loop" + ] +} diff --git a/tests/negative/control-break-in-called-function.mq.md b/tests/negative/control-break-in-called-function.mq.md new file mode 100644 index 0000000..a7caf70 --- /dev/null +++ b/tests/negative/control-break-in-called-function.mq.md @@ -0,0 +1,11 @@ +## @exec main + +`while true` + +`子函数()` + +`end` + +## @exec 子函数 + +`break` diff --git a/tests/negative/control-break-operands.expected.json b/tests/negative/control-break-operands.expected.json new file mode 100644 index 0000000..8386193 --- /dev/null +++ b/tests/negative/control-break-operands.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.syntax" + ] +} diff --git a/tests/negative/control-break-operands.mq.md b/tests/negative/control-break-operands.mq.md new file mode 100644 index 0000000..cab039a --- /dev/null +++ b/tests/negative/control-break-operands.mq.md @@ -0,0 +1,7 @@ +## @exec main + +`while true` + +`break 2` + +`end` diff --git a/tests/negative/control-break-outside-loop.expected.json b/tests/negative/control-break-outside-loop.expected.json new file mode 100644 index 0000000..ab85c6a --- /dev/null +++ b/tests/negative/control-break-outside-loop.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.break_outside_loop" + ] +} diff --git a/tests/negative/control-break-outside-loop.mq.md b/tests/negative/control-break-outside-loop.mq.md new file mode 100644 index 0000000..e6cd4c7 --- /dev/null +++ b/tests/negative/control-break-outside-loop.mq.md @@ -0,0 +1,7 @@ +## @exec main + +`if true` + +`break` + +`end` diff --git a/tests/negative/control-break-partial-assignment.expected.json b/tests/negative/control-break-partial-assignment.expected.json new file mode 100644 index 0000000..b08cfd9 --- /dev/null +++ b/tests/negative/control-break-partial-assignment.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "symbol.uninitialized" + ] +} diff --git a/tests/negative/control-break-partial-assignment.mq.md b/tests/negative/control-break-partial-assignment.mq.md new file mode 100644 index 0000000..4cc80d1 --- /dev/null +++ b/tests/negative/control-break-partial-assignment.mq.md @@ -0,0 +1,19 @@ +## @exec main + +`params(标志: Bool)` + +`while true` + +`if 标志` + +`break` + +`end` + +`结果 = 1` + +`break` + +`end` + +`return 结果` diff --git a/tests/negative/control-continue-label.expected.json b/tests/negative/control-continue-label.expected.json new file mode 100644 index 0000000..8386193 --- /dev/null +++ b/tests/negative/control-continue-label.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.syntax" + ] +} diff --git a/tests/negative/control-continue-label.mq.md b/tests/negative/control-continue-label.mq.md new file mode 100644 index 0000000..07fe0dc --- /dev/null +++ b/tests/negative/control-continue-label.mq.md @@ -0,0 +1,7 @@ +## @exec main + +`while true` + +`continue outer` + +`end` diff --git a/tests/negative/control-continue-outside-loop.expected.json b/tests/negative/control-continue-outside-loop.expected.json new file mode 100644 index 0000000..aa83519 --- /dev/null +++ b/tests/negative/control-continue-outside-loop.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.continue_outside_loop" + ] +} diff --git a/tests/negative/control-continue-outside-loop.mq.md b/tests/negative/control-continue-outside-loop.mq.md new file mode 100644 index 0000000..0161be0 --- /dev/null +++ b/tests/negative/control-continue-outside-loop.mq.md @@ -0,0 +1,3 @@ +## @exec main + +`continue` diff --git a/tests/negative/control-invalid-loop-form-with-name.expected.json b/tests/negative/control-invalid-loop-form-with-name.expected.json new file mode 100644 index 0000000..8386193 --- /dev/null +++ b/tests/negative/control-invalid-loop-form-with-name.expected.json @@ -0,0 +1,5 @@ +{ + "codes": [ + "sem.syntax" + ] +} diff --git a/tests/negative/control-invalid-loop-form-with-name.mq.md b/tests/negative/control-invalid-loop-form-with-name.mq.md new file mode 100644 index 0000000..b27e9e8 --- /dev/null +++ b/tests/negative/control-invalid-loop-form-with-name.mq.md @@ -0,0 +1,7 @@ +## @exec main + +`while true` + +`break 未知` + +`end` diff --git a/tests/negative/control-loop-cross-heading.expected.json b/tests/negative/control-loop-cross-heading.expected.json new file mode 100644 index 0000000..29562ca --- /dev/null +++ b/tests/negative/control-loop-cross-heading.expected.json @@ -0,0 +1,7 @@ +{ + "codes": [ + "sem.continue_outside_loop", + "sem.unclosed_control", + "sem.unmatched_end" + ] +} diff --git a/tests/negative/control-loop-cross-heading.mq.md b/tests/negative/control-loop-cross-heading.mq.md new file mode 100644 index 0000000..8116e26 --- /dev/null +++ b/tests/negative/control-loop-cross-heading.mq.md @@ -0,0 +1,9 @@ +## @exec main + +`while true` + +### 子段 + +`continue` + +`end` diff --git a/tests/negative/control-loop-cross-knowledge-heading.expected.json b/tests/negative/control-loop-cross-knowledge-heading.expected.json new file mode 100644 index 0000000..f0dc761 --- /dev/null +++ b/tests/negative/control-loop-cross-knowledge-heading.expected.json @@ -0,0 +1,6 @@ +{ + "codes": [ + "sem.unclosed_control", + "sem.unmatched_end" + ] +} diff --git a/tests/negative/control-loop-cross-knowledge-heading.mq.md b/tests/negative/control-loop-cross-knowledge-heading.mq.md new file mode 100644 index 0000000..6dff947 --- /dev/null +++ b/tests/negative/control-loop-cross-knowledge-heading.mq.md @@ -0,0 +1,11 @@ +## @exec main + +`while true` + +### @knowledge Loop notes + +`break` `end` + +### @exec Next + +`end`