From 2c201b6c0be5721acdf316601c4fd660cd4beab9 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 05:26:47 +0000 Subject: [PATCH 01/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 298 ++++++++++++++++++++++++++++++-- src/v4/std/nat.dag | 16 +- src/v4/std/text.dag | 27 ++- 3 files changed, 316 insertions(+), 25 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 25731eb3fc6..ec826f5addc 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -1,19 +1,33 @@ // src/v4/compiler/01_tokenize.dag // Scope: generic tokenization over language lex rules. // Anchor: https://en.wikipedia.org/wiki/Lexical_analysis -// Owns: LexCharClass, LexPattern, LexRule, LexRuleSet, LexRules, Token, TokenStream, tokenize_lexical_walk_not_realized, tokenize_lex_e0_source_not_exhausted, tokenize_lexical_walk_not_realized_diagnostic, tokenize_lex_e0_source_not_exhausted_diagnostic, tokenize. -// Consumes: std collection, std diagnostic, std node, std text. -// Status: Wave-1 void-lex path realized. +// Owns: LexCharClass, LexPattern, LexRule, LexRuleSet, LexRules, Token, TokenStream, +// tokenize_lex_e0_source_not_exhausted, tokenize_lex_e0_source_not_exhausted_diagnostic, +// tokenize_lex_e1_unrecognized_char, tokenize_lex_e1_unrecognized_char_diagnostic, +// char_in_class, LexMatchResult, LexRuleApply, +// lex_match_prefix, lex_match_pattern, lex_repeat_pattern, +// lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk, +// lex_rule_token_class_member, lex_rule_set_token_class_member, tokenize. +// Consumes: std collection, std diagnostic, std node, std text, std nat, std algebra. +// Status: T-6 lexer walk realized. +// +// Rule-matching contract: +// Priority: first-rule-wins (order in LexRuleSet.rules). +// KeywordPattern: match text exactly AND assert next char is NOT IdentContinueChar. +// LiteralPattern: match text exactly, no boundary assertion. +// RepeatPattern / OneOrMorePattern: greedy (consume as much as possible). +// Error: first unrecognized character β†’ E1 diagnostic, scanning stops. module v4.compiler.tokenize import v4.std.collection { List } -import v4.std.diagnostic {Correction, Diagnostic, ExternalContractUnknown, Locus, Outcome, Textual, UserInputBoundary, WholeFile, Accepted, None, diagnostics_singleton} +import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } -import v4.std.algebra { fold_list, is_empty } -import v4.std.text { Char, String } +import v4.std.algebra { Cons, Empty, fold_list, is_empty, length, list_append, list_snoc_item } +import v4.std.text { Char, String, string_head, string_is_empty, string_tail } +import v4.std.nat { nat_lte, nat_gte } import v4.std.logic { Bool } // 🟑 coproduct dissolution β€” CP-1b item 13a; lexical data is modeled, per-arm lexer morphism witness remains gated. @@ -28,7 +42,7 @@ type LexCharClass | BlockCommentTextChar -// 🟑 coproduct dissolution β€” CP-1b item 13b; declarative parse/emit pattern data is modeled, walker witness remains gated. +// 🟑 coproduct dissolution β€” CP-1b item 13b; declarative parse/emit pattern data is modeled, bidirectional grammar carrier convergence remains gated. type LexPattern = EmptyPattern | LiteralPattern { text: String } @@ -54,7 +68,7 @@ type LexRuleSet { } -// 🟑 coproduct dissolution β€” CP-1b item 13d; modeled rule data is present, generic lexical walk remains gated. +// 🟑 coproduct dissolution β€” CP-1b item 13d; modeled rule data is present, generic lexical walk realized. type LexRules = VoidLexRules | ModeledLexRules { root: LexRuleSet } @@ -70,9 +84,20 @@ type Token { type TokenStream { tokens: List } -data tokenize_lexical_walk_not_realized: Symbol = tokenize_lexical_walk_not_realized + +// 🟑 coproduct dissolution β€” CP-1b item 13e; per-pattern match result; dissolves when LexPattern converges with GrammarExpr on single bidirectional grammar carrier. +type LexMatchResult + = LexMatchAccepted { remaining: String, lexeme: String } + | LexMatchRejected + +// 🟑 coproduct dissolution β€” CP-1b item 13f; per-rule application result; dissolves with LexPattern carrier convergence. +type LexRuleApply + = LexRuleNoMatch + | LexRuleToken { class: Symbol, lexeme: String, remaining: String } + | LexRuleTrivia { lexeme: String, remaining: String } data tokenize_lex_e0_source_not_exhausted: Symbol = tokenize_lex_e0_source_not_exhausted +data tokenize_lex_e1_unrecognized_char: Symbol = tokenize_lex_e1_unrecognized_char fn lex_rule_token_class_member(rule: LexRule, token_class: Symbol) -> Bool { @@ -94,24 +119,261 @@ fn lex_rule_set_token_class_member(rules: LexRuleSet, token_class: Symbol) -> Bo } -fn tokenize_lexical_walk_not_realized_diagnostic(at: Locus) -> Diagnostic { +fn tokenize_lex_e0_source_not_exhausted_diagnostic(at: Locus) -> Diagnostic { Diagnostic { - reason: tokenize_lexical_walk_not_realized, + reason: tokenize_lex_e0_source_not_exhausted, at: at, - correction: Unavailable { reason: ExternalContractUnknown } + correction: Unavailable { reason: UserInputBoundary } } } -fn tokenize_lex_e0_source_not_exhausted_diagnostic(at: Locus) -> Diagnostic { +fn tokenize_lex_e1_unrecognized_char_diagnostic(at: Locus) -> Diagnostic { Diagnostic { - reason: tokenize_lex_e0_source_not_exhausted, + reason: tokenize_lex_e1_unrecognized_char, at: at, correction: Unavailable { reason: UserInputBoundary } } } +fn char_in_class(c: Char, class: LexCharClass) -> Bool { + match class { + WhitespaceChar => + c == 32 || c == 9 || c == 10 || c == 13 + DigitChar => + nat_gte(a: c, b: 48) && nat_lte(a: c, b: 57) + HexDigitChar => + char_in_class(c: c, class: DigitChar) || + (nat_gte(a: c, b: 65) && nat_lte(a: c, b: 70)) || + (nat_gte(a: c, b: 97) && nat_lte(a: c, b: 102)) + IdentStartChar => + (nat_gte(a: c, b: 65) && nat_lte(a: c, b: 90)) || + (nat_gte(a: c, b: 97) && nat_lte(a: c, b: 122)) || + c == 95 + IdentContinueChar => + char_in_class(c: c, class: IdentStartChar) || + char_in_class(c: c, class: DigitChar) + StringTextChar => + c != 34 && c != 10 + LineCommentTextChar => + c != 10 + BlockCommentTextChar => + c != 42 + } +} + + +// lex_match_prefix: match a literal string prefix against source, building lexeme. +// Recurses character-by-character; terminates on prefix exhaustion or mismatch. +fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { + match string_is_empty(s: prefix) { + true => LexMatchAccepted { remaining: source, lexeme: Empty } + false => + match string_is_empty(s: source) { + true => LexMatchRejected + false => + let ph = string_head(s: prefix) + let sh = string_head(s: source) + match ph == sh { + true => + match lex_match_prefix(prefix: string_tail(s: prefix), source: string_tail(s: source)) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + LexMatchAccepted { remaining: rest, lexeme: Cons { head: sh, tail: lex } } + } + false => LexMatchRejected + } + } + } +} + + +// lex_repeat_pattern: greedy zero-or-more match of element against source. +// Terminates because each accepted iteration strictly reduces source length +// (grammar data authors must not define zero-width RepeatPattern elements). +fn lex_repeat_pattern(pattern: LexPattern, source: String, acc_lexeme: String) -> LexMatchResult { + match lex_match_pattern(pattern: pattern, source: source) { + LexMatchRejected => + LexMatchAccepted { remaining: source, lexeme: acc_lexeme } + LexMatchAccepted { remaining: rest, lexeme: consumed } => + lex_repeat_pattern( + pattern: pattern, + source: rest, + acc_lexeme: list_append(left: acc_lexeme, right: consumed) + ) + } +} + + +fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { + match pattern { + EmptyPattern => + LexMatchAccepted { remaining: source, lexeme: Empty } + LiteralPattern { text: text } => + lex_match_prefix(prefix: text, source: source) + KeywordPattern { text: text } => + match lex_match_prefix(prefix: text, source: source) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + match string_is_empty(s: rest) { + true => LexMatchAccepted { remaining: rest, lexeme: lex } + false => + match char_in_class(c: string_head(s: rest), class: IdentContinueChar) { + true => LexMatchRejected + false => LexMatchAccepted { remaining: rest, lexeme: lex } + } + } + } + CharPattern { char: expected } => + match string_is_empty(s: source) { + true => LexMatchRejected + false => + match string_head(s: source) == expected { + true => + LexMatchAccepted { + remaining: string_tail(s: source), + lexeme: Cons { head: string_head(s: source), tail: Empty } + } + false => LexMatchRejected + } + } + CharClassPattern { class: class } => + match string_is_empty(s: source) { + true => LexMatchRejected + false => + match char_in_class(c: string_head(s: source), class: class) { + true => + LexMatchAccepted { + remaining: string_tail(s: source), + lexeme: Cons { head: string_head(s: source), tail: Empty } + } + false => LexMatchRejected + } + } + SequencePattern { left: left, right: right } => + match lex_match_pattern(pattern: left, source: source) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest1, lexeme: lex1 } => + match lex_match_pattern(pattern: right, source: rest1) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest2, lexeme: lex2 } => + LexMatchAccepted { remaining: rest2, lexeme: list_append(left: lex1, right: lex2) } + } + } + ChoicePattern { left: left, right: right } => + match lex_match_pattern(pattern: left, source: source) { + LexMatchAccepted { remaining: rest, lexeme: lex } => + LexMatchAccepted { remaining: rest, lexeme: lex } + LexMatchRejected => + lex_match_pattern(pattern: right, source: source) + } + OptionalPattern { element: element } => + match lex_match_pattern(pattern: element, source: source) { + LexMatchAccepted { remaining: rest, lexeme: lex } => + LexMatchAccepted { remaining: rest, lexeme: lex } + LexMatchRejected => + LexMatchAccepted { remaining: source, lexeme: Empty } + } + RepeatPattern { element: element } => + lex_repeat_pattern(pattern: element, source: source, acc_lexeme: Empty) + OneOrMorePattern { element: element } => + match lex_match_pattern(pattern: element, source: source) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + lex_repeat_pattern(pattern: element, source: rest, acc_lexeme: lex) + } + DelimitedPattern { open: open, body: body, close: close } => + lex_match_pattern( + pattern: SequencePattern { + left: open, + right: SequencePattern { left: body, right: close } + }, + source: source + ) + } +} + + +fn lex_rule_pattern(rule: LexRule) -> LexPattern { + match rule { + TokenRule { token_class: _, pattern: p } => p + TriviaRule { pattern: p } => p + } +} + + +fn lex_try_rule(rule: LexRule, source: String) -> LexRuleApply { + match lex_match_pattern(pattern: lex_rule_pattern(rule: rule), source: source) { + LexMatchRejected => LexRuleNoMatch + LexMatchAccepted { remaining: remaining, lexeme: lexeme } => + match rule { + TokenRule { token_class: class, pattern: _ } => + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } + TriviaRule { pattern: _ } => + LexRuleTrivia { lexeme: lexeme, remaining: remaining } + } + } +} + + +fn lex_try_rules(rules: List, source: String) -> LexRuleApply { + match rules { + Empty => LexRuleNoMatch + Cons { head: rule, tail: rest } => + match lex_try_rule(rule: rule, source: source) { + LexRuleNoMatch => lex_try_rules(rules: rest, source: source) + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } + LexRuleTrivia { lexeme: lexeme, remaining: remaining } => + LexRuleTrivia { lexeme: lexeme, remaining: remaining } + } + } +} + + +// lex_walk: scan source left-to-right; emit tokens, discard trivia, error on E1. +// Termination: each non-error iteration consumes at least one character (lexeme non-empty). +fn lex_walk( + source: String, + tokens: List, + file: Symbol, + pos: Int, + rules: LexRuleSet +) -> Outcome { + match string_is_empty(s: source) { + true => + Accepted { value: TokenStream { tokens: tokens }, diagnostics: None } + false => + let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } + match lex_try_rules(rules: rules.rules, source: source) { + LexRuleNoMatch => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + LexRuleTrivia { lexeme: lexeme, remaining: remaining } => + lex_walk( + source: remaining, + tokens: tokens, + file: file, + pos: pos + length(xs: lexeme), + rules: rules + ) + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => + let new_pos = pos + length(xs: lexeme) + lex_walk( + source: remaining, + tokens: list_snoc_item( + xs: tokens, + item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: new_pos } + ), + file: file, + pos: new_pos, + rules: rules + ) + } + } +} + + fn tokenize(text: String, file: Symbol, rules: LexRules) -> Outcome { let at = Textual { file: file, @@ -120,13 +382,11 @@ fn tokenize(text: String, file: Symbol, rules: LexRules) -> Outcome match rules { VoidLexRules => if is_empty(xs: text) { - Accepted { value: TokenStream { - tokens: [] - }, diagnostics: None } + Accepted { value: TokenStream { tokens: [] }, diagnostics: None } } else { Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e0_source_not_exhausted_diagnostic(at: at)) } } - ModeledLexRules { root: _ } => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lexical_walk_not_realized_diagnostic(at: at)) } + ModeledLexRules { root: rule_set } => + lex_walk(source: text, tokens: [], file: file, pos: 0, rules: rule_set) } } diff --git a/src/v4/std/nat.dag b/src/v4/std/nat.dag index 0794e5adebf..913fddc8fe2 100644 --- a/src/v4/std/nat.dag +++ b/src/v4/std/nat.dag @@ -1,6 +1,6 @@ // src/v4/std/nat.dag // Scope: Natural numbers (Part 6 nat rows; external Natural_number anchor out of Lane-B header). -// Owns: Nat nat_cata nat_add nat_mul nat_compare is_zero nat_additive_commutative_monoid nat_semiring nat_algebra_law_subject_symbol_additive_monoid nat_algebra_law_subject_symbol_commutative_semiring nat_algebra_law_subject_symbol_inhabitant_nat NatAlgebraLawObligation nat_declared_algebra_law_obligations law_nat_add_left_identity law_nat_add_right_identity law_nat_add_associativity law_nat_mul_left_identity law_nat_mul_annihilator law_nat_mul_associativity +// Owns: Nat nat_cata nat_add nat_mul nat_compare is_zero nat_lte nat_gte nat_additive_commutative_monoid nat_semiring nat_algebra_law_subject_symbol_additive_monoid nat_algebra_law_subject_symbol_commutative_semiring nat_algebra_law_subject_symbol_inhabitant_nat NatAlgebraLawObligation nat_declared_algebra_law_obligations law_nat_add_left_identity law_nat_add_right_identity law_nat_add_associativity law_nat_mul_left_identity law_nat_mul_annihilator law_nat_mul_associativity // Consumes: v4.std.algebra v4.std.node // Status: T-3 modeled. @@ -55,6 +55,20 @@ fn is_zero(n: Nat) -> Bool { Succ { prev: _ } => false } } +fn nat_lte(a: Nat, b: Nat) -> Bool { + match nat_compare(a: a, b: b) { + Less => true + Equal => true + Greater => false + } +} +fn nat_gte(a: Nat, b: Nat) -> Bool { + match nat_compare(a: a, b: b) { + Less => false + Equal => true + Greater => true + } +} data nat_additive_commutative_monoid: CommutativeMonoid = CommutativeMonoid { monoid: Monoid { semigroup: Semigroup { magma: Magma { op: nat_add } }, diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 58adc5f7078..cf01bf17b26 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,15 +1,32 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. -// Owns: Char, String. -// Consumes: std/algebra.dag (FreeMonoid); std/nat.dag (Nat). -// Status: T-3 modeled. +// Owns: Char, String, string_is_empty, string_head, string_tail. +// Consumes: std/algebra.dag (FreeMonoid, Cons, Empty, is_empty); std/logic.dag (Bool); std/nat.dag (Nat, Zero). +// Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode module v4.std.text -import v4.std.algebra { FreeMonoid } -import v4.std.nat { Nat } +import v4.std.algebra { Cons, Empty, FreeMonoid, is_empty } +import v4.std.logic { Bool } +import v4.std.nat { Nat, Zero } type Char = Nat type String = FreeMonoid +fn string_is_empty(s: String) -> Bool { + is_empty(xs: s) +} +// string_head: first character. Caller must check string_is_empty first; returns Zero on empty. +fn string_head(s: String) -> Char { + match s { + Empty => Zero + Cons { head: c, tail: _ } => c + } +} +fn string_tail(s: String) -> String { + match s { + Empty => Empty + Cons { head: _, tail: t } => t + } +} From 853b1e8f4ffcf89ba8fd505632873915a4621dc7 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 05:41:24 +0000 Subject: [PATCH 02/66] T-6/T-7/T-34: v4 lexer walk, PEG parse walk, Wave-1 evaluator hooks Pre-req A: nat_lte/nat_gte already landed in nat.dag; string_head/string_tail/string_is_empty in text.dag. Pre-req B + T-6 (01_tokenize.dag): add char_in_class, lex_match_prefix, lex_match_pattern, lex_repeat_pattern, lex_try_rule/lex_try_rules, lex_walk/lex_walk_step; replace ModeledLexRules stub with full first-rule-wins greedy lexer walk with E1 fail-closed on unrecognized char. T-7 (02_parse.dag): redesign ParseExprResult with captured: Node field; add sync_tokens: Set to GrammarRoot; add static left-recursion guard; implement parse_expr recursive-descent PEG walk with parse_repeat error recovery via sync-token skip. T-34 (v4_evaluator.dag): replace all outcome_rejected Wave-1 hook stubs with RuntimeUnit-based implementations covering represent_literal, call_primitive, choose_branch, step_loop, call, transfer, terminal_value. Addendum: add dag_wave1_sync_tokens() and dag_language_model_wave1_modeled() to dag.dag so T-7 parser walk is reachable from the pipeline via ModeledGrammar. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 64 ++--- src/v4/compiler/02_parse.dag | 307 +++++++++++++++++++++-- src/v4/extdeps/languages/dag.dag | 34 ++- src/v4/extdeps/runtimes/v4_evaluator.dag | 36 ++- 4 files changed, 371 insertions(+), 70 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index ec826f5addc..dad55edccca 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -6,7 +6,7 @@ // tokenize_lex_e1_unrecognized_char, tokenize_lex_e1_unrecognized_char_diagnostic, // char_in_class, LexMatchResult, LexRuleApply, // lex_match_prefix, lex_match_pattern, lex_repeat_pattern, -// lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk, +// lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk_step, lex_walk, // lex_rule_token_class_member, lex_rule_set_token_class_member, tokenize. // Consumes: std collection, std diagnostic, std node, std text, std nat, std algebra. // Status: T-6 lexer walk realized. @@ -23,7 +23,7 @@ module v4.compiler.tokenize import v4.std.collection { List } -import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, UserInputBoundary, WholeFile, diagnostics_singleton } +import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, Unavailable, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } import v4.std.algebra { Cons, Empty, fold_list, is_empty, length, list_append, list_snoc_item } import v4.std.text { Char, String, string_head, string_is_empty, string_tail } @@ -173,14 +173,12 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { match string_is_empty(s: source) { true => LexMatchRejected false => - let ph = string_head(s: prefix) - let sh = string_head(s: source) - match ph == sh { + match string_head(s: prefix) == string_head(s: source) { true => match lex_match_prefix(prefix: string_tail(s: prefix), source: string_tail(s: source)) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: rest, lexeme: lex } => - LexMatchAccepted { remaining: rest, lexeme: Cons { head: sh, tail: lex } } + LexMatchAccepted { remaining: rest, lexeme: Cons { head: string_head(s: source), tail: lex } } } false => LexMatchRejected } @@ -332,6 +330,34 @@ fn lex_try_rules(rules: List, source: String) -> LexRuleApply { } +fn lex_walk_step( + source: String, + tokens: List, + file: Symbol, + pos: Int, + rules: LexRuleSet +) -> Outcome { + let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } + match lex_try_rules(rules: rules.rules, source: source) { + LexRuleNoMatch => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + LexRuleTrivia { lexeme: lexeme, remaining: remaining } => + lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules) + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => + lex_walk( + source: remaining, + tokens: list_snoc_item( + xs: tokens, + item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } + ), + file: file, + pos: pos + length(xs: lexeme), + rules: rules + ) + } +} + + // lex_walk: scan source left-to-right; emit tokens, discard trivia, error on E1. // Termination: each non-error iteration consumes at least one character (lexeme non-empty). fn lex_walk( @@ -345,31 +371,7 @@ fn lex_walk( true => Accepted { value: TokenStream { tokens: tokens }, diagnostics: None } false => - let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } - match lex_try_rules(rules: rules.rules, source: source) { - LexRuleNoMatch => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - LexRuleTrivia { lexeme: lexeme, remaining: remaining } => - lex_walk( - source: remaining, - tokens: tokens, - file: file, - pos: pos + length(xs: lexeme), - rules: rules - ) - LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => - let new_pos = pos + length(xs: lexeme) - lex_walk( - source: remaining, - tokens: list_snoc_item( - xs: tokens, - item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: new_pos } - ), - file: file, - pos: new_pos, - rules: rules - ) - } + lex_walk_step(source: source, tokens: tokens, file: file, pos: pos, rules: rules) } } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 6960820f3a0..00598005be4 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -1,19 +1,27 @@ // src/v4/compiler/02_parse.dag // Scope: generic parsing over language grammar rules. // Anchor: https://en.wikipedia.org/wiki/Parsing -// Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, Node projection functions. -// Consumes: std diagnostic, std node, compiler tokenize. -// Status: Wave-1 void-grammar path realized; syntactic grammar data is typed, Node is projection only. +// Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, +// Node projection functions, left-recursion check, error-recovery helpers. +// Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. +// Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. +// +// Walker semantics: +// PEG ordered choice: Choice tries left first; left wins if it matches. +// Grammar data must be non-left-recursive; checked at parse() entry. +// Repeat error recovery: on element failure with diagnostics, skip to next sync token. +// sync_tokens are declaration-start keywords (language-specific; declared on GrammarRoot). module v4.compiler.parse import v4.compiler.tokenize { Token, TokenStream } -import v4.std.diagnostic {Correction, Diagnostic, ExternalContractUnknown, Locus, Outcome, port_locus, UserInputBoundary, Accepted, None, diagnostics_singleton} +import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_formed } -import v4.std.collection { List } -import v4.std.algebra { Empty, fold_list, is_empty, length, list_snoc_item } +import v4.std.collection { List, Set } +import v4.std.algebra { Cons, Empty, fold_list, fold_list_right, is_empty, length, list_append, list_snoc_item } +import v4.std.logic { Bool } // 🟑 gated β€” feature:CP-1b-bidirectional-grammar-carrier β€” bind TASKS.md T-6/T-7 β€” dissolve-on: GrammarExpr converges with LexPattern on single declarative bidirectional grammar model; forbidden: parallel production algebras without explicit structural justification. @@ -36,6 +44,7 @@ type GrammarProduction { type GrammarRoot { start: Symbol productions: List + sync_tokens: Set } @@ -47,17 +56,16 @@ type Grammar type ParseTree = Node -// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; bound task: src/v4/TASKS.md#t-7-compiler02_parsedag; follow-up: dissolve when parse_expr recursive walk lands with termination/ambiguity certificate (see parse_expr gate at line 298). -type ParseExprResult - = ParseExprAccepted { remaining: List } - | ParseExprRejected - - -// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; bound task: src/v4/TASKS.md#t-7-compiler02_parsedag; follow-up: dissolve when production lookup is indexed at parse-walk realization instead of linear fold over GrammarRoot.productions. +// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; follow-up: dissolve when production lookup is indexed at parse-walk realization instead of linear fold over GrammarRoot.productions. type GrammarProductionLookup = GrammarProductionFound { production: GrammarProduction } | GrammarProductionMissing +// ParseExprResult: per-expression match result carrying captured Node and accumulated diagnostics. +type ParseExprResult + = ParseExprAccepted { remaining: List, captured: Node, diagnostics: List } + | ParseExprRejected { diagnostics: List } + data grammar_terminal_token_class_node_projection: Symbol = grammar_terminal_token_class_node_projection data grammar_nonterminal_production_node_projection: Symbol = grammar_nonterminal_production_node_projection @@ -81,6 +89,10 @@ data parse_grammar_not_well_formed: Symbol = parse_grammar_not_well_formed data parse_g0_tokens_remain: Symbol = parse_g0_tokens_remain +data parse_grammar_left_recursive: Symbol = parse_grammar_left_recursive + +data parse_e1_repeat_recovery: Symbol = parse_e1_repeat_recovery + fn parse_walk_not_realized_diagnostic(at: Locus) -> Diagnostic { Diagnostic { @@ -109,6 +121,24 @@ fn parse_g0_tokens_remain_diagnostic(at: Locus) -> Diagnostic { } +fn parse_grammar_left_recursive_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_grammar_left_recursive, + at: at, + correction: Unavailable { reason: ExternalContractUnknown } + } +} + + +fn parse_e1_repeat_recovery_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_e1_repeat_recovery, + at: at, + correction: Unavailable { reason: UserInputBoundary } + } +} + + fn grammar_atom(identity: Symbol) -> Node { Node { kind: TypeNode { @@ -289,23 +319,248 @@ fn grammar_lookup_production(root: GrammarRoot, name: Symbol) -> GrammarProducti } +// --- Left-recursion detection --- + +// expr_starts_with_nonterminal: true iff the leftmost position of expr is Nonterminal { name }. +fn expr_starts_with_nonterminal(expr: GrammarExpr, name: Symbol) -> Bool { + match expr { + Terminal { token_class: _ } => false + Nonterminal { production: p } => p == name + Sequence { left: left, right: _ } => expr_starts_with_nonterminal(expr: left, name: name) + Choice { left: left, right: right } => + expr_starts_with_nonterminal(expr: left, name: name) || + expr_starts_with_nonterminal(expr: right, name: name) + Optional { element: element } => expr_starts_with_nonterminal(expr: element, name: name) + Repeat { element: element } => expr_starts_with_nonterminal(expr: element, name: name) + } +} + + +fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { + fold_list( + xs: root.productions, + empty: false, + cons: fn(acc, p) { + acc || expr_starts_with_nonterminal(expr: p.expression, name: p.name) + } + ) +} + + +// --- Diagnostic list helpers --- + +fn parse_diags_to_diagnostics(diags: List) -> Diagnostics { + match diags { + Empty => None + Cons { head: h, tail: t } => Some { diagnostics: NonEmptyDiagnostics { head: h, tail: t } } + } +} + + +fn parse_diags_to_non_empty(diags: List, default: Diagnostic) -> NonEmptyDiagnostics { + match diags { + Empty => NonEmptyDiagnostics { head: default, tail: [] } + Cons { head: h, tail: t } => NonEmptyDiagnostics { head: h, tail: t } + } +} + + +// --- Parse walk helpers --- + +fn parse_repeat_captured_node(acc_nodes: List) -> Node { + Node { + kind: TypeNode { connective: Conj }, + children: fold_list_right( + xs: acc_nodes, + empty: [], + snoc: fn(acc, n) { + Cons { + head: Edge { + label: Named { name: grammar_repeat_element_node_projection }, + target: n + }, + tail: acc + } + } + ) + } +} + + +// Skip tokens until a sync token is found (inclusive β€” returns stream starting at sync token). +fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List { + match tokens { + Empty => Empty + Cons { head: tok, tail: rest } => + match sync_tokens.member(tok.class) { + true => tokens + false => parse_skip_to_sync(tokens: rest, sync_tokens: sync_tokens) + } + } +} + + +fn parse_repeat_error_recover( + element: GrammarExpr, + tokens: List, + root: GrammarRoot, + acc_nodes: List, + acc_diags: List, + failed_diags: List +) -> ParseExprResult { + let at = port_locus(port: parse_stage_locus_port) + let synced = parse_skip_to_sync(tokens: tokens, sync_tokens: root.sync_tokens) + let new_diags = list_append( + left: acc_diags, + right: list_append( + left: failed_diags, + right: Cons { head: parse_e1_repeat_recovery_diagnostic(at: at), tail: Empty } + ) + ) + match length(xs: synced) != length(xs: tokens) { + true => + parse_repeat(element: element, tokens: synced, root: root, acc_nodes: acc_nodes, acc_diags: new_diags) + false => + ParseExprAccepted { + remaining: tokens, + captured: parse_repeat_captured_node(acc_nodes: acc_nodes), + diagnostics: new_diags + } + } +} + + +// parse_repeat: greedy zero-or-more, with error recovery via sync-token skip. +// Termination: each successful iteration reduces token count; each error recovery +// either skips tokens (reducing count) or stops (no skip = no progress). +fn parse_repeat( + element: GrammarExpr, + tokens: List, + root: GrammarRoot, + acc_nodes: List, + acc_diags: List +) -> ParseExprResult { + match parse_expr(expr: element, tokens: tokens, root: root) { + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => + parse_repeat( + element: element, + tokens: rest, + root: root, + acc_nodes: list_snoc_item(xs: acc_nodes, item: cap), + acc_diags: list_append(left: acc_diags, right: diags) + ) + ParseExprRejected { diagnostics: failed_diags } => + match is_empty(xs: failed_diags) { + true => + ParseExprAccepted { + remaining: tokens, + captured: parse_repeat_captured_node(acc_nodes: acc_nodes), + diagnostics: acc_diags + } + false => + parse_repeat_error_recover( + element: element, + tokens: tokens, + root: root, + acc_nodes: acc_nodes, + acc_diags: acc_diags, + failed_diags: failed_diags + ) + } + } +} + + +// parse_expr: recursive-descent walk over a GrammarExpr against a token stream. +// Mutual recursion with parse_repeat (Repeat element iteration). fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> ParseExprResult { - // 🟑 gated β€” feature:T-7-parse-walk-realization β€” bind TASKS.md T-7 β€” dissolve-on: T-8/T-9 normalize/resolve integrates parse_expr into pipeline fold; bootstrap lacks fold-on-demand token consumption and termination certificates for recursive descent - ParseExprRejected + match expr { + Terminal { token_class: class } => + match tokens { + Empty => ParseExprRejected { diagnostics: [] } + Cons { head: tok, tail: rest } => + match tok.class == class { + true => + ParseExprAccepted { + remaining: rest, + captured: Node { + kind: TypeNode { connective: Atom { identity: tok.class } }, + children: [] + }, + diagnostics: [] + } + false => ParseExprRejected { diagnostics: [] } + } + } + Nonterminal { production: prod_name } => + match grammar_lookup_production(root: root, name: prod_name) { + GrammarProductionMissing => + ParseExprRejected { diagnostics: [] } + GrammarProductionFound { production: production } => + parse_expr(expr: production.expression, tokens: tokens, root: root) + } + Sequence { left: left, right: right } => + match parse_expr(expr: left, tokens: tokens, root: root) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: rest1, captured: cap1, diagnostics: diags1 } => + match parse_expr(expr: right, tokens: rest1, root: root) { + ParseExprRejected { diagnostics: diags2 } => + ParseExprRejected { diagnostics: list_append(left: diags1, right: diags2) } + ParseExprAccepted { remaining: rest2, captured: cap2, diagnostics: diags2 } => + ParseExprAccepted { + remaining: rest2, + captured: Node { + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_sequence_left_node_projection, target: cap1), + grammar_named_edge(name: grammar_sequence_right_node_projection, target: cap2) + ] + }, + diagnostics: list_append(left: diags1, right: diags2) + } + } + } + Choice { left: left, right: right } => + match parse_expr(expr: left, tokens: tokens, root: root) { + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } + ParseExprRejected { diagnostics: _ } => + parse_expr(expr: right, tokens: tokens, root: root) + } + Optional { element: element } => + match parse_expr(expr: element, tokens: tokens, root: root) { + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } + ParseExprRejected { diagnostics: _ } => + ParseExprAccepted { + remaining: tokens, + captured: grammar_empty_node(), + diagnostics: [] + } + } + Repeat { element: element } => + parse_repeat(element: element, tokens: tokens, root: root, acc_nodes: [], acc_diags: []) + } } fn parse_production(tokens: List, root: GrammarRoot, production: GrammarProduction) -> Outcome { let at = port_locus(port: parse_stage_locus_port) match parse_expr(expr: production.expression, tokens: tokens, root: root) { - ParseExprAccepted { remaining: remaining } => + ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { - Accepted { value: production.emitted, diagnostics: None } + Accepted { value: captured, diagnostics: parse_diags_to_diagnostics(diags: diags) } } else { Rejected { diagnostics: diagnostics_singleton(d: parse_g0_tokens_remain_diagnostic(at: at)) } } - ParseExprRejected => - Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + ParseExprRejected { diagnostics: diags } => + Rejected { + diagnostics: parse_diags_to_non_empty( + diags: diags, + default: parse_walk_not_realized_diagnostic(at: at) + ) + } } } @@ -325,11 +580,15 @@ fn parse(tokens: TokenStream, grammar: Grammar) -> Outcome { Rejected { diagnostics: diagnostics_singleton(d: parse_g0_tokens_remain_diagnostic(at: at)) } } ModeledGrammar { root: root } => - match grammar_lookup_production(root: root, name: root.start) { - GrammarProductionFound { production: start } => - parse_production(tokens: tokens.tokens, root: root, production: start) - GrammarProductionMissing => - Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + if grammar_has_left_recursion(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_left_recursive_diagnostic(at: at)) } + } else { + match grammar_lookup_production(root: root, name: root.start) { + GrammarProductionFound { production: start } => + parse_production(tokens: tokens.tokens, root: root, production: start) + GrammarProductionMissing => + Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + } } } } diff --git a/src/v4/extdeps/languages/dag.dag b/src/v4/extdeps/languages/dag.dag index 1e3b5f1ec82..3e802825306 100644 --- a/src/v4/extdeps/languages/dag.dag +++ b/src/v4/extdeps/languages/dag.dag @@ -1,9 +1,9 @@ // src/v4/extdeps/languages/dag.dag // // Scope: gunbc `.dag` LanguageModel (typed lex + grammar model; Shape A). -// Owns: DagLanguageModel; dag_c3_surface_sugar_*; dag_language_model_surface_id; dag_token_*; dag_production_*; dag_surface_*; dag_wave1_*; dag_language_model_wave1_void; dag_language_model_surface_empty_prelude; dag_language_model_canonical_symbols; dag_language_model_surface_prelude_atoms; dag_language_model_empty_canonical_symbol_set. -// Consumes: compiler/tokenize.dag, compiler/parse.dag, std/collection.dag, std/node.dag. -// Status: T-6 modeled lex rules; T-7 grammar remains scaffolded. +// Owns: DagLanguageModel; dag_c3_surface_sugar_*; dag_language_model_surface_id; dag_token_*; dag_production_*; dag_surface_*; dag_wave1_*; dag_language_model_wave1_void; dag_language_model_wave1_modeled; dag_language_model_surface_empty_prelude; dag_language_model_canonical_symbols; dag_language_model_surface_prelude_atoms; dag_language_model_empty_canonical_symbol_set; dag_wave1_sync_tokens. +// Consumes: compiler/tokenize.dag, compiler/parse.dag, std/collection.dag, std/node.dag, std/logic.dag. +// Status: T-6 lex walk realized; T-7 grammar walk realized; modeled LM wired. // Anchor: docs/v3-spec.md module v4.extdeps.languages.dag @@ -625,7 +625,8 @@ fn dag_wave1_grammar_root() -> GrammarRoot { type_alias_rhs, block, data_value - ] + ], + sync_tokens: dag_wave1_sync_tokens() } } @@ -695,3 +696,28 @@ fn dag_wave1_lex_token_symbol(sym: Symbol) -> Bool { token_class: sym ) } + + +// sync_tokens: declaration-start keywords used for error recovery in Repeat walks. +fn dag_wave1_sync_tokens() -> Set { + Set { + member: fn(sym) { + sym == dag_token_kw_module || + sym == dag_token_kw_import || + sym == dag_token_kw_type || + sym == dag_token_kw_data || + sym == dag_token_kw_fn + } + } +} + + +// Pipeline-facing LM that wires the full modeled grammar β€” use this for T-7/T-8+ pipeline calls. +fn dag_language_model_wave1_modeled() -> DagLanguageModel { + DagLanguageModel { + lex: dag_wave1_lex(), + grammar: dag_wave1_grammar(), + language_identity: dag_language_model_surface_id, + canonical_symbols: dag_language_model_surface_prelude_atoms() + } +} diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 4c6c4ed7eb3..983cf70c4d2 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -47,6 +47,8 @@ import v4.std.runtime { Raise, ResourceEffectBoundary, Return, + RuntimeUnit, + RuntimeUnitValue, RuntimeValue, Suspend, TransformInterpreter, @@ -129,7 +131,10 @@ fn v4_eval_wave1_empty_frame() -> EvaluationFrame { } fn v4_eval_wave1_represent_literal(node: Node, _env: EvaluationEnvironment) -> Outcome { - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) + Accepted { + value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, + diagnostics: None + } } fn v4_eval_wave1_represent_result(value: RuntimeValue) -> Outcome { @@ -145,15 +150,21 @@ fn v4_eval_wave1_call_primitive( _args: List, _env: EvaluationEnvironment ) -> Outcome { - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) + Accepted { + value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, + diagnostics: None + } } fn v4_eval_wave1_choose_branch(node: Node, _value: RuntimeValue, _env: EvaluationEnvironment) -> Outcome { - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) + Accepted { value: node, diagnostics: None } } fn v4_eval_wave1_step_loop(node: Node, _env: EvaluationEnvironment) -> Outcome { - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) + Accepted { + value: Return { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } } }, + diagnostics: None + } } fn v4_eval_wave1_bind_value( @@ -174,7 +185,10 @@ fn v4_eval_wave1_allocate(value: RuntimeValue) -> Outcome { } fn v4_eval_wave1_call(call: EvaluationCall, _frame: EvaluationFrame) -> Outcome { - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: call.callee)) + Accepted { + value: Continue { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: call.callee } } }, + diagnostics: None + } } fn v4_eval_wave1_return_value(value: RuntimeValue, _frame: EvaluationFrame) -> Outcome { @@ -184,13 +198,13 @@ fn v4_eval_wave1_return_value(value: RuntimeValue, _frame: EvaluationFrame) -> O fn v4_eval_wave1_transfer(control: ControlTransfer, frame: EvaluationFrame) -> Outcome { match control { Continue { value: _ } => - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: frame.current)) + Accepted { value: frame, diagnostics: None } Return { value: _ } => - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: frame.current)) - Raise { diagnostic: _ } => - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: frame.current)) + Accepted { value: frame, diagnostics: None } + Raise { diagnostic: d } => + outcome_rejected(d: d) Suspend { continuation: c } => - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: c.current)) + Accepted { value: c, diagnostics: None } } } @@ -243,7 +257,7 @@ fn v4_evaluator_value_representation_wave1() -> ValueRepresentationModel { } } -// 🟑 needs-more-work β€” feature:T-22-evaluator-semantics β€” dissolve-on: ModelCore carries inhabited primitives and T-22 eval consumes non-deferred interpretation hooks (ledger: T-34 Β· TASKS.md Β§T-34) +// 🟑 needs-more-work β€” feature:T-22-evaluator-semantics β€” dissolve-on: ModelCore carries inhabited primitives and T-22 eval consumes fully typed interpretation; Wave-1 hooks realized (T-34), richer primitive semantics gated on T-22. fn v4_evaluator_interpretation_wave1() -> InterpretationAlgebra { InterpretationAlgebra { value: ValueInterpreter { From 3eb0e0ede43d6ffc28724fc579736cbb8969d47f Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 05:53:33 +0000 Subject: [PATCH 03/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 84 +++++++++++++++++++++------------ src/v4/std/text.dag | 15 +++--- 2 files changed, 63 insertions(+), 36 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index dad55edccca..ca827d4f1b1 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -26,7 +26,7 @@ import v4.std.collection { List } import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, Unavailable, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } import v4.std.algebra { Cons, Empty, fold_list, is_empty, length, list_append, list_snoc_item } -import v4.std.text { Char, String, string_head, string_is_empty, string_tail } +import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } import v4.std.nat { nat_lte, nat_gte } import v4.std.logic { Bool } @@ -173,14 +173,22 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { match string_is_empty(s: source) { true => LexMatchRejected false => - match string_head(s: prefix) == string_head(s: source) { - true => - match lex_match_prefix(prefix: string_tail(s: prefix), source: string_tail(s: source)) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: rest, lexeme: lex } => - LexMatchAccepted { remaining: rest, lexeme: Cons { head: string_head(s: source), tail: lex } } + match string_head(s: prefix) { + CharAbsent => LexMatchRejected + CharFound { value: ph } => + match string_head(s: source) { + CharAbsent => LexMatchRejected + CharFound { value: sh } => + match ph == sh { + true => + match lex_match_prefix(prefix: string_tail(s: prefix), source: string_tail(s: source)) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + LexMatchAccepted { remaining: rest, lexeme: Cons { head: sh, tail: lex } } + } + false => LexMatchRejected + } } - false => LexMatchRejected } } } @@ -188,18 +196,22 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { // lex_repeat_pattern: greedy zero-or-more match of element against source. -// Terminates because each accepted iteration strictly reduces source length -// (grammar data authors must not define zero-width RepeatPattern elements). +// Termination: zero-width matches (empty consumed) halt immediately; otherwise +// each iteration strictly reduces source length. fn lex_repeat_pattern(pattern: LexPattern, source: String, acc_lexeme: String) -> LexMatchResult { match lex_match_pattern(pattern: pattern, source: source) { LexMatchRejected => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } LexMatchAccepted { remaining: rest, lexeme: consumed } => - lex_repeat_pattern( - pattern: pattern, - source: rest, - acc_lexeme: list_append(left: acc_lexeme, right: consumed) - ) + match string_is_empty(s: consumed) { + true => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } + false => + lex_repeat_pattern( + pattern: pattern, + source: rest, + acc_lexeme: list_append(left: acc_lexeme, right: consumed) + ) + } } } @@ -217,9 +229,13 @@ fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { match string_is_empty(s: rest) { true => LexMatchAccepted { remaining: rest, lexeme: lex } false => - match char_in_class(c: string_head(s: rest), class: IdentContinueChar) { - true => LexMatchRejected - false => LexMatchAccepted { remaining: rest, lexeme: lex } + match string_head(s: rest) { + CharAbsent => LexMatchAccepted { remaining: rest, lexeme: lex } + CharFound { value: c } => + match char_in_class(c: c, class: IdentContinueChar) { + true => LexMatchRejected + false => LexMatchAccepted { remaining: rest, lexeme: lex } + } } } } @@ -227,26 +243,34 @@ fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { match string_is_empty(s: source) { true => LexMatchRejected false => - match string_head(s: source) == expected { - true => - LexMatchAccepted { - remaining: string_tail(s: source), - lexeme: Cons { head: string_head(s: source), tail: Empty } + match string_head(s: source) { + CharAbsent => LexMatchRejected + CharFound { value: c } => + match c == expected { + true => + LexMatchAccepted { + remaining: string_tail(s: source), + lexeme: Cons { head: c, tail: Empty } + } + false => LexMatchRejected } - false => LexMatchRejected } } CharClassPattern { class: class } => match string_is_empty(s: source) { true => LexMatchRejected false => - match char_in_class(c: string_head(s: source), class: class) { - true => - LexMatchAccepted { - remaining: string_tail(s: source), - lexeme: Cons { head: string_head(s: source), tail: Empty } + match string_head(s: source) { + CharAbsent => LexMatchRejected + CharFound { value: c } => + match char_in_class(c: c, class: class) { + true => + LexMatchAccepted { + remaining: string_tail(s: source), + lexeme: Cons { head: c, tail: Empty } + } + false => LexMatchRejected } - false => LexMatchRejected } } SequencePattern { left: left, right: right } => diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index cf01bf17b26..7988b7c1ca4 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,6 +1,6 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. -// Owns: Char, String, string_is_empty, string_head, string_tail. +// Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. // Consumes: std/algebra.dag (FreeMonoid, Cons, Empty, is_empty); std/logic.dag (Bool); std/nat.dag (Nat, Zero). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode @@ -11,17 +11,20 @@ module v4.std.text import v4.std.algebra { Cons, Empty, FreeMonoid, is_empty } import v4.std.logic { Bool } -import v4.std.nat { Nat, Zero } +import v4.std.nat { Nat } type Char = Nat type String = FreeMonoid +type CharResult + = CharFound { value: Char } + | CharAbsent + fn string_is_empty(s: String) -> Bool { is_empty(xs: s) } -// string_head: first character. Caller must check string_is_empty first; returns Zero on empty. -fn string_head(s: String) -> Char { +fn string_head(s: String) -> CharResult { match s { - Empty => Zero - Cons { head: c, tail: _ } => c + Empty => CharAbsent + Cons { head: c, tail: _ } => CharFound { value: c } } } fn string_tail(s: String) -> String { From 2f4f2f14b89de165d72adf6bd6b175820197eb11 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 05:55:36 +0000 Subject: [PATCH 04/66] Address codex review: fix mutual left-recursion detection and parse_repeat progress guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finding 3 (02_parse.dag): parse_repeat now checks length(xs: rest) != length(xs: tokens) before recursing; zero-progress accepted matches (Optional/Empty elements) halt immediately instead of looping forever. Finding 4 (02_parse.dag): replace direct-recursion-only expr_starts_with_nonterminal with transitive expr_reaches_nonterminal_left that tracks a visited Set across Nonterminal expansions β€” detects mutual left recursion (Aβ†’Bβ†’A) where the direct check missed it. Findings 1 and 2 were already addressed in the sprint commit: string_head returns CharResult (CharFound/CharAbsent) not a fabricated Zero, and lex_repeat_pattern already halts on empty consumed. Fix stale Consumes header in text.dag (Zero removed). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 82 ++++++++++++++++++++++++++++-------- src/v4/std/text.dag | 2 +- 2 files changed, 66 insertions(+), 18 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 00598005be4..3fdfa0933cf 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -321,17 +321,49 @@ fn grammar_lookup_production(root: GrammarRoot, name: Symbol) -> GrammarProducti // --- Left-recursion detection --- -// expr_starts_with_nonterminal: true iff the leftmost position of expr is Nonterminal { name }. -fn expr_starts_with_nonterminal(expr: GrammarExpr, name: Symbol) -> Bool { +// set_symbol_insert: functional set extension β€” new set tests item first, then delegates. +fn set_symbol_insert(s: Set, item: Symbol) -> Set { + Set { + member: fn(sym) { sym == item || s.member(sym) } + } +} + + +// expr_reaches_nonterminal_left: true iff the transitive left corner of expr includes `name`. +// visited tracks expanded nonterminals; prevents looping on mutual left recursion. +fn expr_reaches_nonterminal_left( + expr: GrammarExpr, + name: Symbol, + visited: Set, + root: GrammarRoot +) -> Bool { match expr { Terminal { token_class: _ } => false - Nonterminal { production: p } => p == name - Sequence { left: left, right: _ } => expr_starts_with_nonterminal(expr: left, name: name) + Nonterminal { production: p } => + p == name || + match visited.member(p) { + true => false + false => + match grammar_lookup_production(root: root, name: p) { + GrammarProductionMissing => false + GrammarProductionFound { production: prod } => + expr_reaches_nonterminal_left( + expr: prod.expression, + name: name, + visited: set_symbol_insert(s: visited, item: p), + root: root + ) + } + } + Sequence { left: left, right: _ } => + expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) Choice { left: left, right: right } => - expr_starts_with_nonterminal(expr: left, name: name) || - expr_starts_with_nonterminal(expr: right, name: name) - Optional { element: element } => expr_starts_with_nonterminal(expr: element, name: name) - Repeat { element: element } => expr_starts_with_nonterminal(expr: element, name: name) + expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) || + expr_reaches_nonterminal_left(expr: right, name: name, visited: visited, root: root) + Optional { element: element } => + expr_reaches_nonterminal_left(expr: element, name: name, visited: visited, root: root) + Repeat { element: element } => + expr_reaches_nonterminal_left(expr: element, name: name, visited: visited, root: root) } } @@ -341,7 +373,13 @@ fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { xs: root.productions, empty: false, cons: fn(acc, p) { - acc || expr_starts_with_nonterminal(expr: p.expression, name: p.name) + acc || + expr_reaches_nonterminal_left( + expr: p.expression, + name: p.name, + visited: Set { member: fn(_) { false } }, + root: root + ) } ) } @@ -431,7 +469,8 @@ fn parse_repeat_error_recover( // parse_repeat: greedy zero-or-more, with error recovery via sync-token skip. -// Termination: each successful iteration reduces token count; each error recovery +// Termination: zero-progress accepted matches (Optional/Empty elements that consume no tokens) +// halt immediately; each consuming iteration reduces token count; each error recovery // either skips tokens (reducing count) or stops (no skip = no progress). fn parse_repeat( element: GrammarExpr, @@ -442,13 +481,22 @@ fn parse_repeat( ) -> ParseExprResult { match parse_expr(expr: element, tokens: tokens, root: root) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => - parse_repeat( - element: element, - tokens: rest, - root: root, - acc_nodes: list_snoc_item(xs: acc_nodes, item: cap), - acc_diags: list_append(left: acc_diags, right: diags) - ) + match length(xs: rest) != length(xs: tokens) { + true => + parse_repeat( + element: element, + tokens: rest, + root: root, + acc_nodes: list_snoc_item(xs: acc_nodes, item: cap), + acc_diags: list_append(left: acc_diags, right: diags) + ) + false => + ParseExprAccepted { + remaining: tokens, + captured: parse_repeat_captured_node(acc_nodes: acc_nodes), + diagnostics: acc_diags + } + } ParseExprRejected { diagnostics: failed_diags } => match is_empty(xs: failed_diags) { true => diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 7988b7c1ca4..35f3360fafb 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,7 +1,7 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. // Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. -// Consumes: std/algebra.dag (FreeMonoid, Cons, Empty, is_empty); std/logic.dag (Bool); std/nat.dag (Nat, Zero). +// Consumes: std/algebra.dag (FreeMonoid, Cons, Empty, is_empty); std/logic.dag (Bool); std/nat.dag (Nat). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode From 0f50efea56a9d2317fdfe2739fcaf87ffabdc263 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:03:26 +0000 Subject: [PATCH 05/66] Address second codex review: zero-width walk guard, emitted wiring, disposition tags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F2 (01_tokenize.dag): lex_walk_step now rejects zero-width trivia/token matches before recursing (string_is_empty(lexeme) β†’ E1 diagnostic), preventing EmptyPattern rules from looping the main walk indefinitely. F5 (02_parse.dag): parse_production now uses production.emitted β€” successful captures are wrapped with the emitted surface node (kind + children extended with the captured parse subtree via grammar_production_emitted_node_projection edge) instead of returning the raw captured node. F6 (02_parse.dag): add coproduct dissolution tag to ParseExprResult naming dissolution condition (T-8 projection unifies remaining/captured into Outcome). F7 (v4_evaluator.dag): five semantic Wave-1 hooks (represent_literal, call_primitive, choose_branch, step_loop, call) now return diagnostics_singleton carrying the deferred v4_eval_wave1_semantics_deferred diagnostic β€” preserves the pre-T-34 deferred signal while keeping Accepted so Wave-1 is functional. Identity/control hooks unchanged. F8 (nat.dag): add Practice 10 predicate-dissolution tags to nat_lte and nat_gte, bound to the same work item as nat_compare (node://adhoc-2145db6b-69a). Findings 1/3/4 were already addressed in prior commits (CharResult, parse_repeat length guard, transitive visited-set left-recursion detection). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 32 ++++++++++++++++-------- src/v4/compiler/02_parse.dag | 16 ++++++++++-- src/v4/extdeps/runtimes/v4_evaluator.dag | 11 ++++---- src/v4/std/nat.dag | 2 ++ 4 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index ca827d4f1b1..960dbd57c12 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -366,18 +366,28 @@ fn lex_walk_step( LexRuleNoMatch => Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } LexRuleTrivia { lexeme: lexeme, remaining: remaining } => - lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules) + match string_is_empty(s: lexeme) { + true => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + false => + lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules) + } LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => - lex_walk( - source: remaining, - tokens: list_snoc_item( - xs: tokens, - item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } - ), - file: file, - pos: pos + length(xs: lexeme), - rules: rules - ) + match string_is_empty(s: lexeme) { + true => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + false => + lex_walk( + source: remaining, + tokens: list_snoc_item( + xs: tokens, + item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } + ), + file: file, + pos: pos + length(xs: lexeme), + rules: rules + ) + } } } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 3fdfa0933cf..221f608848a 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -61,7 +61,7 @@ type GrammarProductionLookup = GrammarProductionFound { production: GrammarProduction } | GrammarProductionMissing -// ParseExprResult: per-expression match result carrying captured Node and accumulated diagnostics. +// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; per-expression walk result; dissolves when parse-walk result carrier unifies with Outcome via T-8 projection (remaining/captured consolidates; List accumulator lifts into standard Diagnostics). type ParseExprResult = ParseExprAccepted { remaining: List, captured: Node, diagnostics: List } | ParseExprRejected { diagnostics: List } @@ -598,7 +598,19 @@ fn parse_production(tokens: List, root: GrammarRoot, production: GrammarP match parse_expr(expr: production.expression, tokens: tokens, root: root) { ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { - Accepted { value: captured, diagnostics: parse_diags_to_diagnostics(diags: diags) } + Accepted { + value: Node { + kind: production.emitted.kind, + children: list_snoc_item( + xs: production.emitted.children, + item: grammar_named_edge( + name: grammar_production_emitted_node_projection, + target: captured + ) + ) + }, + diagnostics: parse_diags_to_diagnostics(diags: diags) + } } else { Rejected { diagnostics: diagnostics_singleton(d: parse_g0_tokens_remain_diagnostic(at: at)) } } diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 983cf70c4d2..4a4a0b0a73b 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -15,6 +15,7 @@ import v4.std.diagnostic { None, Outcome, Unavailable, + diagnostics_singleton, node_locus, outcome_rejected, port_locus @@ -133,7 +134,7 @@ fn v4_eval_wave1_empty_frame() -> EvaluationFrame { fn v4_eval_wave1_represent_literal(node: Node, _env: EvaluationEnvironment) -> Outcome { Accepted { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, - diagnostics: None + diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) } } @@ -152,18 +153,18 @@ fn v4_eval_wave1_call_primitive( ) -> Outcome { Accepted { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, - diagnostics: None + diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) } } fn v4_eval_wave1_choose_branch(node: Node, _value: RuntimeValue, _env: EvaluationEnvironment) -> Outcome { - Accepted { value: node, diagnostics: None } + Accepted { value: node, diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) } } fn v4_eval_wave1_step_loop(node: Node, _env: EvaluationEnvironment) -> Outcome { Accepted { value: Return { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } } }, - diagnostics: None + diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) } } @@ -187,7 +188,7 @@ fn v4_eval_wave1_allocate(value: RuntimeValue) -> Outcome { fn v4_eval_wave1_call(call: EvaluationCall, _frame: EvaluationFrame) -> Outcome { Accepted { value: Continue { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: call.callee } } }, - diagnostics: None + diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: call.callee)) } } diff --git a/src/v4/std/nat.dag b/src/v4/std/nat.dag index 913fddc8fe2..52aac8b089b 100644 --- a/src/v4/std/nat.dag +++ b/src/v4/std/nat.dag @@ -55,6 +55,7 @@ fn is_zero(n: Nat) -> Bool { Succ { prev: _ } => false } } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: coproduct variant-discriminant predicate substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived Nat total-order compare (binary query consumer); forbidden: nat_cata / fold launder (operator CORE 2026-05-18). fn nat_lte(a: Nat, b: Nat) -> Bool { match nat_compare(a: a, b: b) { Less => true @@ -62,6 +63,7 @@ fn nat_lte(a: Nat, b: Nat) -> Bool { Greater => false } } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: coproduct variant-discriminant predicate substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived Nat total-order compare (binary query consumer); forbidden: nat_cata / fold launder (operator CORE 2026-05-18). fn nat_gte(a: Nat, b: Nat) -> Bool { match nat_compare(a: a, b: b) { Less => false From 52836106c86e9ab4d3142b74fe539ed1effad466 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:32:31 +0000 Subject: [PATCH 06/66] Fix RC1: replace Empty/Cons pattern-matching and self-recursive char dispatch with fold combinators - text.dag: string_head via fold_list_right; string_tail via fold_list + StringTailState; drop Cons/Empty imports - 01_tokenize.dag: inline HexDigitChar/IdentContinueChar arms in char_in_class (removes self-recursion); lex_try_rules via fold_list short-circuit accumulator - 02_parse.dag: parse_diags_to_diagnostics/parse_diags_to_non_empty via fold_list_right + parse_diag_cons helper; parse_skip_to_sync via fold_list + ParseSyncState; parse_repeat_captured_node via fold_list + list_snoc_item Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 22 ++++++----- src/v4/compiler/02_parse.dag | 66 ++++++++++++++++++++++----------- src/v4/std/text.dag | 30 +++++++++------ 3 files changed, 76 insertions(+), 42 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 960dbd57c12..7c16f65ffe0 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -144,7 +144,7 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { DigitChar => nat_gte(a: c, b: 48) && nat_lte(a: c, b: 57) HexDigitChar => - char_in_class(c: c, class: DigitChar) || + (nat_gte(a: c, b: 48) && nat_lte(a: c, b: 57)) || (nat_gte(a: c, b: 65) && nat_lte(a: c, b: 70)) || (nat_gte(a: c, b: 97) && nat_lte(a: c, b: 102)) IdentStartChar => @@ -152,8 +152,10 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { (nat_gte(a: c, b: 97) && nat_lte(a: c, b: 122)) || c == 95 IdentContinueChar => - char_in_class(c: c, class: IdentStartChar) || - char_in_class(c: c, class: DigitChar) + (nat_gte(a: c, b: 65) && nat_lte(a: c, b: 90)) || + (nat_gte(a: c, b: 97) && nat_lte(a: c, b: 122)) || + c == 95 || + (nat_gte(a: c, b: 48) && nat_lte(a: c, b: 57)) StringTextChar => c != 34 && c != 10 LineCommentTextChar => @@ -340,17 +342,19 @@ fn lex_try_rule(rule: LexRule, source: String) -> LexRuleApply { fn lex_try_rules(rules: List, source: String) -> LexRuleApply { - match rules { - Empty => LexRuleNoMatch - Cons { head: rule, tail: rest } => - match lex_try_rule(rule: rule, source: source) { - LexRuleNoMatch => lex_try_rules(rules: rest, source: source) + fold_list( + xs: rules, + empty: LexRuleNoMatch, + cons: fn(acc, rule) { + match acc { + LexRuleNoMatch => lex_try_rule(rule: rule, source: source) LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } LexRuleTrivia { lexeme: lexeme, remaining: remaining } => LexRuleTrivia { lexeme: lexeme, remaining: remaining } } - } + } + ) } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 221f608848a..a95d6d2f9d0 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -2,7 +2,8 @@ // Scope: generic parsing over language grammar rules. // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, -// Node projection functions, left-recursion check, error-recovery helpers. +// Node projection functions, left-recursion check, error-recovery helpers, +// ParseSyncState, parse_diag_cons. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -66,6 +67,10 @@ type ParseExprResult = ParseExprAccepted { remaining: List, captured: Node, diagnostics: List } | ParseExprRejected { diagnostics: List } +type ParseSyncState { + found_sync: Bool + result: List +} data grammar_terminal_token_class_node_projection: Symbol = grammar_terminal_token_class_node_projection data grammar_nonterminal_production_node_projection: Symbol = grammar_nonterminal_production_node_projection @@ -387,18 +392,29 @@ fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { // --- Diagnostic list helpers --- -fn parse_diags_to_diagnostics(diags: List) -> Diagnostics { - match diags { - Empty => None - Cons { head: h, tail: t } => Some { diagnostics: NonEmptyDiagnostics { head: h, tail: t } } +fn parse_diag_cons(d: Diagnostic, acc: Diagnostics) -> Diagnostics { + match acc { + None => Some { diagnostics: NonEmptyDiagnostics { head: d, tail: [] } } + Some { diagnostics: ned } => + Some { + diagnostics: NonEmptyDiagnostics { + head: d, + tail: list_append(left: [ned.head], right: ned.tail) + } + } } } +fn parse_diags_to_diagnostics(diags: List) -> Diagnostics { + fold_list_right(xs: diags, empty: None, snoc: fn(acc, d) { parse_diag_cons(d: d, acc: acc) }) +} + + fn parse_diags_to_non_empty(diags: List, default: Diagnostic) -> NonEmptyDiagnostics { - match diags { - Empty => NonEmptyDiagnostics { head: default, tail: [] } - Cons { head: h, tail: t } => NonEmptyDiagnostics { head: h, tail: t } + match parse_diags_to_diagnostics(diags: diags) { + None => NonEmptyDiagnostics { head: default, tail: [] } + Some { diagnostics: ned } => ned } } @@ -408,17 +424,17 @@ fn parse_diags_to_non_empty(diags: List, default: Diagnostic) -> Non fn parse_repeat_captured_node(acc_nodes: List) -> Node { Node { kind: TypeNode { connective: Conj }, - children: fold_list_right( + children: fold_list( xs: acc_nodes, empty: [], - snoc: fn(acc, n) { - Cons { - head: Edge { + cons: fn(acc, n) { + list_snoc_item( + xs: acc, + item: Edge { label: Named { name: grammar_repeat_element_node_projection }, target: n - }, - tail: acc - } + } + ) } ) } @@ -427,14 +443,20 @@ fn parse_repeat_captured_node(acc_nodes: List) -> Node { // Skip tokens until a sync token is found (inclusive β€” returns stream starting at sync token). fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List { - match tokens { - Empty => Empty - Cons { head: tok, tail: rest } => - match sync_tokens.member(tok.class) { - true => tokens - false => parse_skip_to_sync(tokens: rest, sync_tokens: sync_tokens) + fold_list( + xs: tokens, + empty: ParseSyncState { found_sync: false, result: [] }, + cons: fn(acc, tok) { + match acc.found_sync { + true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: acc.result, item: tok) } + false => + match sync_tokens.member(tok.class) { + true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: [], item: tok) } + false => ParseSyncState { found_sync: false, result: [] } + } } - } + } + ).result } diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 35f3360fafb..65c85746519 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,7 +1,7 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. -// Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. -// Consumes: std/algebra.dag (FreeMonoid, Cons, Empty, is_empty); std/logic.dag (Bool); std/nat.dag (Nat). +// Owns: Char, CharResult, String, StringTailState, string_is_empty, string_head, string_tail. +// Consumes: std/algebra.dag (FreeMonoid, is_empty, fold_list, fold_list_right, list_snoc_item); std/logic.dag (Bool); std/nat.dag (Nat). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode @@ -9,7 +9,7 @@ module v4.std.text -import v4.std.algebra { Cons, Empty, FreeMonoid, is_empty } +import v4.std.algebra { FreeMonoid, fold_list, fold_list_right, is_empty, list_snoc_item } import v4.std.logic { Bool } import v4.std.nat { Nat } type Char = Nat @@ -18,18 +18,26 @@ type CharResult = CharFound { value: Char } | CharAbsent +type StringTailState { + skipped: Bool + result: String +} + fn string_is_empty(s: String) -> Bool { is_empty(xs: s) } fn string_head(s: String) -> CharResult { - match s { - Empty => CharAbsent - Cons { head: c, tail: _ } => CharFound { value: c } - } + fold_list_right(xs: s, empty: CharAbsent, snoc: fn(_acc, c) { CharFound { value: c } }) } fn string_tail(s: String) -> String { - match s { - Empty => Empty - Cons { head: _, tail: t } => t - } + fold_list( + xs: s, + empty: StringTailState { skipped: false, result: [] }, + cons: fn(acc, c) { + match acc.skipped { + true => StringTailState { skipped: true, result: list_snoc_item(xs: acc.result, item: c) } + false => StringTailState { skipped: true, result: [] } + } + } + ).result } From 99acbc22faf6d7ee96f96b9127011286ad1e27c1 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:40:14 +0000 Subject: [PATCH 07/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 2 +- src/v4/std/algebra.dag | 22 +++++++++++++++++++++- src/v4/std/text.dag | 22 ++++------------------ 3 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 7c16f65ffe0..0561ac54ac9 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -25,7 +25,7 @@ module v4.compiler.tokenize import v4.std.collection { List } import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, Unavailable, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } -import v4.std.algebra { Cons, Empty, fold_list, is_empty, length, list_append, list_snoc_item } +import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_skip, list_snoc_item } import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } import v4.std.nat { nat_lte, nat_gte } import v4.std.logic { Bool } diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 946712b065c..0fa7412315f 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -1,7 +1,7 @@ // src/v4/std/algebra.dag // Scope: algebraic structures and canonical carrier constructions. // Anchor: https://en.wikipedia.org/wiki/Algebraic_structure -// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. +// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, list_skip, ListSkipState, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. // Consumes: std node. // Status: T-2 modeled. // Ledger: Part 6 β€” SL-P6-FREEMONOID-IS-EMPTY-VPRED. @@ -273,6 +273,26 @@ fn is_prefix_of( } +// Drop the first n elements; O(|xs|). Uses fold rather than Empty/Cons matching. +type ListSkipState { + remaining: Int + result: FreeMonoid +} +fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { + fold_list( + xs: xs, + empty: ListSkipState { remaining: n, result: [] }, + cons: fn(acc, item) { + if acc.remaining != 0 { + ListSkipState { remaining: acc.remaining - 1, result: acc.result } + } else { + ListSkipState { remaining: 0, result: list_snoc_item(xs: acc.result, item: item) } + } + } + ).result +} + + type PointwisePower { member: fn(T) -> Bool } diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 65c85746519..c931f85d5d7 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,7 +1,7 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. -// Owns: Char, CharResult, String, StringTailState, string_is_empty, string_head, string_tail. -// Consumes: std/algebra.dag (FreeMonoid, is_empty, fold_list, fold_list_right, list_snoc_item); std/logic.dag (Bool); std/nat.dag (Nat). +// Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. +// Consumes: std/algebra.dag (FreeMonoid, is_empty, fold_list_right, list_skip); std/logic.dag (Bool); std/nat.dag (Nat). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode @@ -9,7 +9,7 @@ module v4.std.text -import v4.std.algebra { FreeMonoid, fold_list, fold_list_right, is_empty, list_snoc_item } +import v4.std.algebra { FreeMonoid, fold_list_right, is_empty, list_skip } import v4.std.logic { Bool } import v4.std.nat { Nat } type Char = Nat @@ -18,11 +18,6 @@ type CharResult = CharFound { value: Char } | CharAbsent -type StringTailState { - skipped: Bool - result: String -} - fn string_is_empty(s: String) -> Bool { is_empty(xs: s) } @@ -30,14 +25,5 @@ fn string_head(s: String) -> CharResult { fold_list_right(xs: s, empty: CharAbsent, snoc: fn(_acc, c) { CharFound { value: c } }) } fn string_tail(s: String) -> String { - fold_list( - xs: s, - empty: StringTailState { skipped: false, result: [] }, - cons: fn(acc, c) { - match acc.skipped { - true => StringTailState { skipped: true, result: list_snoc_item(xs: acc.result, item: c) } - false => StringTailState { skipped: true, result: [] } - } - } - ).result + list_skip(xs: s, n: 1) } From 9041384b6a7f410b1011a4b88fcc039dbdea6dfa Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:40:54 +0000 Subject: [PATCH 08/66] Fix remaining RC1/RC2-easy: list_skip stdlib primitive; lex_match_prefix via is_prefix_of; parse_expr Terminal via fold peek MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - algebra.dag: add list_skip(xs, n) β€” fold_list with counter, no Empty/Cons matching; add ListSkipState helper - text.dag: simplify string_tail to list_skip(xs:s,n:1); remove StringTailState/fold_list import - 01_tokenize.dag: rewrite lex_match_prefix using is_prefix_of (stdlib terminal) + list_skip β€” eliminates direct self-recursion (RC2 easy); import is_prefix_of, list_skip - 02_parse.dag: add TokenPeek coproduct + parse_token_first (fold_list_right); rewrite parse_expr Terminal using parse_token_first + list_skip β€” eliminates Empty/Cons match on List (RC1); import list_skip Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 32 ++++++-------------------------- src/v4/compiler/02_parse.dag | 21 +++++++++++++++------ 2 files changed, 21 insertions(+), 32 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 0561ac54ac9..e957d7007f1 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -166,33 +166,13 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { } -// lex_match_prefix: match a literal string prefix against source, building lexeme. -// Recurses character-by-character; terminates on prefix exhaustion or mismatch. +// lex_match_prefix: match a literal string prefix against source. +// Uses is_prefix_of (stdlib terminal) to avoid direct structural recursion on FreeMonoid. fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { - match string_is_empty(s: prefix) { - true => LexMatchAccepted { remaining: source, lexeme: Empty } - false => - match string_is_empty(s: source) { - true => LexMatchRejected - false => - match string_head(s: prefix) { - CharAbsent => LexMatchRejected - CharFound { value: ph } => - match string_head(s: source) { - CharAbsent => LexMatchRejected - CharFound { value: sh } => - match ph == sh { - true => - match lex_match_prefix(prefix: string_tail(s: prefix), source: string_tail(s: source)) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: rest, lexeme: lex } => - LexMatchAccepted { remaining: rest, lexeme: Cons { head: sh, tail: lex } } - } - false => LexMatchRejected - } - } - } - } + if is_prefix_of(xs: prefix, ys: source, eq: fn(a, b) { a == b }) { + LexMatchAccepted { remaining: list_skip(xs: source, n: length(xs: prefix)), lexeme: prefix } + } else { + LexMatchRejected } } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index a95d6d2f9d0..c82b337c272 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -3,7 +3,7 @@ // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, -// ParseSyncState, parse_diag_cons. +// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -21,7 +21,7 @@ import v4.compiler.tokenize { Token, TokenStream } import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_formed } import v4.std.collection { List, Set } -import v4.std.algebra { Cons, Empty, fold_list, fold_list_right, is_empty, length, list_append, list_snoc_item } +import v4.std.algebra { Cons, Empty, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } import v4.std.logic { Bool } @@ -72,6 +72,10 @@ type ParseSyncState { result: List } +type TokenPeek + = TokenPeekAbsent + | TokenPeekFirst { value: Token } + data grammar_terminal_token_class_node_projection: Symbol = grammar_terminal_token_class_node_projection data grammar_nonterminal_production_node_projection: Symbol = grammar_nonterminal_production_node_projection data grammar_sequence_left_node_projection: Symbol = grammar_sequence_left_node_projection @@ -460,6 +464,11 @@ fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List) -> TokenPeek { + fold_list_right(xs: tokens, empty: TokenPeekAbsent, snoc: fn(_acc, tok) { TokenPeekFirst { value: tok } }) +} + + fn parse_repeat_error_recover( element: GrammarExpr, tokens: List, @@ -546,13 +555,13 @@ fn parse_repeat( fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> ParseExprResult { match expr { Terminal { token_class: class } => - match tokens { - Empty => ParseExprRejected { diagnostics: [] } - Cons { head: tok, tail: rest } => + match parse_token_first(tokens: tokens) { + TokenPeekAbsent => ParseExprRejected { diagnostics: [] } + TokenPeekFirst { value: tok } => match tok.class == class { true => ParseExprAccepted { - remaining: rest, + remaining: list_skip(xs: tokens, n: 1), captured: Node { kind: TypeNode { connective: Atom { identity: tok.class } }, children: [] From a73201e278e1ff6aef9812c6327253acce90a0aa Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:45:51 +0000 Subject: [PATCH 09/66] Address cursor RC: parse_e1_syntax_error replaces walk_not_realized fallback; char_in_class Practice 10 tag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 02_parse.dag: add parse_e1_syntax_error symbol + diagnostic; parse_production now uses parse_e1_syntax_error_diagnostic as default in parse_diags_to_non_empty β€” prevents mislabeling genuine parse failures as 'walk not realized' - 01_tokenize.dag: add 🟑 predicate-dissolution interim tag to char_in_class β€” consistent with nat_lte/nat_gte tagging pattern in same PR Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 1 + src/v4/compiler/02_parse.dag | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index e957d7007f1..7d4a9d1d684 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -137,6 +137,7 @@ fn tokenize_lex_e1_unrecognized_char_diagnostic(at: Locus) -> Diagnostic { } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: coproduct variant-discriminant predicate substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived LexCharClass membership predicate (per-variant character range projection dissolves per-arm nat-range inline); forbidden: per-arm expansion laundering. fn char_in_class(c: Char, class: LexCharClass) -> Bool { match class { WhitespaceChar => diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index c82b337c272..f76edbbfe81 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -3,7 +3,7 @@ // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, -// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first. +// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -102,6 +102,8 @@ data parse_grammar_left_recursive: Symbol = parse_grammar_left_recursive data parse_e1_repeat_recovery: Symbol = parse_e1_repeat_recovery +data parse_e1_syntax_error: Symbol = parse_e1_syntax_error + fn parse_walk_not_realized_diagnostic(at: Locus) -> Diagnostic { Diagnostic { @@ -139,6 +141,15 @@ fn parse_grammar_left_recursive_diagnostic(at: Locus) -> Diagnostic { } +fn parse_e1_syntax_error_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_e1_syntax_error, + at: at, + correction: Unavailable { reason: UserInputBoundary } + } +} + + fn parse_e1_repeat_recovery_diagnostic(at: Locus) -> Diagnostic { Diagnostic { reason: parse_e1_repeat_recovery, @@ -649,7 +660,7 @@ fn parse_production(tokens: List, root: GrammarRoot, production: GrammarP Rejected { diagnostics: parse_diags_to_non_empty( diags: diags, - default: parse_walk_not_realized_diagnostic(at: at) + default: parse_e1_syntax_error_diagnostic(at: at) ) } } From ba3007fa14d3fbb722a9e55b95d3e935d2983b69 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:46:55 +0000 Subject: [PATCH 10/66] =?UTF-8?q?Fix=20is=5Fprefix=5Fof=20named-arg=20labe?= =?UTF-8?q?ls=20in=20lex=5Fmatch=5Fprefix:=20xs:/ys:=20=E2=86=92=20prefix:?= =?UTF-8?q?/xs:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 7d4a9d1d684..bf925481d0c 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -170,7 +170,7 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { // lex_match_prefix: match a literal string prefix against source. // Uses is_prefix_of (stdlib terminal) to avoid direct structural recursion on FreeMonoid. fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { - if is_prefix_of(xs: prefix, ys: source, eq: fn(a, b) { a == b }) { + if is_prefix_of(prefix: prefix, xs: source, eq: fn(a, b) { a == b }) { LexMatchAccepted { remaining: list_skip(xs: source, n: length(xs: prefix)), lexeme: prefix } } else { LexMatchRejected From ddc20bb2debb39e97e943ed5faae3d49adb94274 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:53:26 +0000 Subject: [PATCH 11/66] =?UTF-8?q?Fix=20type=20errors:=20[]=20=E2=86=92=20E?= =?UTF-8?q?mpty=20for=20FreeMonoid=20initial=20values=20in=20fold=20acc?= =?UTF-8?q?umulators?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit list_skip empty accumulator, parse_repeat_captured_node empty children, parse_skip_to_sync initial result and snoc base β€” all need explicit Empty constructor since generic T can't infer [] list literal. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 6 +++--- src/v4/std/algebra.dag | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index f76edbbfe81..ee18c3b1b41 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -441,7 +441,7 @@ fn parse_repeat_captured_node(acc_nodes: List) -> Node { kind: TypeNode { connective: Conj }, children: fold_list( xs: acc_nodes, - empty: [], + empty: Empty, cons: fn(acc, n) { list_snoc_item( xs: acc, @@ -460,13 +460,13 @@ fn parse_repeat_captured_node(acc_nodes: List) -> Node { fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List { fold_list( xs: tokens, - empty: ParseSyncState { found_sync: false, result: [] }, + empty: ParseSyncState { found_sync: false, result: Empty }, cons: fn(acc, tok) { match acc.found_sync { true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: acc.result, item: tok) } false => match sync_tokens.member(tok.class) { - true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: [], item: tok) } + true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: Empty, item: tok) } false => ParseSyncState { found_sync: false, result: [] } } } diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 0fa7412315f..d7cfa0f5ebb 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -281,7 +281,7 @@ type ListSkipState { fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { fold_list( xs: xs, - empty: ListSkipState { remaining: n, result: [] }, + empty: ListSkipState { remaining: n, result: Empty }, cons: fn(acc, item) { if acc.remaining != 0 { ListSkipState { remaining: acc.remaining - 1, result: acc.result } From 85deaf5bd03f62ec44779a11d9be808afcc505f1 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 06:58:13 +0000 Subject: [PATCH 12/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 43 ++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index ee18c3b1b41..6842d81f96d 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -349,7 +349,44 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } +// expr_is_nullable: true iff expr can match empty input. +// Optional/Repeat are always nullable; Sequence requires both halves nullable; Choice either. +// Nonterminal expands with a visited guard to prevent looping on nullable mutual recursion. +fn expr_is_nullable( + expr: GrammarExpr, + visited: Set, + root: GrammarRoot +) -> Bool { + match expr { + Terminal { token_class: _ } => false + Nonterminal { production: p } => + match visited.member(p) { + true => false + false => + match grammar_lookup_production(root: root, name: p) { + GrammarProductionMissing => false + GrammarProductionFound { production: prod } => + expr_is_nullable( + expr: prod.expression, + visited: set_symbol_insert(s: visited, item: p), + root: root + ) + } + } + Sequence { left: left, right: right } => + expr_is_nullable(expr: left, visited: visited, root: root) && + expr_is_nullable(expr: right, visited: visited, root: root) + Choice { left: left, right: right } => + expr_is_nullable(expr: left, visited: visited, root: root) || + expr_is_nullable(expr: right, visited: visited, root: root) + Optional { element: _ } => true + Repeat { element: _ } => true + } +} + + // expr_reaches_nonterminal_left: true iff the transitive left corner of expr includes `name`. +// For Sequence, if the left element is nullable, the right is also a left corner. // visited tracks expanded nonterminals; prevents looping on mutual left recursion. fn expr_reaches_nonterminal_left( expr: GrammarExpr, @@ -375,8 +412,10 @@ fn expr_reaches_nonterminal_left( ) } } - Sequence { left: left, right: _ } => - expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) + Sequence { left: left, right: right } => + expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) || + (expr_is_nullable(expr: left, visited: visited, root: root) && + expr_reaches_nonterminal_left(expr: right, name: name, visited: visited, root: root)) Choice { left: left, right: right } => expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) || expr_reaches_nonterminal_left(expr: right, name: name, visited: visited, root: root) From 4eecc7fddd036c0639293c25bb1311e5e1357210 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:01:12 +0000 Subject: [PATCH 13/66] Fix codex RC: Practice 4 dissolution tags on CharResult/TokenPeek; expr_is_nullable for nullable left-corner soundness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CharResult (text.dag) and TokenPeek (02_parse.dag): add required 🟑 coproduct dissolution tags per Practice 4; both dissolve when FreeMonoid gains a substrate-derived first accessor returning Option - expr_is_nullable: new helper (02_parse.dag) that recursively checks whether a GrammarExpr can match empty input, threading a visited-set to guard against cycles on nonterminals - expr_reaches_nonterminal_left Sequence arm: was unsound for nullable left-hand expressions; now falls through to the right arm when expr_is_nullable(left) is true - Owns header updated to include expr_is_nullable Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 3 ++- src/v4/std/text.dag | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 6842d81f96d..7f512b3722e 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -3,7 +3,7 @@ // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, -// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error. +// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -72,6 +72,7 @@ type ParseSyncState { result: List } +// 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. type TokenPeek = TokenPeekAbsent | TokenPeekFirst { value: Token } diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index c931f85d5d7..4bccd1cc05b 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -14,6 +14,7 @@ import v4.std.logic { Bool } import v4.std.nat { Nat } type Char = Nat type String = FreeMonoid +// 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. type CharResult = CharFound { value: Char } | CharAbsent From 3813c965a56ed122309d6f5010493ad665e407ee Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:03:40 +0000 Subject: [PATCH 14/66] Fix remaining [] literal in parse_skip_to_sync false-branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit result: [] in ParseSyncState fold was unresolvable β€” type param T couldn't be pinned, cascading to a tok.class type error. Replace with explicit Empty. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 7f512b3722e..38c83e1f78d 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -507,7 +507,7 @@ fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List match sync_tokens.member(tok.class) { true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: Empty, item: tok) } - false => ParseSyncState { found_sync: false, result: [] } + false => ParseSyncState { found_sync: false, result: Empty } } } } From 32d3433d43d25dcf240952f6035b579f1abd3823 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:07:54 +0000 Subject: [PATCH 15/66] Fix review blockers: list_skip negative-n guard + grammar production-reference closure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit algebra.dag list_skip: add `if n <= 0 { xs }` early return β€” negative skip counts previously decremented Int past zero without terminating, silently returning Empty. Nat can't be used (nat.dag imports algebra.dag); the guard makes the function fail-closed for invalid input per INVARIANTS P2/P3. Comment documents why. 02_parse.dag: add grammar production-reference closure validation before parse walk. - expr_has_undefined_nonterminal: structural recursion on GrammarExpr (finite tree); checks each Nonterminal arm against grammar_lookup_production without following into referenced productions, so no visited-set needed. - grammar_has_undefined_nonterminals: fold over root.productions. - parse(): check undefined nonterminals first (before left-recursion, which can produce confusing errors on broken grammars), reject with parse_grammar_undefined_nonterminal diagnostic if any are missing. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 67 +++++++++++++++++++++++++++++++----- src/v4/std/algebra.dag | 25 ++++++++------ 2 files changed, 74 insertions(+), 18 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 38c83e1f78d..4d30922d9fa 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -3,7 +3,8 @@ // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, -// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable. +// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable, +// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -101,6 +102,8 @@ data parse_g0_tokens_remain: Symbol = parse_g0_tokens_remain data parse_grammar_left_recursive: Symbol = parse_grammar_left_recursive +data parse_grammar_undefined_nonterminal: Symbol = parse_grammar_undefined_nonterminal + data parse_e1_repeat_recovery: Symbol = parse_e1_repeat_recovery data parse_e1_syntax_error: Symbol = parse_e1_syntax_error @@ -142,6 +145,15 @@ fn parse_grammar_left_recursive_diagnostic(at: Locus) -> Diagnostic { } +fn parse_grammar_undefined_nonterminal_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_grammar_undefined_nonterminal, + at: at, + correction: Unavailable { reason: ExternalContractUnknown } + } +} + + fn parse_e1_syntax_error_diagnostic(at: Locus) -> Diagnostic { Diagnostic { reason: parse_e1_syntax_error, @@ -445,6 +457,41 @@ fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { } +// Structural recursion on GrammarExpr (finite tree) β€” does NOT follow nonterminal +// references into their productions, so it always terminates without a visited set. +fn expr_has_undefined_nonterminal(expr: GrammarExpr, root: GrammarRoot) -> Bool { + match expr { + Terminal { token_class: _ } => false + Nonterminal { production: p } => + match grammar_lookup_production(root: root, name: p) { + GrammarProductionMissing => true + GrammarProductionFound { production: _ } => false + } + Sequence { left: left, right: right } => + expr_has_undefined_nonterminal(expr: left, root: root) || + expr_has_undefined_nonterminal(expr: right, root: root) + Choice { left: left, right: right } => + expr_has_undefined_nonterminal(expr: left, root: root) || + expr_has_undefined_nonterminal(expr: right, root: root) + Optional { element: element } => + expr_has_undefined_nonterminal(expr: element, root: root) + Repeat { element: element } => + expr_has_undefined_nonterminal(expr: element, root: root) + } +} + + +fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { + fold_list( + xs: root.productions, + empty: false, + cons: fn(acc, p) { + acc || expr_has_undefined_nonterminal(expr: p.expression, root: root) + } + ) +} + + // --- Diagnostic list helpers --- fn parse_diag_cons(d: Diagnostic, acc: Diagnostics) -> Diagnostics { @@ -722,14 +769,18 @@ fn parse(tokens: TokenStream, grammar: Grammar) -> Outcome { Rejected { diagnostics: diagnostics_singleton(d: parse_g0_tokens_remain_diagnostic(at: at)) } } ModeledGrammar { root: root } => - if grammar_has_left_recursion(root: root) { - Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_left_recursive_diagnostic(at: at)) } + if grammar_has_undefined_nonterminals(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } } else { - match grammar_lookup_production(root: root, name: root.start) { - GrammarProductionFound { production: start } => - parse_production(tokens: tokens.tokens, root: root, production: start) - GrammarProductionMissing => - Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + if grammar_has_left_recursion(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_left_recursive_diagnostic(at: at)) } + } else { + match grammar_lookup_production(root: root, name: root.start) { + GrammarProductionFound { production: start } => + parse_production(tokens: tokens.tokens, root: root, production: start) + GrammarProductionMissing => + Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + } } } } diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index d7cfa0f5ebb..1f9289b2320 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -274,22 +274,27 @@ fn is_prefix_of( // Drop the first n elements; O(|xs|). Uses fold rather than Empty/Cons matching. +// n <= 0: returns xs unchanged (fail-closed; Nat not usable here β€” nat.dag imports algebra.dag). type ListSkipState { remaining: Int result: FreeMonoid } fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { - fold_list( - xs: xs, - empty: ListSkipState { remaining: n, result: Empty }, - cons: fn(acc, item) { - if acc.remaining != 0 { - ListSkipState { remaining: acc.remaining - 1, result: acc.result } - } else { - ListSkipState { remaining: 0, result: list_snoc_item(xs: acc.result, item: item) } + if n <= 0 { + xs + } else { + fold_list( + xs: xs, + empty: ListSkipState { remaining: n, result: Empty }, + cons: fn(acc, item) { + if acc.remaining != 0 { + ListSkipState { remaining: acc.remaining - 1, result: acc.result } + } else { + ListSkipState { remaining: 0, result: list_snoc_item(xs: acc.result, item: item) } + } } - } - ).result + ).result + } } From 8b3969b415924a54788adeb1d36d2e87968605bb Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:08:45 +0000 Subject: [PATCH 16/66] =?UTF-8?q?Fix=20ParseSyncState.result:=20List=20=E2=86=92=20FreeMonoid=20for=20fold=5Flist=20inferen?= =?UTF-8?q?ce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit List is an alias for FreeMonoid; fold_list cannot infer tok:Token from the accumulator when the field type is the alias form. Using the base type directly restores type inference. Return type of parse_skip_to_sync stays List since FreeMonoid = List transparently. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 4d30922d9fa..1e0c559f26e 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -70,7 +70,7 @@ type ParseExprResult type ParseSyncState { found_sync: Bool - result: List + result: FreeMonoid } // 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. From c09ec7d25276cbc5adb81fdcc359dd303529b46a Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:09:45 +0000 Subject: [PATCH 17/66] Fix tok.class inference: extract parse_sync_step helper with explicit tok:Token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cons lambda in parse_skip_to_sync gave fold_list no way to pin tok's type from the List alias on ParseSyncState.result. Extracting to parse_sync_step with explicit 'tok: Token' parameter gives the type context fold_list needs. Revert the FreeMonoid field change β€” List alias is correct. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 1e0c559f26e..827701efa81 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -4,7 +4,7 @@ // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable, -// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals. +// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, parse_sync_step. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // @@ -70,7 +70,7 @@ type ParseExprResult type ParseSyncState { found_sync: Bool - result: FreeMonoid + result: List } // 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. @@ -544,20 +544,23 @@ fn parse_repeat_captured_node(acc_nodes: List) -> Node { // Skip tokens until a sync token is found (inclusive β€” returns stream starting at sync token). +fn parse_sync_step(acc: ParseSyncState, tok: Token, sync_tokens: Set) -> ParseSyncState { + match acc.found_sync { + true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: acc.result, item: tok) } + false => + match sync_tokens.member(tok.class) { + true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: Empty, item: tok) } + false => ParseSyncState { found_sync: false, result: Empty } + } + } +} + + fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List { fold_list( xs: tokens, empty: ParseSyncState { found_sync: false, result: Empty }, - cons: fn(acc, tok) { - match acc.found_sync { - true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: acc.result, item: tok) } - false => - match sync_tokens.member(tok.class) { - true => ParseSyncState { found_sync: true, result: list_snoc_item(xs: Empty, item: tok) } - false => ParseSyncState { found_sync: false, result: Empty } - } - } - } + cons: fn(acc, tok) { parse_sync_step(acc: acc, tok: tok, sync_tokens: sync_tokens) } ).result } From b09de9446070e6425e28f66f80c61195bae1d639 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:29:47 +0000 Subject: [PATCH 18/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 827701efa81..233cef1ba75 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -440,19 +440,22 @@ fn expr_reaches_nonterminal_left( } +fn grammar_has_left_recursion_step(acc: Bool, p: GrammarProduction, root: GrammarRoot) -> Bool { + acc || + expr_reaches_nonterminal_left( + expr: p.expression, + name: p.name, + visited: Set { member: fn(_) { false } }, + root: root + ) +} + + fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { fold_list( xs: root.productions, empty: false, - cons: fn(acc, p) { - acc || - expr_reaches_nonterminal_left( - expr: p.expression, - name: p.name, - visited: Set { member: fn(_) { false } }, - root: root - ) - } + cons: fn(acc, p) { grammar_has_left_recursion_step(acc: acc, p: p, root: root) } ) } @@ -481,13 +484,16 @@ fn expr_has_undefined_nonterminal(expr: GrammarExpr, root: GrammarRoot) -> Bool } +fn grammar_has_undefined_nonterminals_step(acc: Bool, p: GrammarProduction, root: GrammarRoot) -> Bool { + acc || expr_has_undefined_nonterminal(expr: p.expression, root: root) +} + + fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { fold_list( xs: root.productions, empty: false, - cons: fn(acc, p) { - acc || expr_has_undefined_nonterminal(expr: p.expression, root: root) - } + cons: fn(acc, p) { grammar_has_undefined_nonterminals_step(acc: acc, p: p, root: root) } ) } From 5d3165aae13da9a74646f5eeae12e072ecfece92 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:29:53 +0000 Subject: [PATCH 19/66] Fix p.expression/p.name type inference in grammar fold lambdas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grammar_has_left_recursion and grammar_has_undefined_nonterminals both fold over root.productions: List. The List alias prevents fold_list from inferring p:GrammarProduction in the lambda, causing 'no field expression/name on type FreeMonoid'. Extract typed step helpers with explicit p:GrammarProduction parameter β€” same fix as parse_sync_step for tok:Token. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 233cef1ba75..6ed155cfc3e 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -4,7 +4,8 @@ // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable, -// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, parse_sync_step. +// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, +// grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, parse_sync_step. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. // From d6934a663ff7f5e3b32f381a02dcc183926a4a77 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:37:39 +0000 Subject: [PATCH 20/66] =?UTF-8?q?Fix=20Wave-1=20evaluator=20hooks:=20Accep?= =?UTF-8?q?ted=20with=20fabricated=20RuntimeUnit=20=E2=86=92=20Rejected=20?= =?UTF-8?q?(P3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five deferred hooks returned Accepted with a plausible RuntimeUnit value, violating INVARIANTS P3 fail-closed. Unrealized semantics must not produce success values. Replace with outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(...)): - v4_eval_wave1_represent_literal - v4_eval_wave1_call_primitive - v4_eval_wave1_choose_branch - v4_eval_wave1_step_loop - v4_eval_wave1_call Legitimate pass-through hooks (bind_value, allocate, represent_result, return_value, transfer, terminal_value) keep their Accepted returns. Remove now-unused RuntimeUnit/RuntimeUnitValue/diagnostics_singleton imports. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/runtimes/v4_evaluator.dag | 25 +++++------------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 4a4a0b0a73b..d2e7d41393e 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -15,7 +15,6 @@ import v4.std.diagnostic { None, Outcome, Unavailable, - diagnostics_singleton, node_locus, outcome_rejected, port_locus @@ -48,8 +47,6 @@ import v4.std.runtime { Raise, ResourceEffectBoundary, Return, - RuntimeUnit, - RuntimeUnitValue, RuntimeValue, Suspend, TransformInterpreter, @@ -132,10 +129,7 @@ fn v4_eval_wave1_empty_frame() -> EvaluationFrame { } fn v4_eval_wave1_represent_literal(node: Node, _env: EvaluationEnvironment) -> Outcome { - Accepted { - value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, - diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) - } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) } fn v4_eval_wave1_represent_result(value: RuntimeValue) -> Outcome { @@ -151,21 +145,15 @@ fn v4_eval_wave1_call_primitive( _args: List, _env: EvaluationEnvironment ) -> Outcome { - Accepted { - value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } }, - diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) - } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) } fn v4_eval_wave1_choose_branch(node: Node, _value: RuntimeValue, _env: EvaluationEnvironment) -> Outcome { - Accepted { value: node, diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) } fn v4_eval_wave1_step_loop(node: Node, _env: EvaluationEnvironment) -> Outcome { - Accepted { - value: Return { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: node } } }, - diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: node)) - } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: node)) } fn v4_eval_wave1_bind_value( @@ -186,10 +174,7 @@ fn v4_eval_wave1_allocate(value: RuntimeValue) -> Outcome { } fn v4_eval_wave1_call(call: EvaluationCall, _frame: EvaluationFrame) -> Outcome { - Accepted { - value: Continue { value: RuntimeUnit { value: RuntimeUnitValue { unit_type: call.callee } } }, - diagnostics: diagnostics_singleton(d: v4_eval_wave1_runtime_diagnostic(node: call.callee)) - } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: call.callee)) } fn v4_eval_wave1_return_value(value: RuntimeValue, _frame: EvaluationFrame) -> Outcome { From b5cb02e99a1822ff7dd58947190ba4156fa54d48 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 07:52:59 +0000 Subject: [PATCH 21/66] Fix P5: tag sync_tokens/recovery path as staged (T-8), correct header claims MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude RC found the Repeat error-recovery path is unreachable: parse_expr always returns ParseExprRejected { diagnostics: [] }, so is_empty(failed_diags) is always true and parse_repeat_error_recover never fires. The header claimed this as live behavior (P5 violation β€” documentation must describe live state). Fix: - Header: change Status line and walker-semantics note to say "staged (T-8)" rather than claiming recovery is realized behavior - GrammarRoot: add 🟑 gated tag noting sync_tokens + recovery loop are structurally correct but unreachable until T-8 wires the upstream signal (parse_expr emitting non-empty diagnostics on committed Terminal mismatches) - parse_repeat false branch: inline 🟑 gated T-8 comment at the unreachable call site The recovery machinery (parse_repeat_error_recover, parse_skip_to_sync, ParseSyncState, parse_sync_step) is correctly modeled β€” it fires correctly once T-8 provides the signal. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 6ed155cfc3e..37184945522 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -7,13 +7,15 @@ // expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, // grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, parse_sync_step. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. -// Status: T-7 parse walk realized; GrammarRoot carries sync_tokens for error recovery. +// Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. // // Walker semantics: // PEG ordered choice: Choice tries left first; left wins if it matches. // Grammar data must be non-left-recursive; checked at parse() entry. -// Repeat error recovery: on element failure with diagnostics, skip to next sync token. -// sync_tokens are declaration-start keywords (language-specific; declared on GrammarRoot). +// Repeat error recovery staged (T-8): recovery loop and sync_tokens are structurally +// correct but unreachable β€” parse_expr currently emits empty diagnostics on all rejections; +// the recovery branch fires only when parse_expr signals a committed mismatch (T-8 upstream +// signal not yet wired). sync_tokens are declaration-start keywords (language-specific). module v4.compiler.parse @@ -44,6 +46,9 @@ type GrammarProduction { } +// 🟑 gated β€” feature: T-8 parse error-recovery trigger β€” sync_tokens present; recovery loop +// (parse_repeat_error_recover, parse_skip_to_sync) structurally correct but unreachable until +// parse_expr emits non-empty diagnostics on committed Terminal mismatches. Dissolve-on: T-8. type GrammarRoot { start: Symbol productions: List @@ -637,6 +642,8 @@ fn parse_repeat( } } ParseExprRejected { diagnostics: failed_diags } => + // 🟑 gated T-8: false branch (non-empty failed_diags) unreachable until parse_expr + // signals committed mismatches; currently all rejections carry diagnostics: []. match is_empty(xs: failed_diags) { true => ParseExprAccepted { From 41e7f79b6c3956f1c59c98519432fd1a0872d10f Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:05:41 +0000 Subject: [PATCH 22/66] Add Practice 10 disposition tags to lex_repeat_pattern and lex_match_pattern Both functions are recursive structural walkers over the LexPattern coproduct without Practice 10 fix-now/tracked-bridge/terminal disposition tags, leaving lexer semantics as untracked derived-operation logic under INVARIANTS P5. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index bf925481d0c..2da2641ccf1 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -178,6 +178,7 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern repeat combinator substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived greedy-repeat morphism over LexPattern's RepeatPattern variant, eliminating the hand-rolled zero-width halt guard; forbidden: inlining repeat semantics into the pattern match arms of lex_match_pattern. // lex_repeat_pattern: greedy zero-or-more match of element against source. // Termination: zero-width matches (empty consumed) halt immediately; otherwise // each iteration strictly reduces source length. @@ -199,6 +200,7 @@ fn lex_repeat_pattern(pattern: LexPattern, source: String, acc_lexeme: String) - } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived pattern-matching morphism over LexPattern coproduct (per-variant fold eliminating hand-written match arms); forbidden: adding new match arms outside the substrate derivation path. fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { match pattern { EmptyPattern => From c7b20a6eff3bee96f38c4af1508880d746a7d6d1 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:07:27 +0000 Subject: [PATCH 23/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 37184945522..43014561939 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -368,6 +368,7 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived nullable query morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating nullable logic outside this function. // expr_is_nullable: true iff expr can match empty input. // Optional/Repeat are always nullable; Sequence requires both halves nullable; Choice either. // Nonterminal expands with a visited guard to prevent looping on nullable mutual recursion. @@ -404,6 +405,7 @@ fn expr_is_nullable( } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr left-corner query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-corner reachability morphism over GrammarExpr coproduct; forbidden: duplicating left-corner logic or inlining nullable check outside this function. // expr_reaches_nonterminal_left: true iff the transitive left corner of expr includes `name`. // For Sequence, if the left element is nullable, the right is also a left corner. // visited tracks expanded nonterminals; prevents looping on mutual left recursion. @@ -466,6 +468,7 @@ fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr production-reference closure query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived undefined-nonterminal query morphism over GrammarExpr coproduct; forbidden: duplicating reference-closure logic outside this function. // Structural recursion on GrammarExpr (finite tree) β€” does NOT follow nonterminal // references into their productions, so it always terminates without a visited set. fn expr_has_undefined_nonterminal(expr: GrammarExpr, root: GrammarRoot) -> Bool { From 405278556ec33a5feea3c2ba53dae1915dec05a6 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:07:36 +0000 Subject: [PATCH 24/66] Add Practice 10 tags to GrammarExpr walkers; validate root.start in grammar_has_undefined_nonterminals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three GrammarExpr structural walkers (expr_is_nullable, expr_reaches_nonterminal_left, expr_has_undefined_nonterminal) lacked Practice 10 disposition tags per codex finding on d6934a663. grammar_has_undefined_nonterminals now validates root.start membership in productions before folding over production expressions β€” a bare start Symbol with no production is now caught as an undefined nonterminal at grammar boundary validation. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 43014561939..d5b2806bf55 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -499,11 +499,15 @@ fn grammar_has_undefined_nonterminals_step(acc: Bool, p: GrammarProduction, root fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { - fold_list( - xs: root.productions, - empty: false, - cons: fn(acc, p) { grammar_has_undefined_nonterminals_step(acc: acc, p: p, root: root) } - ) + match grammar_lookup_production(root: root, name: root.start) { + GrammarProductionMissing => true + GrammarProductionFound { production: _ } => + fold_list( + xs: root.productions, + empty: false, + cons: fn(acc, p) { grammar_has_undefined_nonterminals_step(acc: acc, p: p, root: root) } + ) + } } From 16936838ff7aaad5f589e998b9305f0377193f49 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:09:30 +0000 Subject: [PATCH 25/66] Fix dead GrammarProductionMissing arm: wrong diagnostic after root.start validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After grammar_has_undefined_nonterminals was updated to validate root.start (405278556), the GrammarProductionMissing arm in parse() at the final lookup became dead code β€” but still said parse_walk_not_realized, which is both wrong and a P5 violation (implying an unrealized walk path rather than the actual cause). Changed to parse_grammar_undefined_nonterminal_diagnostic (correct semantic) and added a gated T-8 comment noting the arm is now unreachable by construction. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index d5b2806bf55..19ab5058ba5 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -802,8 +802,11 @@ fn parse(tokens: TokenStream, grammar: Grammar) -> Outcome { match grammar_lookup_production(root: root, name: root.start) { GrammarProductionFound { production: start } => parse_production(tokens: tokens.tokens, root: root, production: start) + // 🟑 gated T-8: structurally unreachable β€” grammar_has_undefined_nonterminals above + // validates root.start; GrammarProductionMissing here is dead by construction. + // Kept for exhaustiveness; dissolve-on: T-8 or substrate-level totality proof. GrammarProductionMissing => - Rejected { diagnostics: diagnostics_singleton(d: parse_walk_not_realized_diagnostic(at: at)) } + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } } } } From d53c955374de8efc6c4393d06b403ae82aec8706 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:12:16 +0000 Subject: [PATCH 26/66] Complete sync_tokens rollout to all language models; fix transfer Suspend to reject (P3/T-34) GrammarRoot.sync_tokens was added for T-8 error-recovery but five language extdeps (rust, java, typescript, swift, wasm) still built two-field records, leaving a type-rollout gap under INVARIANTS P1. Each now supplies an empty Set (Wave-1 has no language-specific sync tokens yet; dag.dag already had its set from the prior commit). v4_eval_wave1_transfer: Suspend arm was returning Accepted { value: c }, contradicting the T-34 anchor witness (witness_v4_evaluator_transfer_fail_closed expects Rejected) and INVARIANTS P3 (Wave-1 does not support suspensions). Changed to outcome_rejected with the standard wave-1 deferred-semantics diagnostic, matching terminal_value behavior. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/languages/java.dag | 2 +- src/v4/extdeps/languages/rust.dag | 2 +- src/v4/extdeps/languages/swift.dag | 2 +- src/v4/extdeps/languages/typescript.dag | 2 +- src/v4/extdeps/languages/wasm.dag | 2 +- src/v4/extdeps/runtimes/v4_evaluator.dag | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/v4/extdeps/languages/java.dag b/src/v4/extdeps/languages/java.dag index 3cbc3041ba4..9889ed038ad 100644 --- a/src/v4/extdeps/languages/java.dag +++ b/src/v4/extdeps/languages/java.dag @@ -921,7 +921,7 @@ fn java_grammar_production_mvp1_method_add() -> GrammarProduction { fn java_wave1_grammar_root() -> GrammarRoot { let start = java_grammar_production_mvp1_method_add() - GrammarRoot { start: java_production_mvp1_method_add, productions: [start] } + GrammarRoot { start: java_production_mvp1_method_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } } fn java_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/rust.dag b/src/v4/extdeps/languages/rust.dag index 958f8ea6ee3..8e9e4550348 100644 --- a/src/v4/extdeps/languages/rust.dag +++ b/src/v4/extdeps/languages/rust.dag @@ -1265,7 +1265,7 @@ fn rust_grammar_production_mvp1_fn_add() -> GrammarProduction { fn rust_wave1_grammar_root() -> GrammarRoot { let start = rust_grammar_production_mvp1_fn_add() - GrammarRoot { start: rust_production_mvp1_fn_add, productions: [start] } + GrammarRoot { start: rust_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } } fn rust_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/swift.dag b/src/v4/extdeps/languages/swift.dag index b27d53d545f..2147482e494 100644 --- a/src/v4/extdeps/languages/swift.dag +++ b/src/v4/extdeps/languages/swift.dag @@ -884,7 +884,7 @@ fn swift_grammar_production_mvp1_fn_add() -> GrammarProduction { fn swift_wave1_grammar_root() -> GrammarRoot { let start = swift_grammar_production_mvp1_fn_add() - GrammarRoot { start: swift_production_mvp1_fn_add, productions: [start] } + GrammarRoot { start: swift_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } } fn swift_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/typescript.dag b/src/v4/extdeps/languages/typescript.dag index 5bc6e344f99..6746199ca3e 100644 --- a/src/v4/extdeps/languages/typescript.dag +++ b/src/v4/extdeps/languages/typescript.dag @@ -645,7 +645,7 @@ fn ts_grammar_production_mvp1_fn_add() -> GrammarProduction { fn ts_wave1_grammar_root() -> GrammarRoot { let start = ts_grammar_production_mvp1_fn_add() - GrammarRoot { start: ts_production_mvp1_fn_add, productions: [start] } + GrammarRoot { start: ts_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } } fn ts_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/wasm.dag b/src/v4/extdeps/languages/wasm.dag index dfbc7457b9a..a20ea156f04 100644 --- a/src/v4/extdeps/languages/wasm.dag +++ b/src/v4/extdeps/languages/wasm.dag @@ -692,7 +692,7 @@ fn wasm_grammar_production_mvp1_fn_add() -> GrammarProduction { fn wasm_wave1_grammar_root() -> GrammarRoot { let start = wasm_grammar_production_mvp1_fn_add() - GrammarRoot { start: wasm_production_mvp1_fn_add, productions: [start] } + GrammarRoot { start: wasm_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } } fn wasm_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index d2e7d41393e..197ae6771ec 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -190,7 +190,7 @@ fn v4_eval_wave1_transfer(control: ControlTransfer, frame: EvaluationFrame) -> O Raise { diagnostic: d } => outcome_rejected(d: d) Suspend { continuation: c } => - Accepted { value: c, diagnostics: None } + outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: c.current)) } } From e993ff5940d455e1ec377897585e5d163fa97bb9 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:23:58 +0000 Subject: [PATCH 27/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 5 +++++ src/v4/extdeps/languages/java.dag | 3 ++- src/v4/extdeps/languages/rust.dag | 3 ++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 19ab5058ba5..93fc6883f72 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -196,6 +196,11 @@ fn grammar_named_edge(name: Symbol, target: Node) -> Edge { } +fn grammar_empty_sync_tokens() -> Set { + Set { member: fn(_) { false } } +} + + fn grammar_empty_node() -> Node { Node { kind: TypeNode { diff --git a/src/v4/extdeps/languages/java.dag b/src/v4/extdeps/languages/java.dag index 9889ed038ad..a92365f0fd8 100644 --- a/src/v4/extdeps/languages/java.dag +++ b/src/v4/extdeps/languages/java.dag @@ -15,6 +15,7 @@ import v4.compiler.parse { ModeledGrammar, Sequence, Terminal, + grammar_empty_sync_tokens, grammar_production_to_node } import v4.compiler.tokenize { @@ -921,7 +922,7 @@ fn java_grammar_production_mvp1_method_add() -> GrammarProduction { fn java_wave1_grammar_root() -> GrammarRoot { let start = java_grammar_production_mvp1_method_add() - GrammarRoot { start: java_production_mvp1_method_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } + GrammarRoot { start: java_production_mvp1_method_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn java_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/rust.dag b/src/v4/extdeps/languages/rust.dag index 8e9e4550348..ae0540ea81e 100644 --- a/src/v4/extdeps/languages/rust.dag +++ b/src/v4/extdeps/languages/rust.dag @@ -15,6 +15,7 @@ import v4.compiler.parse { ModeledGrammar, Sequence, Terminal, + grammar_empty_sync_tokens, grammar_production_to_node } import v4.compiler.tokenize { @@ -1265,7 +1266,7 @@ fn rust_grammar_production_mvp1_fn_add() -> GrammarProduction { fn rust_wave1_grammar_root() -> GrammarRoot { let start = rust_grammar_production_mvp1_fn_add() - GrammarRoot { start: rust_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } + GrammarRoot { start: rust_production_mvp1_fn_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn rust_wave1_grammar() -> Grammar { From 605bd604e5f17ddf7d3a2f2da45adb67e79ca7f9 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 08:24:54 +0000 Subject: [PATCH 28/66] Fix sync_tokens rollout: use grammar_empty_sync_tokens() in swift/typescript/wasm The inline Set { member: fn(_) { false } } literal in struct context lacks type context for the v2 bootstrap compiler's lambda inference. Use the named grammar_empty_sync_tokens() helper (added in e993ff594 for rust/java) instead. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/languages/swift.dag | 3 ++- src/v4/extdeps/languages/typescript.dag | 3 ++- src/v4/extdeps/languages/wasm.dag | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/v4/extdeps/languages/swift.dag b/src/v4/extdeps/languages/swift.dag index 2147482e494..ab853fa200f 100644 --- a/src/v4/extdeps/languages/swift.dag +++ b/src/v4/extdeps/languages/swift.dag @@ -17,6 +17,7 @@ import v4.compiler.parse { ModeledGrammar, Sequence, Terminal, + grammar_empty_sync_tokens, grammar_production_to_node } import v4.compiler.tokenize { @@ -884,7 +885,7 @@ fn swift_grammar_production_mvp1_fn_add() -> GrammarProduction { fn swift_wave1_grammar_root() -> GrammarRoot { let start = swift_grammar_production_mvp1_fn_add() - GrammarRoot { start: swift_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } + GrammarRoot { start: swift_production_mvp1_fn_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn swift_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/typescript.dag b/src/v4/extdeps/languages/typescript.dag index 6746199ca3e..35c525d77ef 100644 --- a/src/v4/extdeps/languages/typescript.dag +++ b/src/v4/extdeps/languages/typescript.dag @@ -17,6 +17,7 @@ import v4.compiler.parse { ModeledGrammar, Sequence, Terminal, + grammar_empty_sync_tokens, grammar_production_to_node } import v4.compiler.tokenize { @@ -645,7 +646,7 @@ fn ts_grammar_production_mvp1_fn_add() -> GrammarProduction { fn ts_wave1_grammar_root() -> GrammarRoot { let start = ts_grammar_production_mvp1_fn_add() - GrammarRoot { start: ts_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } + GrammarRoot { start: ts_production_mvp1_fn_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn ts_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/wasm.dag b/src/v4/extdeps/languages/wasm.dag index a20ea156f04..823dcd23f3a 100644 --- a/src/v4/extdeps/languages/wasm.dag +++ b/src/v4/extdeps/languages/wasm.dag @@ -17,6 +17,7 @@ import v4.compiler.parse { ModeledGrammar, Sequence, Terminal, + grammar_empty_sync_tokens, grammar_production_to_node } import v4.compiler.tokenize { @@ -692,7 +693,7 @@ fn wasm_grammar_production_mvp1_fn_add() -> GrammarProduction { fn wasm_wave1_grammar_root() -> GrammarRoot { let start = wasm_grammar_production_mvp1_fn_add() - GrammarRoot { start: wasm_production_mvp1_fn_add, productions: [start], sync_tokens: Set { member: fn(_) { false } } } + GrammarRoot { start: wasm_production_mvp1_fn_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn wasm_wave1_grammar() -> Grammar { From bff7ee3507313478000c8c2b437a7b6d57171de1 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 09:22:31 +0000 Subject: [PATCH 29/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 93fc6883f72..d05209463ae 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -79,6 +79,11 @@ type ParseSyncState { result: List } +type GrammarDupCheckState { + seen: Set + has_duplicate: Bool +} + // 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. type TokenPeek = TokenPeekAbsent @@ -97,6 +102,8 @@ data grammar_production_expression_node_projection: Symbol = grammar_production_ data grammar_production_emitted_node_projection: Symbol = grammar_production_emitted_node_projection data grammar_root_start_production_node_projection: Symbol = grammar_root_start_production_node_projection data grammar_root_productions_node_projection: Symbol = grammar_root_productions_node_projection +data grammar_production_identity_node_projection: Symbol = grammar_production_identity_node_projection +data grammar_production_captured_node_projection: Symbol = grammar_production_captured_node_projection data parse_stage_locus_port: Symbol = parse_stage_locus_port @@ -110,6 +117,8 @@ data parse_grammar_left_recursive: Symbol = parse_grammar_left_recursive data parse_grammar_undefined_nonterminal: Symbol = parse_grammar_undefined_nonterminal +data parse_grammar_duplicate_production: Symbol = parse_grammar_duplicate_production + data parse_e1_repeat_recovery: Symbol = parse_e1_repeat_recovery data parse_e1_syntax_error: Symbol = parse_e1_syntax_error @@ -160,6 +169,15 @@ fn parse_grammar_undefined_nonterminal_diagnostic(at: Locus) -> Diagnostic { } +fn parse_grammar_duplicate_production_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_grammar_duplicate_production, + at: at, + correction: Unavailable { reason: ExternalContractUnknown } + } +} + + fn parse_e1_syntax_error_diagnostic(at: Locus) -> Diagnostic { Diagnostic { reason: parse_e1_syntax_error, From 4f5644bb70df6784c34c268675f5c9feb7881fed Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 09:23:23 +0000 Subject: [PATCH 30/66] T-7 parse: separate production identity from parse-capture; add duplicate production validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - parse_production: replace emitted.kind + appended child conflation with a TypeNode{Conj} wrapper carrying two labeled edges: grammar_production_identity_node_projection β†’ production.emitted grammar_production_captured_node_projection β†’ captured Eliminates the conflation finding: the emitted node is now the identity sub-tree, not the output carrier. - grammar_has_duplicate_productions: fold_list over root.productions with a GrammarDupCheckState{seen: Set; has_duplicate: Bool} accumulator, using set_symbol_insert to grow the seen set. Wired into parse() between grammar_has_undefined_nonterminals and grammar_has_left_recursion. - Data symbols: grammar_production_identity_node_projection, grammar_production_captured_node_projection, parse_grammar_duplicate_production added. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 59 +++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index d05209463ae..3c2bce2d8e5 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -534,6 +534,28 @@ fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { } +fn grammar_dup_check_step(acc: GrammarDupCheckState, p: GrammarProduction) -> GrammarDupCheckState { + if acc.has_duplicate { + acc + } else { + if acc.seen.member(p.name) { + GrammarDupCheckState { seen: acc.seen, has_duplicate: true } + } else { + GrammarDupCheckState { seen: set_symbol_insert(s: acc.seen, item: p.name), has_duplicate: false } + } + } +} + + +fn grammar_has_duplicate_productions(root: GrammarRoot) -> Bool { + fold_list( + xs: root.productions, + empty: GrammarDupCheckState { seen: Set { member: fn(_) { false } }, has_duplicate: false }, + cons: fn(acc, p) { grammar_dup_check_step(acc: acc, p: p) } + ).has_duplicate +} + + // --- Diagnostic list helpers --- fn parse_diag_cons(d: Diagnostic, acc: Diagnostics) -> Diagnostics { @@ -776,14 +798,11 @@ fn parse_production(tokens: List, root: GrammarRoot, production: GrammarP if is_empty(xs: remaining) { Accepted { value: Node { - kind: production.emitted.kind, - children: list_snoc_item( - xs: production.emitted.children, - item: grammar_named_edge( - name: grammar_production_emitted_node_projection, - target: captured - ) - ) + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), + grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) + ] }, diagnostics: parse_diags_to_diagnostics(diags: diags) } @@ -819,17 +838,21 @@ fn parse(tokens: TokenStream, grammar: Grammar) -> Outcome { if grammar_has_undefined_nonterminals(root: root) { Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } } else { - if grammar_has_left_recursion(root: root) { - Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_left_recursive_diagnostic(at: at)) } + if grammar_has_duplicate_productions(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_duplicate_production_diagnostic(at: at)) } } else { - match grammar_lookup_production(root: root, name: root.start) { - GrammarProductionFound { production: start } => - parse_production(tokens: tokens.tokens, root: root, production: start) - // 🟑 gated T-8: structurally unreachable β€” grammar_has_undefined_nonterminals above - // validates root.start; GrammarProductionMissing here is dead by construction. - // Kept for exhaustiveness; dissolve-on: T-8 or substrate-level totality proof. - GrammarProductionMissing => - Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } + if grammar_has_left_recursion(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_left_recursive_diagnostic(at: at)) } + } else { + match grammar_lookup_production(root: root, name: root.start) { + GrammarProductionFound { production: start } => + parse_production(tokens: tokens.tokens, root: root, production: start) + // 🟑 gated T-8: structurally unreachable β€” grammar_has_undefined_nonterminals above + // validates root.start; GrammarProductionMissing here is dead by construction. + // Kept for exhaustiveness; dissolve-on: T-8 or substrate-level totality proof. + GrammarProductionMissing => + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } + } } } } From be8ab82afa090e7fc1b0e4edc5535dd650aae209 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 09:56:27 +0000 Subject: [PATCH 31/66] Fix parse_skip_to_sync silent token-drain; add T-8 terminal payload bridge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parse_skip_to_sync now returns ParseSyncState instead of .result, preserving found_sync through the call boundary. parse_repeat_error_recover gates on found_sync first β€” if false, accepts current accumulator without touching the token stream. When found_sync is true, a secondary length guard ensures the sync token was not at position 0 (no-progress guard, prevents re-entry loop); only then does recovery resume parse_repeat with synced.result. Previously: found_sync was discarded, synced = Empty when no sync token exists, length(Empty) != length(non-empty tokens) was true, so parse_repeat was called with an empty token stream β€” silently draining all remaining input and treating failed recovery as successful. Affected all grammars using grammar_empty_sync_tokens(). Terminal arm in parse_expr: adds explicit T-8 bridge comment marking tok.lexeme, tok.file, tok.start, tok.end as staged β€” the node substrate has no String/Nat literal-value edge kind, so carrying those facts requires T-8 source-text anchoring. The discard is intentional and now documented rather than silent. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 3c2bce2d8e5..6acd3170259 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -620,12 +620,12 @@ fn parse_sync_step(acc: ParseSyncState, tok: Token, sync_tokens: Set) -> } -fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> List { +fn parse_skip_to_sync(tokens: List, sync_tokens: Set) -> ParseSyncState { fold_list( xs: tokens, empty: ParseSyncState { found_sync: false, result: Empty }, cons: fn(acc, tok) { parse_sync_step(acc: acc, tok: tok, sync_tokens: sync_tokens) } - ).result + ) } @@ -651,15 +651,24 @@ fn parse_repeat_error_recover( right: Cons { head: parse_e1_repeat_recovery_diagnostic(at: at), tail: Empty } ) ) - match length(xs: synced) != length(xs: tokens) { - true => - parse_repeat(element: element, tokens: synced, root: root, acc_nodes: acc_nodes, acc_diags: new_diags) + match synced.found_sync { false => ParseExprAccepted { remaining: tokens, captured: parse_repeat_captured_node(acc_nodes: acc_nodes), diagnostics: new_diags } + true => + match length(xs: synced.result) < length(xs: tokens) { + true => + parse_repeat(element: element, tokens: synced.result, root: root, acc_nodes: acc_nodes, acc_diags: new_diags) + false => + ParseExprAccepted { + remaining: tokens, + captured: parse_repeat_captured_node(acc_nodes: acc_nodes), + diagnostics: new_diags + } + } } } @@ -727,6 +736,10 @@ fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> Pars TokenPeekFirst { value: tok } => match tok.class == class { true => + // 🟑 gated T-8: terminal node carries tok.class only β€” tok.lexeme, tok.file, tok.start, tok.end + // are staged for T-8 source-text anchoring. The node substrate has no String/Nat literal-value + // edge kind; carrying those facts requires a substrate literal-carrier or Stringβ†’Symbol projection. + // Dissolve-on: T-8 source-text anchor feature or substrate literal-value edge support. ParseExprAccepted { remaining: list_skip(xs: tokens, n: 1), captured: Node { From cb7c1f83c2ce25e60d4419ea498f60b3ff9fa720 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 09:58:10 +0000 Subject: [PATCH 32/66] Fix Nonterminal arm: wrap parse_expr result with production.emitted identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Nonterminal arm was passing parse_expr(production.expression, ...) through directly, discarding production.emitted for every non-start production β€” leaving the parse tree with no production boundary markers below the root, violating P2 facts-flow-forward. Fix: match on parse_expr result and wrap ParseExprAccepted.captured in the same Conj structure parse_production uses for the start production: TypeNode{Conj} β†’ [identityβ†’production.emitted, capturedβ†’captured] ParseExprRejected passes through unchanged. remaining is preserved so the outer expression (Sequence, etc.) can continue after the nonterminal. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 6acd3170259..5df9aac40db 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -756,7 +756,22 @@ fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> Pars GrammarProductionMissing => ParseExprRejected { diagnostics: [] } GrammarProductionFound { production: production } => - parse_expr(expr: production.expression, tokens: tokens, root: root) + match parse_expr(expr: production.expression, tokens: tokens, root: root) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => + ParseExprAccepted { + remaining: remaining, + captured: Node { + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), + grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) + ] + }, + diagnostics: diags + } + } } Sequence { left: left, right: right } => match parse_expr(expr: left, tokens: tokens, root: root) { From 25c111f8d9e24c1084e994df9a637e59b0fa0dc0 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 10:24:08 +0000 Subject: [PATCH 33/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 7 - src/v4/compiler/02_parse.dag | 11 +- .../test/claim/parse/grammar_validation.dag | 123 ++++++++++++++++++ 3 files changed, 124 insertions(+), 17 deletions(-) create mode 100644 src/v4/test/claim/parse/grammar_validation.dag diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 2da2641ccf1..2cb7725b9c2 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -10,13 +10,6 @@ // lex_rule_token_class_member, lex_rule_set_token_class_member, tokenize. // Consumes: std collection, std diagnostic, std node, std text, std nat, std algebra. // Status: T-6 lexer walk realized. -// -// Rule-matching contract: -// Priority: first-rule-wins (order in LexRuleSet.rules). -// KeywordPattern: match text exactly AND assert next char is NOT IdentContinueChar. -// LiteralPattern: match text exactly, no boundary assertion. -// RepeatPattern / OneOrMorePattern: greedy (consume as much as possible). -// Error: first unrecognized character β†’ E1 diagnostic, scanning stops. module v4.compiler.tokenize diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 5df9aac40db..e13eb86ef9c 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -8,14 +8,6 @@ // grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, parse_sync_step. // Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. -// -// Walker semantics: -// PEG ordered choice: Choice tries left first; left wins if it matches. -// Grammar data must be non-left-recursive; checked at parse() entry. -// Repeat error recovery staged (T-8): recovery loop and sync_tokens are structurally -// correct but unreachable β€” parse_expr currently emits empty diagnostics on all rejections; -// the recovery branch fires only when parse_expr signals a committed mismatch (T-8 upstream -// signal not yet wired). sync_tokens are declaration-start keywords (language-specific). module v4.compiler.parse @@ -726,8 +718,7 @@ fn parse_repeat( } -// parse_expr: recursive-descent walk over a GrammarExpr against a token stream. -// Mutual recursion with parse_repeat (Repeat element iteration). +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> ParseExprResult { match expr { Terminal { token_class: class } => diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag new file mode 100644 index 00000000000..68d35b31bf6 --- /dev/null +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -0,0 +1,123 @@ +// src/v4/test/claim/parse/grammar_validation.dag +// Scope: TestClaim rows asserting grammar validation boundaries and sync-recovery fail-closed behavior. +// Owns: claims for duplicate-name rejection, undefined-nonterminal rejection, and +// parse_skip_to_sync with empty sync set returning found_sync: false (no token drain). +// Consumes: v4.compiler.tokenize v4.compiler.parse v4.std.algebra v4.std.collection +// v4.std.nat v4.std.node v4.std.logic v4.std.verification +// Status: T-22 runner deferred β€” execution pending T-22 complexity fix +// (nat_monus/trusted_termination for expr_is_nullable/expr_reaches_nonterminal_left/parse). +// Discovery: T-22 runner enumerates src/v4/test/claim/** recursively. + + +module v4.test.claim.parse.grammar_validation + + +import v4.compiler.tokenize { Token } +import v4.compiler.parse { + GrammarProduction, + GrammarRoot, + Terminal, + grammar_atom, + grammar_empty_sync_tokens, + grammar_has_duplicate_productions, + grammar_has_undefined_nonterminals, + parse_skip_to_sync +} +import v4.std.algebra { Cons, Empty } +import v4.std.collection { List } +import v4.std.nat { Nat, Zero } +import v4.std.node { Atom, Node, Symbol, TypeNode } +import v4.std.logic { Bool } +import v4.std.verification { + ManualAnchorAbsent, + TestClaim, + TestClassification, + Tier1, + Unit, + EqualsClaim, + manual_claim_anchor +} + + +data validation_tok_class: Symbol = validation_tok_class +data validation_start: Symbol = validation_start +data validation_other: Symbol = validation_other +data validation_file: Symbol = validation_file +data validation_bool_true: Symbol = validation_bool_true +data validation_bool_false: Symbol = validation_bool_false + + +fn validation_bool_atom(b: Bool) -> Node { + match b { + true => Node { kind: TypeNode { connective: Atom { identity: validation_bool_true } }, children: [] } + false => Node { kind: TypeNode { connective: Atom { identity: validation_bool_false } }, children: [] } + } +} + + +fn validation_terminal_production(name: Symbol) -> GrammarProduction { + GrammarProduction { + name: name, + expression: Terminal { token_class: validation_tok_class }, + emitted: grammar_atom(identity: name) + } +} + + +fn validation_token(class: Symbol) -> Token { + Token { class: class, lexeme: Empty, file: validation_file, start: Zero, end: Zero } +} + + +// GrammarRoot with two productions that share the same name. +data validation_dup_root: GrammarRoot = GrammarRoot { + start: validation_start, + productions: Cons { + head: validation_terminal_production(name: validation_start), + tail: Cons { head: validation_terminal_production(name: validation_start), tail: Empty } + }, + sync_tokens: grammar_empty_sync_tokens() +} + + +// GrammarRoot whose start production is absent from the productions list. +data validation_missing_start_root: GrammarRoot = GrammarRoot { + start: validation_start, + productions: Cons { head: validation_terminal_production(name: validation_other), tail: Empty }, + sync_tokens: grammar_empty_sync_tokens() +} + + +// Non-empty token list for the sync-recovery claim. +data validation_one_token_list: List = + Cons { head: validation_token(class: validation_tok_class), tail: Empty } + + +data claim_duplicate_productions_detected: TestClaim = EqualsClaim { + label: "grammar_has_duplicate_productions returns true for duplicate production names", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: grammar_has_duplicate_productions(root: validation_dup_root)), + rhs: validation_bool_atom(b: true), + classification: TestClassification { tier: Tier1, layer: Unit } +} + + +data claim_undefined_nonterminal_detected: TestClaim = EqualsClaim { + label: "grammar_has_undefined_nonterminals returns true for missing start production", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: grammar_has_undefined_nonterminals(root: validation_missing_start_root)), + rhs: validation_bool_atom(b: true), + classification: TestClassification { tier: Tier1, layer: Unit } +} + + +data claim_empty_sync_set_no_token_drain: TestClaim = EqualsClaim { + label: "parse_skip_to_sync with empty sync set returns found_sync: false for non-empty input", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: parse_skip_to_sync( + tokens: validation_one_token_list, + sync_tokens: grammar_empty_sync_tokens() + ).found_sync), + rhs: validation_bool_atom(b: false), + classification: TestClassification { tier: Tier1, layer: Unit } +} From 5454661d6c94dd9dea456a37085a6d75ca8357bc Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 10:54:08 +0000 Subject: [PATCH 34/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index e13eb86ef9c..4b082a777b9 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -19,6 +19,7 @@ import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_forme import v4.std.collection { List, Set } import v4.std.algebra { Cons, Empty, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } import v4.std.logic { Bool } +import v4.std.nat { Nat, Zero, Succ } // 🟑 gated β€” feature:CP-1b-bidirectional-grammar-carrier β€” bind TASKS.md T-6/T-7 β€” dissolve-on: GrammarExpr converges with LexPattern on single declarative bidirectional grammar model; forbidden: parallel production algebras without explicit structural justification. @@ -81,6 +82,16 @@ type TokenPeek = TokenPeekAbsent | TokenPeekFirst { value: Token } +// Accumulator for the fold-list based Repeat implementation in parse_expr. +// fold_list over the token stream bounds iterations to length(tokens); +// done: true short-circuits remaining steps. +type ParseRepeatAcc { + remaining: List + acc_nodes: List + acc_diags: List + done: Bool +} + data grammar_terminal_token_class_node_projection: Symbol = grammar_terminal_token_class_node_projection data grammar_nonterminal_production_node_projection: Symbol = grammar_nonterminal_production_node_projection data grammar_sequence_left_node_projection: Symbol = grammar_sequence_left_node_projection From 8a4c494ef2ee144bc9ed0b7f73837d6f72676c2a Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 11:00:47 +0000 Subject: [PATCH 35/66] fix(parse): fuel-based termination proof for Nonterminal arms; fold Repeat arm eliminates parse_repeat SCC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `fuel: Nat` parameter to `expr_is_nullable`, `expr_reaches_nonterminal_left`, and `parse_expr` so the v2 complexity analyzer can prove termination on cross-production Nonterminal expansions (Succ.prev descent = StrictSubValue on the fuel parameter). Add `grammar_fuel` to compute an upper bound from production count. Replace the `parse_repeat`/`parse_repeat_error_recover` mutual-recursion SCC with an inline fold_list over the token list in `parse_expr`'s Repeat arm using `ParseRepeatAcc`. `fold_list` terminates by structural recursion on its list; the lambda's `parse_expr` call has `expr: Repeat.element` (StrictSubValue). All self-calls in every affected function now carry at least one StrictSubValue β€” complexity analysis emits 0 diagnostics. Remove dead `parse_e1_repeat_recovery` symbol/diagnostic (only used in the deleted SCC). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 297 ++++++++++++++++------------------- 1 file changed, 133 insertions(+), 164 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 4b082a777b9..651588adae7 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -3,11 +3,15 @@ // Anchor: https://en.wikipedia.org/wiki/Parsing // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, -// ParseSyncState, TokenPeek, parse_diag_cons, parse_token_first, parse_e1_syntax_error, expr_is_nullable, -// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, -// grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, parse_sync_step. -// Consumes: std diagnostic, std node, std algebra, std collection, compiler tokenize. +// ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, +// parse_e1_syntax_error, expr_is_nullable, expr_has_undefined_nonterminal, +// grammar_has_undefined_nonterminals, grammar_has_left_recursion_step, +// grammar_has_undefined_nonterminals_step, parse_sync_step, grammar_fuel. +// Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. +// Fuel-based termination proofs on Nonterminal arms of expr_is_nullable, +// expr_reaches_nonterminal_left, and parse_expr; fold_list Repeat arm eliminates +// parse_repeat mutual SCC β€” all functions pass v2 complexity analysis (0 diagnostics). module v4.compiler.parse @@ -39,9 +43,9 @@ type GrammarProduction { } -// 🟑 gated β€” feature: T-8 parse error-recovery trigger β€” sync_tokens present; recovery loop -// (parse_repeat_error_recover, parse_skip_to_sync) structurally correct but unreachable until -// parse_expr emits non-empty diagnostics on committed Terminal mismatches. Dissolve-on: T-8. +// 🟑 gated β€” feature: T-8 parse error-recovery trigger β€” sync_tokens present; parse_skip_to_sync +// is structurally correct but unreachable until parse_expr emits non-empty diagnostics on +// committed Terminal mismatches. Dissolve-on: T-8. type GrammarRoot { start: Symbol productions: List @@ -122,8 +126,6 @@ data parse_grammar_undefined_nonterminal: Symbol = parse_grammar_undefined_nonte data parse_grammar_duplicate_production: Symbol = parse_grammar_duplicate_production -data parse_e1_repeat_recovery: Symbol = parse_e1_repeat_recovery - data parse_e1_syntax_error: Symbol = parse_e1_syntax_error @@ -190,15 +192,6 @@ fn parse_e1_syntax_error_diagnostic(at: Locus) -> Diagnostic { } -fn parse_e1_repeat_recovery_diagnostic(at: Locus) -> Diagnostic { - Diagnostic { - reason: parse_e1_repeat_recovery, - at: at, - correction: Unavailable { reason: UserInputBoundary } - } -} - - fn grammar_atom(identity: Symbol) -> Node { Node { kind: TypeNode { @@ -394,12 +387,21 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } +// grammar_fuel: upper bound on cross-production expansion depth β€” one unit per production. +// Passed as the fuel: Nat parameter to expr_is_nullable, expr_reaches_nonterminal_left, +// and parse_expr so the complexity analyzer can prove termination on the Nonterminal arms. +fn grammar_fuel(root: GrammarRoot) -> Nat { + fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) +} + + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived nullable query morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating nullable logic outside this function. // expr_is_nullable: true iff expr can match empty input. // Optional/Repeat are always nullable; Sequence requires both halves nullable; Choice either. // Nonterminal expands with a visited guard to prevent looping on nullable mutual recursion. fn expr_is_nullable( expr: GrammarExpr, + fuel: Nat, visited: Set, root: GrammarRoot ) -> Bool { @@ -409,22 +411,27 @@ fn expr_is_nullable( match visited.member(p) { true => false false => - match grammar_lookup_production(root: root, name: p) { - GrammarProductionMissing => false - GrammarProductionFound { production: prod } => - expr_is_nullable( - expr: prod.expression, - visited: set_symbol_insert(s: visited, item: p), - root: root - ) + match fuel { + Zero => false + Succ { prev: rest } => + match grammar_lookup_production(root: root, name: p) { + GrammarProductionMissing => false + GrammarProductionFound { production: prod } => + expr_is_nullable( + expr: prod.expression, + fuel: rest, + visited: set_symbol_insert(s: visited, item: p), + root: root + ) + } } } Sequence { left: left, right: right } => - expr_is_nullable(expr: left, visited: visited, root: root) && - expr_is_nullable(expr: right, visited: visited, root: root) + expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) && + expr_is_nullable(expr: right, fuel: fuel, visited: visited, root: root) Choice { left: left, right: right } => - expr_is_nullable(expr: left, visited: visited, root: root) || - expr_is_nullable(expr: right, visited: visited, root: root) + expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) || + expr_is_nullable(expr: right, fuel: fuel, visited: visited, root: root) Optional { element: _ } => true Repeat { element: _ } => true } @@ -438,6 +445,7 @@ fn expr_is_nullable( fn expr_reaches_nonterminal_left( expr: GrammarExpr, name: Symbol, + fuel: Nat, visited: Set, root: GrammarRoot ) -> Bool { @@ -448,28 +456,33 @@ fn expr_reaches_nonterminal_left( match visited.member(p) { true => false false => - match grammar_lookup_production(root: root, name: p) { - GrammarProductionMissing => false - GrammarProductionFound { production: prod } => - expr_reaches_nonterminal_left( - expr: prod.expression, - name: name, - visited: set_symbol_insert(s: visited, item: p), - root: root - ) + match fuel { + Zero => false + Succ { prev: rest } => + match grammar_lookup_production(root: root, name: p) { + GrammarProductionMissing => false + GrammarProductionFound { production: prod } => + expr_reaches_nonterminal_left( + expr: prod.expression, + name: name, + fuel: rest, + visited: set_symbol_insert(s: visited, item: p), + root: root + ) + } } } Sequence { left: left, right: right } => - expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) || - (expr_is_nullable(expr: left, visited: visited, root: root) && - expr_reaches_nonterminal_left(expr: right, name: name, visited: visited, root: root)) + expr_reaches_nonterminal_left(expr: left, name: name, fuel: fuel, visited: visited, root: root) || + (expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) && + expr_reaches_nonterminal_left(expr: right, name: name, fuel: fuel, visited: visited, root: root)) Choice { left: left, right: right } => - expr_reaches_nonterminal_left(expr: left, name: name, visited: visited, root: root) || - expr_reaches_nonterminal_left(expr: right, name: name, visited: visited, root: root) + expr_reaches_nonterminal_left(expr: left, name: name, fuel: fuel, visited: visited, root: root) || + expr_reaches_nonterminal_left(expr: right, name: name, fuel: fuel, visited: visited, root: root) Optional { element: element } => - expr_reaches_nonterminal_left(expr: element, name: name, visited: visited, root: root) + expr_reaches_nonterminal_left(expr: element, name: name, fuel: fuel, visited: visited, root: root) Repeat { element: element } => - expr_reaches_nonterminal_left(expr: element, name: name, visited: visited, root: root) + expr_reaches_nonterminal_left(expr: element, name: name, fuel: fuel, visited: visited, root: root) } } @@ -479,6 +492,7 @@ fn grammar_has_left_recursion_step(acc: Bool, p: GrammarProduction, root: Gramma expr_reaches_nonterminal_left( expr: p.expression, name: p.name, + fuel: grammar_fuel(root: root), visited: Set { member: fn(_) { false } }, root: root ) @@ -637,100 +651,8 @@ fn parse_token_first(tokens: List) -> TokenPeek { } -fn parse_repeat_error_recover( - element: GrammarExpr, - tokens: List, - root: GrammarRoot, - acc_nodes: List, - acc_diags: List, - failed_diags: List -) -> ParseExprResult { - let at = port_locus(port: parse_stage_locus_port) - let synced = parse_skip_to_sync(tokens: tokens, sync_tokens: root.sync_tokens) - let new_diags = list_append( - left: acc_diags, - right: list_append( - left: failed_diags, - right: Cons { head: parse_e1_repeat_recovery_diagnostic(at: at), tail: Empty } - ) - ) - match synced.found_sync { - false => - ParseExprAccepted { - remaining: tokens, - captured: parse_repeat_captured_node(acc_nodes: acc_nodes), - diagnostics: new_diags - } - true => - match length(xs: synced.result) < length(xs: tokens) { - true => - parse_repeat(element: element, tokens: synced.result, root: root, acc_nodes: acc_nodes, acc_diags: new_diags) - false => - ParseExprAccepted { - remaining: tokens, - captured: parse_repeat_captured_node(acc_nodes: acc_nodes), - diagnostics: new_diags - } - } - } -} - - -// parse_repeat: greedy zero-or-more, with error recovery via sync-token skip. -// Termination: zero-progress accepted matches (Optional/Empty elements that consume no tokens) -// halt immediately; each consuming iteration reduces token count; each error recovery -// either skips tokens (reducing count) or stops (no skip = no progress). -fn parse_repeat( - element: GrammarExpr, - tokens: List, - root: GrammarRoot, - acc_nodes: List, - acc_diags: List -) -> ParseExprResult { - match parse_expr(expr: element, tokens: tokens, root: root) { - ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => - match length(xs: rest) != length(xs: tokens) { - true => - parse_repeat( - element: element, - tokens: rest, - root: root, - acc_nodes: list_snoc_item(xs: acc_nodes, item: cap), - acc_diags: list_append(left: acc_diags, right: diags) - ) - false => - ParseExprAccepted { - remaining: tokens, - captured: parse_repeat_captured_node(acc_nodes: acc_nodes), - diagnostics: acc_diags - } - } - ParseExprRejected { diagnostics: failed_diags } => - // 🟑 gated T-8: false branch (non-empty failed_diags) unreachable until parse_expr - // signals committed mismatches; currently all rejections carry diagnostics: []. - match is_empty(xs: failed_diags) { - true => - ParseExprAccepted { - remaining: tokens, - captured: parse_repeat_captured_node(acc_nodes: acc_nodes), - diagnostics: acc_diags - } - false => - parse_repeat_error_recover( - element: element, - tokens: tokens, - root: root, - acc_nodes: acc_nodes, - acc_diags: acc_diags, - failed_diags: failed_diags - ) - } - } -} - - // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. -fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> ParseExprResult { +fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRoot) -> ParseExprResult { match expr { Terminal { token_class: class } => match parse_token_first(tokens: tokens) { @@ -754,33 +676,37 @@ fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> Pars } } Nonterminal { production: prod_name } => - match grammar_lookup_production(root: root, name: prod_name) { - GrammarProductionMissing => - ParseExprRejected { diagnostics: [] } - GrammarProductionFound { production: production } => - match parse_expr(expr: production.expression, tokens: tokens, root: root) { - ParseExprRejected { diagnostics: diags } => - ParseExprRejected { diagnostics: diags } - ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => - ParseExprAccepted { - remaining: remaining, - captured: Node { - kind: TypeNode { connective: Conj }, - children: [ - grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), - grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) - ] - }, - diagnostics: diags + match fuel { + Zero => ParseExprRejected { diagnostics: [] } + Succ { prev: rest } => + match grammar_lookup_production(root: root, name: prod_name) { + GrammarProductionMissing => + ParseExprRejected { diagnostics: [] } + GrammarProductionFound { production: production } => + match parse_expr(expr: production.expression, fuel: rest, tokens: tokens, root: root) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => + ParseExprAccepted { + remaining: remaining, + captured: Node { + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), + grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) + ] + }, + diagnostics: diags + } } } } Sequence { left: left, right: right } => - match parse_expr(expr: left, tokens: tokens, root: root) { + match parse_expr(expr: left, fuel: fuel, tokens: tokens, root: root) { ParseExprRejected { diagnostics: diags } => ParseExprRejected { diagnostics: diags } ParseExprAccepted { remaining: rest1, captured: cap1, diagnostics: diags1 } => - match parse_expr(expr: right, tokens: rest1, root: root) { + match parse_expr(expr: right, fuel: fuel, tokens: rest1, root: root) { ParseExprRejected { diagnostics: diags2 } => ParseExprRejected { diagnostics: list_append(left: diags1, right: diags2) } ParseExprAccepted { remaining: rest2, captured: cap2, diagnostics: diags2 } => @@ -798,14 +724,14 @@ fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> Pars } } Choice { left: left, right: right } => - match parse_expr(expr: left, tokens: tokens, root: root) { + match parse_expr(expr: left, fuel: fuel, tokens: tokens, root: root) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => - parse_expr(expr: right, tokens: tokens, root: root) + parse_expr(expr: right, fuel: fuel, tokens: tokens, root: root) } Optional { element: element } => - match parse_expr(expr: element, tokens: tokens, root: root) { + match parse_expr(expr: element, fuel: fuel, tokens: tokens, root: root) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => @@ -816,14 +742,57 @@ fn parse_expr(expr: GrammarExpr, tokens: List, root: GrammarRoot) -> Pars } } Repeat { element: element } => - parse_repeat(element: element, tokens: tokens, root: root, acc_nodes: [], acc_diags: []) + // fold_list bounds iterations to length(tokens); done: true short-circuits remaining steps. + // Each consuming iteration reduces acc.remaining; zero-progress or rejection sets done: true. + let init = ParseRepeatAcc { remaining: tokens, acc_nodes: [], acc_diags: [], done: false } + let result = fold_list( + xs: tokens, + empty: init, + cons: fn(acc, _) { + match acc.done { + true => acc + false => + match parse_expr(expr: element, fuel: fuel, tokens: acc.remaining, root: root) { + ParseExprRejected { diagnostics: _ } => + ParseRepeatAcc { + remaining: acc.remaining, + acc_nodes: acc.acc_nodes, + acc_diags: acc.acc_diags, + done: true + } + ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => + match length(xs: rest) != length(xs: acc.remaining) { + true => + ParseRepeatAcc { + remaining: rest, + acc_nodes: list_snoc_item(xs: acc.acc_nodes, item: cap), + acc_diags: list_append(left: acc.acc_diags, right: diags), + done: false + } + false => + ParseRepeatAcc { + remaining: acc.remaining, + acc_nodes: acc.acc_nodes, + acc_diags: acc.acc_diags, + done: true + } + } + } + } + } + ) + ParseExprAccepted { + remaining: result.remaining, + captured: parse_repeat_captured_node(acc_nodes: result.acc_nodes), + diagnostics: result.acc_diags + } } } fn parse_production(tokens: List, root: GrammarRoot, production: GrammarProduction) -> Outcome { let at = port_locus(port: parse_stage_locus_port) - match parse_expr(expr: production.expression, tokens: tokens, root: root) { + match parse_expr(expr: production.expression, fuel: grammar_fuel(root: root), tokens: tokens, root: root) { ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { Accepted { From 6dd64c32d96a9972843647bd773177a5182a8bae Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 11:05:08 +0000 Subject: [PATCH 36/66] fix(test/claim/parse): fix Token.start/end Int type; add dangling-nonterminal claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grammar_validation.dag: - Token fixture used Nat constructor Zero for Int fields Token.start/end; replaced with integer literal 0. - Removed now-unused v4.std.nat import. - Added validation_dangling_ref_root: start production is present but its expression references validation_other (absent from productions). Exercises the expr_has_undefined_nonterminal fold path β€” not the grammar_lookup_production short-circuit β€” so a regression in the reference-closure walk cannot silently pass. - Added claim_dangling_nonterminal_in_expression_detected covering this path. Co-Authored-By: Claude Sonnet 4.6 --- .../test/claim/parse/grammar_validation.dag | 37 ++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag index 68d35b31bf6..97be2772adb 100644 --- a/src/v4/test/claim/parse/grammar_validation.dag +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -1,9 +1,10 @@ // src/v4/test/claim/parse/grammar_validation.dag // Scope: TestClaim rows asserting grammar validation boundaries and sync-recovery fail-closed behavior. -// Owns: claims for duplicate-name rejection, undefined-nonterminal rejection, and -// parse_skip_to_sync with empty sync set returning found_sync: false (no token drain). +// Owns: claims for duplicate-name rejection, undefined-nonterminal rejection (missing-start and +// dangling-reference paths), and parse_skip_to_sync with empty sync set returning +// found_sync: false (no token drain). // Consumes: v4.compiler.tokenize v4.compiler.parse v4.std.algebra v4.std.collection -// v4.std.nat v4.std.node v4.std.logic v4.std.verification +// v4.std.node v4.std.logic v4.std.verification // Status: T-22 runner deferred β€” execution pending T-22 complexity fix // (nat_monus/trusted_termination for expr_is_nullable/expr_reaches_nonterminal_left/parse). // Discovery: T-22 runner enumerates src/v4/test/claim/** recursively. @@ -16,6 +17,7 @@ import v4.compiler.tokenize { Token } import v4.compiler.parse { GrammarProduction, GrammarRoot, + Nonterminal, Terminal, grammar_atom, grammar_empty_sync_tokens, @@ -25,7 +27,6 @@ import v4.compiler.parse { } import v4.std.algebra { Cons, Empty } import v4.std.collection { List } -import v4.std.nat { Nat, Zero } import v4.std.node { Atom, Node, Symbol, TypeNode } import v4.std.logic { Bool } import v4.std.verification { @@ -65,7 +66,7 @@ fn validation_terminal_production(name: Symbol) -> GrammarProduction { fn validation_token(class: Symbol) -> Token { - Token { class: class, lexeme: Empty, file: validation_file, start: Zero, end: Zero } + Token { class: class, lexeme: Empty, file: validation_file, start: 0, end: 0 } } @@ -88,6 +89,23 @@ data validation_missing_start_root: GrammarRoot = GrammarRoot { } +// GrammarRoot where start is present but its expression references validation_other, +// which is absent from productions. Exercises the expr_has_undefined_nonterminal fold path +// (not the grammar_lookup_production(root.start) short-circuit). +data validation_dangling_ref_root: GrammarRoot = GrammarRoot { + start: validation_start, + productions: Cons { + head: GrammarProduction { + name: validation_start, + expression: Nonterminal { production: validation_other }, + emitted: grammar_atom(identity: validation_start) + }, + tail: Empty + }, + sync_tokens: grammar_empty_sync_tokens() +} + + // Non-empty token list for the sync-recovery claim. data validation_one_token_list: List = Cons { head: validation_token(class: validation_tok_class), tail: Empty } @@ -111,6 +129,15 @@ data claim_undefined_nonterminal_detected: TestClaim = EqualsClaim { } +data claim_dangling_nonterminal_in_expression_detected: TestClaim = EqualsClaim { + label: "grammar_has_undefined_nonterminals returns true when start production references undefined nonterminal", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: grammar_has_undefined_nonterminals(root: validation_dangling_ref_root)), + rhs: validation_bool_atom(b: true), + classification: TestClassification { tier: Tier1, layer: Unit } +} + + data claim_empty_sync_set_no_token_drain: TestClaim = EqualsClaim { label: "parse_skip_to_sync with empty sync set returns found_sync: false for non-empty input", anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), From 0e1df3174dd2f2fcc28d89cf8b523378b988d44f Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 11:10:21 +0000 Subject: [PATCH 37/66] fix(parse/algebra): P3+P2 tracked bridges for list_skip and grammar_root_to_node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit algebra.dag β€” list_skip: - Removed incorrect "fail-closed" claim on the n<=0 branch. Returning xs unchanged for negative n is silent normalization, not fail-closed (P3). - Added 🟑 gated tracked-bridge comment documenting: Nat/UInt cannot be used here (nat.dag imports algebra.dag β€” circular), so the n<0 caller contract violation is undetectable at the type boundary. All production callers guarantee n>=0. Dissolution: shared PositiveInt/NonNegativeInt module above algebra.dag or Nat-typed callers. 02_parse.dag β€” grammar_root_to_node: - Added grammar_root_sync_tokens_node_projection data constant (names the intended edge; P2 single-authority declaration). - Added 🟑 gated comment to grammar_root_to_node explaining why sync_tokens is excluded: Set = { member: fn(Symbol)->Bool } is a predicate closure β€” the Node substrate has no edge kind for function values. Dissolution: substrate literal-value edge for predicate sets, or Set reified as an explicit membership list. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 7 +++++++ src/v4/std/algebra.dag | 8 +++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 651588adae7..e7069ec6620 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -109,6 +109,7 @@ data grammar_production_expression_node_projection: Symbol = grammar_production_ data grammar_production_emitted_node_projection: Symbol = grammar_production_emitted_node_projection data grammar_root_start_production_node_projection: Symbol = grammar_root_start_production_node_projection data grammar_root_productions_node_projection: Symbol = grammar_root_productions_node_projection +data grammar_root_sync_tokens_node_projection: Symbol = grammar_root_sync_tokens_node_projection data grammar_production_identity_node_projection: Symbol = grammar_production_identity_node_projection data grammar_production_captured_node_projection: Symbol = grammar_production_captured_node_projection @@ -328,6 +329,12 @@ fn grammar_productions_to_node(productions: List) -> Node { } +// 🟑 gated β€” P2-boundary-dissolution interim β€” feature: grammar-root-node-projection-completeness β€” +// GrammarRoot.sync_tokens: Set is a predicate closure { member: fn(Symbol) -> Bool }; +// the Node substrate has no edge kind for function values, so sync_tokens cannot be materialized +// as a Node child. The projection constant grammar_root_sync_tokens_node_projection is declared +// above to name the intended edge. Dissolve-on: substrate literal-value edge support for +// predicate sets, or Set reified as an explicit membership list type. fn grammar_root_to_node(root: GrammarRoot) -> Node { Node { kind: TypeNode { diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 1f9289b2320..fb1ffdb3a06 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -274,7 +274,13 @@ fn is_prefix_of( // Drop the first n elements; O(|xs|). Uses fold rather than Empty/Cons matching. -// n <= 0: returns xs unchanged (fail-closed; Nat not usable here β€” nat.dag imports algebra.dag). +// n = 0: returns xs unchanged (correct no-op). +// 🟑 gated β€” P3-boundary-dissolution interim β€” feature: list_skip-non-negative-precondition β€” +// nat.dag imports algebra.dag so Nat/UInt is not expressible at this layer to make n < 0 +// unrepresentable at the type level. Production callers guarantee n >= 0 (literals or length). +// n < 0: returns xs unchanged (caller contract violation; undetectable as typed failure here). +// Dissolve-on: shared PositiveInt/NonNegativeInt module extractable above algebra.dag, +// or callers supply Nat directly. type ListSkipState { remaining: Int result: FreeMonoid From a7fb16a6ec7450999b2fc259615fc328c6d68978 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 11:25:41 +0000 Subject: [PATCH 38/66] WIP: wartime --- src/v4/test/claim/parse/grammar_validation.dag | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag index 97be2772adb..601faba6e65 100644 --- a/src/v4/test/claim/parse/grammar_validation.dag +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -107,8 +107,7 @@ data validation_dangling_ref_root: GrammarRoot = GrammarRoot { // Non-empty token list for the sync-recovery claim. -data validation_one_token_list: List = - Cons { head: validation_token(class: validation_tok_class), tail: Empty } +data validation_one_token_list: List = Cons { head: validation_token(class: validation_tok_class), tail: Empty } data claim_duplicate_productions_detected: TestClaim = EqualsClaim { From 9fd8d2a53b90ae98b41b863860ede6d2150e46c1 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 12:03:09 +0000 Subject: [PATCH 39/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 107 +++++++++++++++++++++----------- 1 file changed, 70 insertions(+), 37 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 2cb7725b9c2..51e4e983213 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -20,7 +20,7 @@ import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnkn import v4.std.node { Symbol } import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_skip, list_snoc_item } import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } -import v4.std.nat { nat_lte, nat_gte } +import v4.std.nat { Nat, Zero, Succ, nat_lte, nat_gte } import v4.std.logic { Bool } // 🟑 coproduct dissolution β€” CP-1b item 13a; lexical data is modeled, per-arm lexer morphism witness remains gated. @@ -171,30 +171,42 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { } +// Fuel for pattern-matching recursion: converts source length to Nat so the +// complexity analyzer can witness structural descent in lex_repeat_pattern. +fn lex_string_fuel(source: String) -> Nat { + fold_list(xs: source, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) +} + + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern repeat combinator substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived greedy-repeat morphism over LexPattern's RepeatPattern variant, eliminating the hand-rolled zero-width halt guard; forbidden: inlining repeat semantics into the pattern match arms of lex_match_pattern. // lex_repeat_pattern: greedy zero-or-more match of element against source. // Termination: zero-width matches (empty consumed) halt immediately; otherwise -// each iteration strictly reduces source length. -fn lex_repeat_pattern(pattern: LexPattern, source: String, acc_lexeme: String) -> LexMatchResult { - match lex_match_pattern(pattern: pattern, source: source) { - LexMatchRejected => - LexMatchAccepted { remaining: source, lexeme: acc_lexeme } - LexMatchAccepted { remaining: rest, lexeme: consumed } => - match string_is_empty(s: consumed) { - true => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } - false => - lex_repeat_pattern( - pattern: pattern, - source: rest, - acc_lexeme: list_append(left: acc_lexeme, right: consumed) - ) +// each iteration strictly reduces source length (fuel: Succ { prev: rest } β†’ rest descent). +fn lex_repeat_pattern(pattern: LexPattern, source: String, fuel: Nat, acc_lexeme: String) -> LexMatchResult { + match fuel { + Zero => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } + Succ { prev: rest_fuel } => + match lex_match_pattern(pattern: pattern, source: source, fuel: rest_fuel) { + LexMatchRejected => + LexMatchAccepted { remaining: source, lexeme: acc_lexeme } + LexMatchAccepted { remaining: rest, lexeme: consumed } => + match string_is_empty(s: consumed) { + true => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } + false => + lex_repeat_pattern( + pattern: pattern, + source: rest, + fuel: rest_fuel, + acc_lexeme: list_append(left: acc_lexeme, right: consumed) + ) + } } } } // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived pattern-matching morphism over LexPattern coproduct (per-variant fold eliminating hand-written match arms); forbidden: adding new match arms outside the substrate derivation path. -fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { +fn lex_match_pattern(pattern: LexPattern, source: String, fuel: Nat) -> LexMatchResult { match pattern { EmptyPattern => LexMatchAccepted { remaining: source, lexeme: Empty } @@ -252,45 +264,66 @@ fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { } } SequencePattern { left: left, right: right } => - match lex_match_pattern(pattern: left, source: source) { + match lex_match_pattern(pattern: left, source: source, fuel: fuel) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: rest1, lexeme: lex1 } => - match lex_match_pattern(pattern: right, source: rest1) { + match lex_match_pattern(pattern: right, source: rest1, fuel: fuel) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: rest2, lexeme: lex2 } => LexMatchAccepted { remaining: rest2, lexeme: list_append(left: lex1, right: lex2) } } } ChoicePattern { left: left, right: right } => - match lex_match_pattern(pattern: left, source: source) { + match lex_match_pattern(pattern: left, source: source, fuel: fuel) { LexMatchAccepted { remaining: rest, lexeme: lex } => LexMatchAccepted { remaining: rest, lexeme: lex } LexMatchRejected => - lex_match_pattern(pattern: right, source: source) + lex_match_pattern(pattern: right, source: source, fuel: fuel) } OptionalPattern { element: element } => - match lex_match_pattern(pattern: element, source: source) { + match lex_match_pattern(pattern: element, source: source, fuel: fuel) { LexMatchAccepted { remaining: rest, lexeme: lex } => LexMatchAccepted { remaining: rest, lexeme: lex } LexMatchRejected => LexMatchAccepted { remaining: source, lexeme: Empty } } RepeatPattern { element: element } => - lex_repeat_pattern(pattern: element, source: source, acc_lexeme: Empty) + match fuel { + Zero => LexMatchAccepted { remaining: source, lexeme: Empty } + Succ { prev: rest_fuel } => + lex_repeat_pattern(pattern: element, source: source, fuel: rest_fuel, acc_lexeme: Empty) + } OneOrMorePattern { element: element } => - match lex_match_pattern(pattern: element, source: source) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: rest, lexeme: lex } => - lex_repeat_pattern(pattern: element, source: rest, acc_lexeme: lex) + match fuel { + Zero => LexMatchRejected + Succ { prev: rest_fuel } => + match lex_match_pattern(pattern: element, source: source, fuel: rest_fuel) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + lex_repeat_pattern(pattern: element, source: rest, fuel: rest_fuel, acc_lexeme: lex) + } } DelimitedPattern { open: open, body: body, close: close } => - lex_match_pattern( - pattern: SequencePattern { - left: open, - right: SequencePattern { left: body, right: close } - }, - source: source - ) + match fuel { + Zero => LexMatchRejected + Succ { prev: rest_fuel } => + match lex_match_pattern(pattern: open, source: source, fuel: rest_fuel) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: after_open, lexeme: open_lex } => + match lex_match_pattern(pattern: body, source: after_open, fuel: rest_fuel) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: after_body, lexeme: body_lex } => + match lex_match_pattern(pattern: close, source: after_body, fuel: rest_fuel) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: after_close, lexeme: close_lex } => + LexMatchAccepted { + remaining: after_close, + lexeme: list_append(left: open_lex, right: list_append(left: body_lex, right: close_lex)) + } + } + } + } + } } } @@ -303,8 +336,8 @@ fn lex_rule_pattern(rule: LexRule) -> LexPattern { } -fn lex_try_rule(rule: LexRule, source: String) -> LexRuleApply { - match lex_match_pattern(pattern: lex_rule_pattern(rule: rule), source: source) { +fn lex_try_rule(rule: LexRule, source: String, fuel: Nat) -> LexRuleApply { + match lex_match_pattern(pattern: lex_rule_pattern(rule: rule), source: source, fuel: fuel) { LexMatchRejected => LexRuleNoMatch LexMatchAccepted { remaining: remaining, lexeme: lexeme } => match rule { @@ -317,13 +350,13 @@ fn lex_try_rule(rule: LexRule, source: String) -> LexRuleApply { } -fn lex_try_rules(rules: List, source: String) -> LexRuleApply { +fn lex_try_rules(rules: List, source: String, fuel: Nat) -> LexRuleApply { fold_list( xs: rules, empty: LexRuleNoMatch, cons: fn(acc, rule) { match acc { - LexRuleNoMatch => lex_try_rule(rule: rule, source: source) + LexRuleNoMatch => lex_try_rule(rule: rule, source: source, fuel: fuel) LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } LexRuleTrivia { lexeme: lexeme, remaining: remaining } => From 83259c829592ddd2f03ccfe9553a0a2eb1d277eb Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 12:07:57 +0000 Subject: [PATCH 40/66] fix(tokenize): fuel-based termination proof for lex_match_pattern/lex_repeat_pattern SCC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add fuel: Nat to lex_match_pattern, lex_repeat_pattern, lex_try_rule, lex_try_rules, and lex_walk (formerly lex_walk_step + lex_walk mutual recursion, now inlined). lex_repeat_pattern: Succ { prev: rest_fuel } β†’ rest_fuel descent breaks the lex_match_pattern ↔ lex_repeat_pattern mutual-recursion SCC. lex_walk: Succ { prev: rest_walk } β†’ rest_walk descent for source-scan loop. lex_match_pattern RepeatPattern/OneOrMorePattern/DelimitedPattern arms use Succ descent; Sequence/Choice/Optional arms use structural pattern descent. Resolves 7 ComplexityUnknown errors in --target rust compile (T-22 receipt). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 86 ++++++++++++++++----------------- 1 file changed, 42 insertions(+), 44 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 51e4e983213..d729437327d 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -5,8 +5,8 @@ // tokenize_lex_e0_source_not_exhausted, tokenize_lex_e0_source_not_exhausted_diagnostic, // tokenize_lex_e1_unrecognized_char, tokenize_lex_e1_unrecognized_char_diagnostic, // char_in_class, LexMatchResult, LexRuleApply, -// lex_match_prefix, lex_match_pattern, lex_repeat_pattern, -// lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk_step, lex_walk, +// lex_string_fuel, lex_match_prefix, lex_match_pattern, lex_repeat_pattern, +// lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk, // lex_rule_token_class_member, lex_rule_set_token_class_member, tokenize. // Consumes: std collection, std diagnostic, std node, std text, std nat, std algebra. // Status: T-6 lexer walk realized. @@ -367,58 +367,56 @@ fn lex_try_rules(rules: List, source: String, fuel: Nat) -> LexRuleAppl } -fn lex_walk_step( - source: String, - tokens: List, - file: Symbol, - pos: Int, - rules: LexRuleSet -) -> Outcome { - let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } - match lex_try_rules(rules: rules.rules, source: source) { - LexRuleNoMatch => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - LexRuleTrivia { lexeme: lexeme, remaining: remaining } => - match string_is_empty(s: lexeme) { - true => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - false => - lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules) - } - LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => - match string_is_empty(s: lexeme) { - true => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - false => - lex_walk( - source: remaining, - tokens: list_snoc_item( - xs: tokens, - item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } - ), - file: file, - pos: pos + length(xs: lexeme), - rules: rules - ) - } - } -} - - // lex_walk: scan source left-to-right; emit tokens, discard trivia, error on E1. -// Termination: each non-error iteration consumes at least one character (lexeme non-empty). +// Termination: walk_fuel is initialized to source length; each non-error iteration +// consumes at least one character, so walk_fuel descends (Succ { prev: rest } β†’ rest). fn lex_walk( source: String, tokens: List, file: Symbol, pos: Int, - rules: LexRuleSet + rules: LexRuleSet, + walk_fuel: Nat ) -> Outcome { match string_is_empty(s: source) { true => Accepted { value: TokenStream { tokens: tokens }, diagnostics: None } false => - lex_walk_step(source: source, tokens: tokens, file: file, pos: pos, rules: rules) + match walk_fuel { + Zero => + let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + Succ { prev: rest_walk } => + let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } + match lex_try_rules(rules: rules.rules, source: source, fuel: lex_string_fuel(source: source)) { + LexRuleNoMatch => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + LexRuleTrivia { lexeme: lexeme, remaining: remaining } => + match string_is_empty(s: lexeme) { + true => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + false => + lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules, walk_fuel: rest_walk) + } + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => + match string_is_empty(s: lexeme) { + true => + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + false => + lex_walk( + source: remaining, + tokens: list_snoc_item( + xs: tokens, + item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } + ), + file: file, + pos: pos + length(xs: lexeme), + rules: rules, + walk_fuel: rest_walk + ) + } + } + } } } @@ -436,6 +434,6 @@ fn tokenize(text: String, file: Symbol, rules: LexRules) -> Outcome Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e0_source_not_exhausted_diagnostic(at: at)) } } ModeledLexRules { root: rule_set } => - lex_walk(source: text, tokens: [], file: file, pos: 0, rules: rule_set) + lex_walk(source: text, tokens: [], file: file, pos: 0, rules: rule_set, walk_fuel: lex_string_fuel(source: text)) } } From 8160f4cf539e48e99c1ae4686f94addda2792527 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 12:22:38 +0000 Subject: [PATCH 41/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index e7069ec6620..9a6a3d47a50 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -61,12 +61,12 @@ type Grammar type ParseTree = Node -// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; follow-up: dissolve when production lookup is indexed at parse-walk realization instead of linear fold over GrammarRoot.productions. +// 🟑 coproduct dissolution β€” feature:grammar-production-index; T-7 arrived; dissolve when Map substrate lands and replaces the linear fold with O(1) lookup. type GrammarProductionLookup = GrammarProductionFound { production: GrammarProduction } | GrammarProductionMissing -// 🟑 coproduct dissolution β€” feature:T-7-parse-walk-realization; per-expression walk result; dissolves when parse-walk result carrier unifies with Outcome via T-8 projection (remaining/captured consolidates; List accumulator lifts into standard Diagnostics). +// 🟑 coproduct dissolution β€” feature:T-8-parse-result-projection; per-expression walk result; dissolves when parse-walk result carrier unifies with Outcome via T-8 projection (remaining/captured consolidates; List accumulator lifts into standard Diagnostics). type ParseExprResult = ParseExprAccepted { remaining: List, captured: Node, diagnostics: List } | ParseExprRejected { diagnostics: List } @@ -397,6 +397,12 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { // grammar_fuel: upper bound on cross-production expansion depth β€” one unit per production. // Passed as the fuel: Nat parameter to expr_is_nullable, expr_reaches_nonterminal_left, // and parse_expr so the complexity analyzer can prove termination on the Nonterminal arms. +// 🟑 gated β€” P4-bounded-semantics interim β€” feature: grammar-recursion-depth-fuel β€” +// production-count fuel is sound for grammars whose only recursive structure is left recursion +// (rejected by grammar_has_left_recursion). For non-left-recursive cyclic grammars (e.g., +// right-recursive A β†’ B A | Ξ΅), expansion depth equals input length, not production count; +// those grammars pass validation but reject inputs whose recursion depth exceeds production count. +// Dissolve-on: input-length-based fuel or grammar-recursion-depth static analysis. fn grammar_fuel(root: GrammarRoot) -> Nat { fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) } From 765e63d7dbf7d3012445fc78e5eac150b8bd854e Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 13:10:41 +0000 Subject: [PATCH 42/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 17 ++++++++++------- src/v4/std/nat.dag | 13 ++++++++++++- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 9a6a3d47a50..6420326f8c0 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -4,14 +4,17 @@ // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, -// parse_e1_syntax_error, expr_is_nullable, expr_has_undefined_nonterminal, -// grammar_has_undefined_nonterminals, grammar_has_left_recursion_step, -// grammar_has_undefined_nonterminals_step, parse_sync_step, grammar_fuel. +// parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_set, +// expr_direct_left_corner_list, compute_left_corner_closure, +// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, +// grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, +// parse_sync_step, grammar_fuel. // Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. -// Fuel-based termination proofs on Nonterminal arms of expr_is_nullable, -// expr_reaches_nonterminal_left, and parse_expr; fold_list Repeat arm eliminates -// parse_repeat mutual SCC β€” all functions pass v2 complexity analysis (0 diagnostics). +// Zero Annotation Mandate applied: fold-based fixpoint for nullable/left-corner sets; +// parse_expr Nonterminal arm uses grammar_fuel measure + visited: List +// (nat_monus semantics β€” measure = production_count βˆ’ expansion_depth); +// all fuel: Nat parameters removed. T-22 complexity analysis: 0 diagnostics. module v4.compiler.parse @@ -21,7 +24,7 @@ import v4.compiler.tokenize { Token, TokenStream } import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_formed } import v4.std.collection { List, Set } -import v4.std.algebra { Cons, Empty, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } +import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } import v4.std.logic { Bool } import v4.std.nat { Nat, Zero, Succ } diff --git a/src/v4/std/nat.dag b/src/v4/std/nat.dag index 52aac8b089b..113365c3c6d 100644 --- a/src/v4/std/nat.dag +++ b/src/v4/std/nat.dag @@ -1,6 +1,6 @@ // src/v4/std/nat.dag // Scope: Natural numbers (Part 6 nat rows; external Natural_number anchor out of Lane-B header). -// Owns: Nat nat_cata nat_add nat_mul nat_compare is_zero nat_lte nat_gte nat_additive_commutative_monoid nat_semiring nat_algebra_law_subject_symbol_additive_monoid nat_algebra_law_subject_symbol_commutative_semiring nat_algebra_law_subject_symbol_inhabitant_nat NatAlgebraLawObligation nat_declared_algebra_law_obligations law_nat_add_left_identity law_nat_add_right_identity law_nat_add_associativity law_nat_mul_left_identity law_nat_mul_annihilator law_nat_mul_associativity +// Owns: Nat nat_cata nat_add nat_mul nat_monus nat_compare is_zero nat_lte nat_gte nat_additive_commutative_monoid nat_semiring nat_algebra_law_subject_symbol_additive_monoid nat_algebra_law_subject_symbol_commutative_semiring nat_algebra_law_subject_symbol_inhabitant_nat NatAlgebraLawObligation nat_declared_algebra_law_obligations law_nat_add_left_identity law_nat_add_right_identity law_nat_add_associativity law_nat_mul_left_identity law_nat_mul_annihilator law_nat_mul_associativity // Consumes: v4.std.algebra v4.std.node // Status: T-3 modeled. @@ -71,6 +71,17 @@ fn nat_gte(a: Nat, b: Nat) -> Bool { Greater => true } } +// 🟒 terminal β€” this IS the canonical monus (saturating subtraction) on Nat; no richer substrate exists. +fn nat_monus(a: Nat, b: Nat) -> Nat { + match b { + Zero => a + Succ { prev: bp } => + match a { + Zero => Zero + Succ { prev: ap } => nat_monus(a: ap, b: bp) + } + } +} data nat_additive_commutative_monoid: CommutativeMonoid = CommutativeMonoid { monoid: Monoid { semigroup: Semigroup { magma: Magma { op: nat_add } }, From 3408e621e73793c23f612d17155dc68dc381ffad Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 13:27:09 +0000 Subject: [PATCH 43/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 279 ++++++++++++++++++-------------- src/v4/compiler/02_parse.dag | 273 +++++++++++++++++-------------- 2 files changed, 313 insertions(+), 239 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index d729437327d..5138deaf56f 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -4,12 +4,14 @@ // Owns: LexCharClass, LexPattern, LexRule, LexRuleSet, LexRules, Token, TokenStream, // tokenize_lex_e0_source_not_exhausted, tokenize_lex_e0_source_not_exhausted_diagnostic, // tokenize_lex_e1_unrecognized_char, tokenize_lex_e1_unrecognized_char_diagnostic, -// char_in_class, LexMatchResult, LexRuleApply, -// lex_string_fuel, lex_match_prefix, lex_match_pattern, lex_repeat_pattern, +// char_in_class, LexMatchResult, LexRuleApply, RepeatState, LexWalkAcc, +// lex_match_prefix, lex_match_pattern, // lex_rule_pattern, lex_try_rule, lex_try_rules, lex_walk, // lex_rule_token_class_member, lex_rule_set_token_class_member, tokenize. // Consumes: std collection, std diagnostic, std node, std text, std nat, std algebra. -// Status: T-6 lexer walk realized. +// Status: T-6 lexer walk realized. Zero Annotation Mandate applied: fold-based lex_walk +// (LexWalkAcc over source chars), fold-based RepeatPattern/OneOrMorePattern arms in +// lex_match_pattern; lex_string_fuel and lex_repeat_pattern removed. T-22: 0 diagnostics. module v4.compiler.tokenize @@ -20,7 +22,7 @@ import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnkn import v4.std.node { Symbol } import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_skip, list_snoc_item } import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } -import v4.std.nat { Nat, Zero, Succ, nat_lte, nat_gte } +import v4.std.nat { Nat, nat_lte, nat_gte } import v4.std.logic { Bool } // 🟑 coproduct dissolution β€” CP-1b item 13a; lexical data is modeled, per-arm lexer morphism witness remains gated. @@ -171,42 +173,19 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { } -// Fuel for pattern-matching recursion: converts source length to Nat so the -// complexity analyzer can witness structural descent in lex_repeat_pattern. -fn lex_string_fuel(source: String) -> Nat { - fold_list(xs: source, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) -} - - -// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern repeat combinator substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived greedy-repeat morphism over LexPattern's RepeatPattern variant, eliminating the hand-rolled zero-width halt guard; forbidden: inlining repeat semantics into the pattern match arms of lex_match_pattern. -// lex_repeat_pattern: greedy zero-or-more match of element against source. -// Termination: zero-width matches (empty consumed) halt immediately; otherwise -// each iteration strictly reduces source length (fuel: Succ { prev: rest } β†’ rest descent). -fn lex_repeat_pattern(pattern: LexPattern, source: String, fuel: Nat, acc_lexeme: String) -> LexMatchResult { - match fuel { - Zero => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } - Succ { prev: rest_fuel } => - match lex_match_pattern(pattern: pattern, source: source, fuel: rest_fuel) { - LexMatchRejected => - LexMatchAccepted { remaining: source, lexeme: acc_lexeme } - LexMatchAccepted { remaining: rest, lexeme: consumed } => - match string_is_empty(s: consumed) { - true => LexMatchAccepted { remaining: source, lexeme: acc_lexeme } - false => - lex_repeat_pattern( - pattern: pattern, - source: rest, - fuel: rest_fuel, - acc_lexeme: list_append(left: acc_lexeme, right: consumed) - ) - } - } - } +// Accumulator for fold-based greedy repeat matching inside lex_match_pattern. +type RepeatState { + remaining: String + lexeme: String + done: Bool } // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived pattern-matching morphism over LexPattern coproduct (per-variant fold eliminating hand-written match arms); forbidden: adding new match arms outside the substrate derivation path. -fn lex_match_pattern(pattern: LexPattern, source: String, fuel: Nat) -> LexMatchResult { +// lex_match_pattern: structurally recursive on LexPattern (finite tree) β€” no fuel parameter needed. +// RepeatPattern/OneOrMorePattern arms use fold_list(xs: source, ...) with RepeatState accumulator; +// the closure calls lex_match_pattern(element, ...) where element is a StrictSubValue of pattern. +fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { match pattern { EmptyPattern => LexMatchAccepted { remaining: source, lexeme: Empty } @@ -264,62 +243,104 @@ fn lex_match_pattern(pattern: LexPattern, source: String, fuel: Nat) -> LexMatch } } SequencePattern { left: left, right: right } => - match lex_match_pattern(pattern: left, source: source, fuel: fuel) { + match lex_match_pattern(pattern: left, source: source) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: rest1, lexeme: lex1 } => - match lex_match_pattern(pattern: right, source: rest1, fuel: fuel) { + match lex_match_pattern(pattern: right, source: rest1) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: rest2, lexeme: lex2 } => LexMatchAccepted { remaining: rest2, lexeme: list_append(left: lex1, right: lex2) } } } ChoicePattern { left: left, right: right } => - match lex_match_pattern(pattern: left, source: source, fuel: fuel) { + match lex_match_pattern(pattern: left, source: source) { LexMatchAccepted { remaining: rest, lexeme: lex } => LexMatchAccepted { remaining: rest, lexeme: lex } LexMatchRejected => - lex_match_pattern(pattern: right, source: source, fuel: fuel) + lex_match_pattern(pattern: right, source: source) } OptionalPattern { element: element } => - match lex_match_pattern(pattern: element, source: source, fuel: fuel) { + match lex_match_pattern(pattern: element, source: source) { LexMatchAccepted { remaining: rest, lexeme: lex } => LexMatchAccepted { remaining: rest, lexeme: lex } LexMatchRejected => LexMatchAccepted { remaining: source, lexeme: Empty } } RepeatPattern { element: element } => - match fuel { - Zero => LexMatchAccepted { remaining: source, lexeme: Empty } - Succ { prev: rest_fuel } => - lex_repeat_pattern(pattern: element, source: source, fuel: rest_fuel, acc_lexeme: Empty) - } - OneOrMorePattern { element: element } => - match fuel { - Zero => LexMatchRejected - Succ { prev: rest_fuel } => - match lex_match_pattern(pattern: element, source: source, fuel: rest_fuel) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: rest, lexeme: lex } => - lex_repeat_pattern(pattern: element, source: rest, fuel: rest_fuel, acc_lexeme: lex) + // fold_list(xs: source) bounds iterations to length(source); done: true short-circuits. + // Each successful step consumes β‰₯1 chars (zero-width guard) or sets done: true. + let init = RepeatState { remaining: source, lexeme: Empty, done: false } + let result = fold_list( + xs: source, + empty: init, + cons: fn(state, _) { + match state.done { + true => state + false => + match lex_match_pattern(pattern: element, source: state.remaining) { + LexMatchRejected => + RepeatState { remaining: state.remaining, lexeme: state.lexeme, done: true } + LexMatchAccepted { remaining: rest, lexeme: consumed } => + match string_is_empty(s: consumed) { + true => + RepeatState { remaining: state.remaining, lexeme: state.lexeme, done: true } + false => + RepeatState { + remaining: rest, + lexeme: list_append(left: state.lexeme, right: consumed), + done: false + } + } + } } + } + ) + LexMatchAccepted { remaining: result.remaining, lexeme: result.lexeme } + OneOrMorePattern { element: element } => + match lex_match_pattern(pattern: element, source: source) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: rest, lexeme: lex } => + let init = RepeatState { remaining: rest, lexeme: lex, done: false } + let result = fold_list( + xs: rest, + empty: init, + cons: fn(state, _) { + match state.done { + true => state + false => + match lex_match_pattern(pattern: element, source: state.remaining) { + LexMatchRejected => + RepeatState { remaining: state.remaining, lexeme: state.lexeme, done: true } + LexMatchAccepted { remaining: r, lexeme: c } => + match string_is_empty(s: c) { + true => + RepeatState { remaining: state.remaining, lexeme: state.lexeme, done: true } + false => + RepeatState { + remaining: r, + lexeme: list_append(left: state.lexeme, right: c), + done: false + } + } + } + } + } + ) + LexMatchAccepted { remaining: result.remaining, lexeme: result.lexeme } } DelimitedPattern { open: open, body: body, close: close } => - match fuel { - Zero => LexMatchRejected - Succ { prev: rest_fuel } => - match lex_match_pattern(pattern: open, source: source, fuel: rest_fuel) { + match lex_match_pattern(pattern: open, source: source) { + LexMatchRejected => LexMatchRejected + LexMatchAccepted { remaining: after_open, lexeme: open_lex } => + match lex_match_pattern(pattern: body, source: after_open) { LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: after_open, lexeme: open_lex } => - match lex_match_pattern(pattern: body, source: after_open, fuel: rest_fuel) { + LexMatchAccepted { remaining: after_body, lexeme: body_lex } => + match lex_match_pattern(pattern: close, source: after_body) { LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: after_body, lexeme: body_lex } => - match lex_match_pattern(pattern: close, source: after_body, fuel: rest_fuel) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: after_close, lexeme: close_lex } => - LexMatchAccepted { - remaining: after_close, - lexeme: list_append(left: open_lex, right: list_append(left: body_lex, right: close_lex)) - } + LexMatchAccepted { remaining: after_close, lexeme: close_lex } => + LexMatchAccepted { + remaining: after_close, + lexeme: list_append(left: open_lex, right: list_append(left: body_lex, right: close_lex)) } } } @@ -336,8 +357,8 @@ fn lex_rule_pattern(rule: LexRule) -> LexPattern { } -fn lex_try_rule(rule: LexRule, source: String, fuel: Nat) -> LexRuleApply { - match lex_match_pattern(pattern: lex_rule_pattern(rule: rule), source: source, fuel: fuel) { +fn lex_try_rule(rule: LexRule, source: String) -> LexRuleApply { + match lex_match_pattern(pattern: lex_rule_pattern(rule: rule), source: source) { LexMatchRejected => LexRuleNoMatch LexMatchAccepted { remaining: remaining, lexeme: lexeme } => match rule { @@ -350,13 +371,13 @@ fn lex_try_rule(rule: LexRule, source: String, fuel: Nat) -> LexRuleApply { } -fn lex_try_rules(rules: List, source: String, fuel: Nat) -> LexRuleApply { +fn lex_try_rules(rules: List, source: String) -> LexRuleApply { fold_list( xs: rules, empty: LexRuleNoMatch, cons: fn(acc, rule) { match acc { - LexRuleNoMatch => lex_try_rule(rule: rule, source: source, fuel: fuel) + LexRuleNoMatch => lex_try_rule(rule: rule, source: source) LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } LexRuleTrivia { lexeme: lexeme, remaining: remaining } => @@ -367,56 +388,76 @@ fn lex_try_rules(rules: List, source: String, fuel: Nat) -> LexRuleAppl } +// Accumulator for fold-based lex_walk. +// fold_list(xs: source) bounds iterations to length(source); done: true short-circuits. +// Each successful step consumes β‰₯1 chars (zero-width guard sets error: true). +type LexWalkAcc { + remaining: String + tokens: List + pos: Int + done: Bool + error: Bool +} + + // lex_walk: scan source left-to-right; emit tokens, discard trivia, error on E1. -// Termination: walk_fuel is initialized to source length; each non-error iteration -// consumes at least one character, so walk_fuel descends (Succ { prev: rest } β†’ rest). -fn lex_walk( - source: String, - tokens: List, - file: Symbol, - pos: Int, - rules: LexRuleSet, - walk_fuel: Nat -) -> Outcome { - match string_is_empty(s: source) { - true => - Accepted { value: TokenStream { tokens: tokens }, diagnostics: None } - false => - match walk_fuel { - Zero => - let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - Succ { prev: rest_walk } => - let at = Textual { file: file, extent: ByteRange { start: pos, end: pos } } - match lex_try_rules(rules: rules.rules, source: source, fuel: lex_string_fuel(source: source)) { - LexRuleNoMatch => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - LexRuleTrivia { lexeme: lexeme, remaining: remaining } => - match string_is_empty(s: lexeme) { - true => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - false => - lex_walk(source: remaining, tokens: tokens, file: file, pos: pos + length(xs: lexeme), rules: rules, walk_fuel: rest_walk) - } - LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => - match string_is_empty(s: lexeme) { - true => - Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } - false => - lex_walk( - source: remaining, - tokens: list_snoc_item( - xs: tokens, - item: Token { class: class, lexeme: lexeme, file: file, start: pos, end: pos + length(xs: lexeme) } - ), - file: file, - pos: pos + length(xs: lexeme), - rules: rules, - walk_fuel: rest_walk - ) +// fold_list(xs: source) provides the termination bound (length(source) iterations). +// Each non-error step consumes β‰₯1 characters; done: true short-circuits remaining steps. +fn lex_walk(source: String, file: Symbol, rules: LexRuleSet) -> Outcome { + let init = LexWalkAcc { remaining: source, tokens: Empty, pos: 0, done: false, error: false } + let result = fold_list( + xs: source, + empty: init, + cons: fn(acc, _) { + match acc.done { + true => acc + false => + match string_is_empty(s: acc.remaining) { + true => + LexWalkAcc { remaining: acc.remaining, tokens: acc.tokens, pos: acc.pos, done: true, error: false } + false => + match lex_try_rules(rules: rules.rules, source: acc.remaining) { + LexRuleNoMatch => + LexWalkAcc { remaining: acc.remaining, tokens: acc.tokens, pos: acc.pos, done: true, error: true } + LexRuleTrivia { lexeme: lexeme, remaining: remaining } => + match string_is_empty(s: lexeme) { + true => + LexWalkAcc { remaining: acc.remaining, tokens: acc.tokens, pos: acc.pos, done: true, error: true } + false => + LexWalkAcc { + remaining: remaining, + tokens: acc.tokens, + pos: acc.pos + length(xs: lexeme), + done: false, + error: false + } + } + LexRuleToken { class: class, lexeme: lexeme, remaining: remaining } => + match string_is_empty(s: lexeme) { + true => + LexWalkAcc { remaining: acc.remaining, tokens: acc.tokens, pos: acc.pos, done: true, error: true } + false => + LexWalkAcc { + remaining: remaining, + tokens: list_snoc_item( + xs: acc.tokens, + item: Token { class: class, lexeme: lexeme, file: file, start: acc.pos, end: acc.pos + length(xs: lexeme) } + ), + pos: acc.pos + length(xs: lexeme), + done: false, + error: false + } + } } } } + } + ) + let at = Textual { file: file, extent: ByteRange { start: result.pos, end: result.pos } } + if result.error { + Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e1_unrecognized_char_diagnostic(at: at)) } + } else { + Accepted { value: TokenStream { tokens: result.tokens }, diagnostics: None } } } @@ -434,6 +475,6 @@ fn tokenize(text: String, file: Symbol, rules: LexRules) -> Outcome Rejected { diagnostics: diagnostics_singleton(d: tokenize_lex_e0_source_not_exhausted_diagnostic(at: at)) } } ModeledLexRules { root: rule_set } => - lex_walk(source: text, tokens: [], file: file, pos: 0, rules: rule_set, walk_fuel: lex_string_fuel(source: text)) + lex_walk(source: text, file: file, rules: rule_set) } } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 6420326f8c0..762794d1344 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -397,129 +397,147 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } -// grammar_fuel: upper bound on cross-production expansion depth β€” one unit per production. -// Passed as the fuel: Nat parameter to expr_is_nullable, expr_reaches_nonterminal_left, -// and parse_expr so the complexity analyzer can prove termination on the Nonterminal arms. -// 🟑 gated β€” P4-bounded-semantics interim β€” feature: grammar-recursion-depth-fuel β€” -// production-count fuel is sound for grammars whose only recursive structure is left recursion -// (rejected by grammar_has_left_recursion). For non-left-recursive cyclic grammars (e.g., -// right-recursive A β†’ B A | Ξ΅), expansion depth equals input length, not production count; -// those grammars pass validation but reject inputs whose recursion depth exceeds production count. -// Dissolve-on: input-length-based fuel or grammar-recursion-depth static analysis. +// grammar_fuel: production count as Nat β€” initial measure for parse_expr's Nonterminal arm. +// Semantics: nat_monus(production_count, length(visited)) β€” remaining expansion budget. +// With visited: List guarding re-entry of any production, expansion depth ≀ +// production_count for well-formed non-left-recursive grammars. P4 concern from prior +// fuel-only scheme is resolved: visited cycle guard makes the bound tight. fn grammar_fuel(root: GrammarRoot) -> Nat { fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) } // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived nullable query morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating nullable logic outside this function. -// expr_is_nullable: true iff expr can match empty input. -// Optional/Repeat are always nullable; Sequence requires both halves nullable; Choice either. -// Nonterminal expands with a visited guard to prevent looping on nullable mutual recursion. -fn expr_is_nullable( - expr: GrammarExpr, - fuel: Nat, - visited: Set, - root: GrammarRoot -) -> Bool { +// expr_is_nullable_given_set: true iff expr can match empty input given a pre-computed nullable set. +// Structurally recursive on GrammarExpr (finite tree) β€” no fuel needed. +// Nonterminal arms consult nullable_set rather than following production references. +fn expr_is_nullable_given_set(expr: GrammarExpr, nullable_set: Set) -> Bool { match expr { Terminal { token_class: _ } => false - Nonterminal { production: p } => - match visited.member(p) { - true => false - false => - match fuel { - Zero => false - Succ { prev: rest } => - match grammar_lookup_production(root: root, name: p) { - GrammarProductionMissing => false - GrammarProductionFound { production: prod } => - expr_is_nullable( - expr: prod.expression, - fuel: rest, - visited: set_symbol_insert(s: visited, item: p), - root: root - ) - } - } - } + Nonterminal { production: name } => nullable_set.member(name) Sequence { left: left, right: right } => - expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) && - expr_is_nullable(expr: right, fuel: fuel, visited: visited, root: root) + expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) && + expr_is_nullable_given_set(expr: right, nullable_set: nullable_set) Choice { left: left, right: right } => - expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) || - expr_is_nullable(expr: right, fuel: fuel, visited: visited, root: root) + expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) || + expr_is_nullable_given_set(expr: right, nullable_set: nullable_set) Optional { element: _ } => true Repeat { element: _ } => true } } +// compute_nullable_set: fixpoint over productions. +// Outer fold iterates |productions| times (convergence bound); inner fold adds nullable productions. +fn compute_nullable_set(root: GrammarRoot) -> Set { + fold_list( + xs: root.productions, + empty: Set { member: fn(_) { false } }, + cons: fn(acc, _) { + fold_list( + xs: root.productions, + empty: acc, + cons: fn(ns, p) { + if expr_is_nullable_given_set(expr: p.expression, nullable_set: ns) { + set_symbol_insert(s: ns, item: p.name) + } else { + ns + } + } + ) + } + ) +} + + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr left-corner query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-corner reachability morphism over GrammarExpr coproduct; forbidden: duplicating left-corner logic or inlining nullable check outside this function. -// expr_reaches_nonterminal_left: true iff the transitive left corner of expr includes `name`. -// For Sequence, if the left element is nullable, the right is also a left corner. -// visited tracks expanded nonterminals; prevents looping on mutual left recursion. -fn expr_reaches_nonterminal_left( - expr: GrammarExpr, - name: Symbol, - fuel: Nat, - visited: Set, - root: GrammarRoot -) -> Bool { +// expr_direct_left_corner_list: direct (non-transitive) left-corner nonterminals of expr. +// Structurally recursive on GrammarExpr (finite tree) β€” no fuel needed. +// Sequence: when left is nullable, both left and right contribute left corners. +fn expr_direct_left_corner_list(expr: GrammarExpr, nullable_set: Set) -> List { match expr { - Terminal { token_class: _ } => false - Nonterminal { production: p } => - p == name || - match visited.member(p) { - true => false - false => - match fuel { - Zero => false - Succ { prev: rest } => - match grammar_lookup_production(root: root, name: p) { - GrammarProductionMissing => false - GrammarProductionFound { production: prod } => - expr_reaches_nonterminal_left( - expr: prod.expression, - name: name, - fuel: rest, - visited: set_symbol_insert(s: visited, item: p), - root: root - ) - } - } - } + Terminal { token_class: _ } => Empty + Nonterminal { production: name } => Cons { head: name, tail: Empty } Sequence { left: left, right: right } => - expr_reaches_nonterminal_left(expr: left, name: name, fuel: fuel, visited: visited, root: root) || - (expr_is_nullable(expr: left, fuel: fuel, visited: visited, root: root) && - expr_reaches_nonterminal_left(expr: right, name: name, fuel: fuel, visited: visited, root: root)) + if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { + list_append( + left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), + right: expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) + ) + } else { + expr_direct_left_corner_list(expr: left, nullable_set: nullable_set) + } Choice { left: left, right: right } => - expr_reaches_nonterminal_left(expr: left, name: name, fuel: fuel, visited: visited, root: root) || - expr_reaches_nonterminal_left(expr: right, name: name, fuel: fuel, visited: visited, root: root) + list_append( + left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), + right: expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) + ) Optional { element: element } => - expr_reaches_nonterminal_left(expr: element, name: name, fuel: fuel, visited: visited, root: root) + expr_direct_left_corner_list(expr: element, nullable_set: nullable_set) Repeat { element: element } => - expr_reaches_nonterminal_left(expr: element, name: name, fuel: fuel, visited: visited, root: root) + expr_direct_left_corner_list(expr: element, nullable_set: nullable_set) } } -fn grammar_has_left_recursion_step(acc: Bool, p: GrammarProduction, root: GrammarRoot) -> Bool { +// compute_left_corner_closure: transitive closure of left-corner reachability from start symbols. +// Outer fold iterates |productions| times (convergence bound). +// Inner fold expands each reachable symbol by its production's direct left corners. +fn compute_left_corner_closure( + start: List, + nullable_set: Set, + root: GrammarRoot +) -> List { + fold_list( + xs: root.productions, + empty: start, + cons: fn(reachable, _) { + fold_list( + xs: reachable, + empty: reachable, + cons: fn(acc, sym) { + match grammar_lookup_production(root: root, name: sym) { + GrammarProductionMissing => acc + GrammarProductionFound { production: prod } => + fold_list( + xs: expr_direct_left_corner_list(expr: prod.expression, nullable_set: nullable_set), + empty: acc, + cons: fn(r, name) { + if contains(xs: r, item: name, eq: fn(a, b) { a == b }) { + r + } else { + list_snoc_item(xs: r, item: name) + } + } + ) + } + } + ) + } + ) +} + + +fn grammar_has_left_recursion_step(acc: Bool, p: GrammarProduction, root: GrammarRoot, nullable_set: Set) -> Bool { acc || - expr_reaches_nonterminal_left( - expr: p.expression, - name: p.name, - fuel: grammar_fuel(root: root), - visited: Set { member: fn(_) { false } }, - root: root + contains( + xs: compute_left_corner_closure( + start: expr_direct_left_corner_list(expr: p.expression, nullable_set: nullable_set), + nullable_set: nullable_set, + root: root + ), + item: p.name, + eq: fn(a, b) { a == b } ) } fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { + let nullable_set = compute_nullable_set(root: root) fold_list( xs: root.productions, empty: false, - cons: fn(acc, p) { grammar_has_left_recursion_step(acc: acc, p: p, root: root) } + cons: fn(acc, p) { grammar_has_left_recursion_step(acc: acc, p: p, root: root, nullable_set: nullable_set) } ) } @@ -668,7 +686,17 @@ fn parse_token_first(tokens: List) -> TokenPeek { // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. -fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRoot) -> ParseExprResult { +// parse_expr: recursive-descent parse walk. +// measure: Nat β€” initial value grammar_fuel(root); decrements once per Nonterminal expansion. +// visited: List β€” productions entered on this path; guards against cycles. +// Semantics: measure = nat_monus(production_count, length(visited)) β€” remaining expansion budget. +fn parse_expr( + expr: GrammarExpr, + tokens: List, + root: GrammarRoot, + measure: Nat, + visited: List +) -> ParseExprResult { match expr { Terminal { token_class: class } => match parse_token_first(tokens: tokens) { @@ -692,37 +720,42 @@ fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRo } } Nonterminal { production: prod_name } => - match fuel { - Zero => ParseExprRejected { diagnostics: [] } - Succ { prev: rest } => - match grammar_lookup_production(root: root, name: prod_name) { - GrammarProductionMissing => - ParseExprRejected { diagnostics: [] } - GrammarProductionFound { production: production } => - match parse_expr(expr: production.expression, fuel: rest, tokens: tokens, root: root) { - ParseExprRejected { diagnostics: diags } => - ParseExprRejected { diagnostics: diags } - ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => - ParseExprAccepted { - remaining: remaining, - captured: Node { - kind: TypeNode { connective: Conj }, - children: [ - grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), - grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) - ] - }, - diagnostics: diags - } - } - } + if contains(xs: visited, item: prod_name, eq: fn(a, b) { a == b }) { + ParseExprRejected { diagnostics: [] } + } else { + match measure { + Zero => ParseExprRejected { diagnostics: [] } + Succ { prev: rest_measure } => + let new_visited = list_snoc_item(xs: visited, item: prod_name) + match grammar_lookup_production(root: root, name: prod_name) { + GrammarProductionMissing => + ParseExprRejected { diagnostics: [] } + GrammarProductionFound { production: production } => + match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: rest_measure, visited: new_visited) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => + ParseExprAccepted { + remaining: remaining, + captured: Node { + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), + grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) + ] + }, + diagnostics: diags + } + } + } + } } Sequence { left: left, right: right } => - match parse_expr(expr: left, fuel: fuel, tokens: tokens, root: root) { + match parse_expr(expr: left, tokens: tokens, root: root, measure: measure, visited: visited) { ParseExprRejected { diagnostics: diags } => ParseExprRejected { diagnostics: diags } ParseExprAccepted { remaining: rest1, captured: cap1, diagnostics: diags1 } => - match parse_expr(expr: right, fuel: fuel, tokens: rest1, root: root) { + match parse_expr(expr: right, tokens: rest1, root: root, measure: measure, visited: visited) { ParseExprRejected { diagnostics: diags2 } => ParseExprRejected { diagnostics: list_append(left: diags1, right: diags2) } ParseExprAccepted { remaining: rest2, captured: cap2, diagnostics: diags2 } => @@ -740,14 +773,14 @@ fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRo } } Choice { left: left, right: right } => - match parse_expr(expr: left, fuel: fuel, tokens: tokens, root: root) { + match parse_expr(expr: left, tokens: tokens, root: root, measure: measure, visited: visited) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => - parse_expr(expr: right, fuel: fuel, tokens: tokens, root: root) + parse_expr(expr: right, tokens: tokens, root: root, measure: measure, visited: visited) } Optional { element: element } => - match parse_expr(expr: element, fuel: fuel, tokens: tokens, root: root) { + match parse_expr(expr: element, tokens: tokens, root: root, measure: measure, visited: visited) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => @@ -768,7 +801,7 @@ fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRo match acc.done { true => acc false => - match parse_expr(expr: element, fuel: fuel, tokens: acc.remaining, root: root) { + match parse_expr(expr: element, tokens: acc.remaining, root: root, measure: measure, visited: visited) { ParseExprRejected { diagnostics: _ } => ParseRepeatAcc { remaining: acc.remaining, @@ -808,7 +841,7 @@ fn parse_expr(expr: GrammarExpr, fuel: Nat, tokens: List, root: GrammarRo fn parse_production(tokens: List, root: GrammarRoot, production: GrammarProduction) -> Outcome { let at = port_locus(port: parse_stage_locus_port) - match parse_expr(expr: production.expression, fuel: grammar_fuel(root: root), tokens: tokens, root: root) { + match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: grammar_fuel(root: root), visited: []) { ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { Accepted { From f3efe34ae32038bf48723f03bccb9a13e0e2af8f Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:04:42 +0000 Subject: [PATCH 44/66] WIP: wartime --- src/v4/compiler/02_parse.dag | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 762794d1344..9cce3f51cd2 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -4,11 +4,11 @@ // Owns: Grammar type hierarchy (GrammarExpr/GrammarProduction/GrammarRoot), ParseTree, parse walk, // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, -// parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_set, -// expr_direct_left_corner_list, compute_left_corner_closure, -// expr_has_undefined_nonterminal, grammar_has_undefined_nonterminals, -// grammar_has_left_recursion_step, grammar_has_undefined_nonterminals_step, -// parse_sync_step, grammar_fuel. +// parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_step, +// compute_nullable_set, expr_direct_left_corner_step, expr_direct_left_corner_list, +// compute_left_corner_closure, expr_has_undefined_nonterminal, +// grammar_has_undefined_nonterminals, grammar_has_left_recursion_step, +// grammar_has_undefined_nonterminals_step, parse_sync_step, grammar_fuel. // Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. // Zero Annotation Mandate applied: fold-based fixpoint for nullable/left-corner sets; @@ -427,6 +427,15 @@ fn expr_is_nullable_given_set(expr: GrammarExpr, nullable_set: Set) -> B } +fn compute_nullable_step(ns: Set, p: GrammarProduction) -> Set { + if expr_is_nullable_given_set(expr: p.expression, nullable_set: ns) { + set_symbol_insert(s: ns, item: p.name) + } else { + ns + } +} + + // compute_nullable_set: fixpoint over productions. // Outer fold iterates |productions| times (convergence bound); inner fold adds nullable productions. fn compute_nullable_set(root: GrammarRoot) -> Set { @@ -438,11 +447,7 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { xs: root.productions, empty: acc, cons: fn(ns, p) { - if expr_is_nullable_given_set(expr: p.expression, nullable_set: ns) { - set_symbol_insert(s: ns, item: p.name) - } else { - ns - } + compute_nullable_step(ns: ns, p: p) } ) } From 799971633fea95e0632159f2db7b01629c4f1f42 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:12:28 +0000 Subject: [PATCH 45/66] fix(parse): extract expr_direct_left_corner_step to resolve Coproduct/Container type mismatch The Sequence arm of expr_direct_left_corner_list had an if/else where the true branch returned via list_append (Container) and the false branch returned via direct recursive call (Coproduct). Lens-CI rejected the incompatible branch types. Extracting expr_direct_left_corner_step with explicit -> List return type forces both branches into the same type representation. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 9cce3f51cd2..cb499c982ff 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -455,6 +455,18 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { } +fn expr_direct_left_corner_step(left: GrammarExpr, right: GrammarExpr, nullable_set: Set) -> List { + if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { + list_append( + left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), + right: expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) + ) + } else { + expr_direct_left_corner_list(expr: left, nullable_set: nullable_set) + } +} + + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr left-corner query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-corner reachability morphism over GrammarExpr coproduct; forbidden: duplicating left-corner logic or inlining nullable check outside this function. // expr_direct_left_corner_list: direct (non-transitive) left-corner nonterminals of expr. // Structurally recursive on GrammarExpr (finite tree) β€” no fuel needed. @@ -464,14 +476,7 @@ fn expr_direct_left_corner_list(expr: GrammarExpr, nullable_set: Set) -> Terminal { token_class: _ } => Empty Nonterminal { production: name } => Cons { head: name, tail: Empty } Sequence { left: left, right: right } => - if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { - list_append( - left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), - right: expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) - ) - } else { - expr_direct_left_corner_list(expr: left, nullable_set: nullable_set) - } + expr_direct_left_corner_step(left: left, right: right, nullable_set: nullable_set) Choice { left: left, right: right } => list_append( left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), From 7d4de9926f34d84f5d7f3023512ffd0cceaa1fb6 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:24:13 +0000 Subject: [PATCH 46/66] WIP: wartime --- src/v4/std/algebra.dag | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index fb1ffdb3a06..8f85335b2b7 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -278,7 +278,8 @@ fn is_prefix_of( // 🟑 gated β€” P3-boundary-dissolution interim β€” feature: list_skip-non-negative-precondition β€” // nat.dag imports algebra.dag so Nat/UInt is not expressible at this layer to make n < 0 // unrepresentable at the type level. Production callers guarantee n >= 0 (literals or length). -// n < 0: returns xs unchanged (caller contract violation; undetectable as typed failure here). +// n < 0: returns Empty (caller contract violation; visibly wrong β€” fails fast at callers +// rather than silently producing the same result as n=0). // Dissolve-on: shared PositiveInt/NonNegativeInt module extractable above algebra.dag, // or callers supply Nat directly. type ListSkipState { @@ -286,7 +287,9 @@ type ListSkipState { result: FreeMonoid } fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { - if n <= 0 { + if n < 0 { + Empty + } else if n == 0 { xs } else { fold_list( From e4cc3117ea43bf0d9f51ac959653bcc1149b87bb Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:24:35 +0000 Subject: [PATCH 47/66] fix(parse): rename left/right to lhs/rhs in expr_direct_left_corner_step to avoid named-param collision --- src/v4/compiler/02_parse.dag | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 37ad709101a..dcb183b1b4c 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -500,14 +500,14 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { } -fn expr_direct_left_corner_step(left: GrammarExpr, right: GrammarExpr, nullable_set: Set) -> List { - if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { +fn expr_direct_left_corner_step(lhs: GrammarExpr, rhs: GrammarExpr, nullable_set: Set) -> List { + if expr_is_nullable_given_set(expr: lhs, nullable_set: nullable_set) { list_append( - left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), - right: expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) + left: expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set), + right: expr_direct_left_corner_list(expr: rhs, nullable_set: nullable_set) ) } else { - expr_direct_left_corner_list(expr: left, nullable_set: nullable_set) + expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set) } } @@ -521,7 +521,7 @@ fn expr_direct_left_corner_list(expr: GrammarExpr, nullable_set: Set) -> Terminal { token_class: _ } => Empty Nonterminal { production: name } => Cons { head: name, tail: Empty } Sequence { left: left, right: right } => - expr_direct_left_corner_step(left: left, right: right, nullable_set: nullable_set) + expr_direct_left_corner_step(lhs: left, rhs: right, nullable_set: nullable_set) Choice { left: left, right: right } => list_append( left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), From 0f8ff718d3222c7b1a351319a2a0a15b6b25af13 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:26:24 +0000 Subject: [PATCH 48/66] =?UTF-8?q?fix(parse/algebra):=20address=20openai-pr?= =?UTF-8?q?o=20review=20findings=20=E2=80=94=20list=5Fskip=20and=20parse?= =?UTF-8?q?=5Fexpr?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit list_skip: n < 0 now returns Empty (visibly wrong, fails fast at callers) rather than xs (indistinguishable from n=0 no-op). Gate comment updated. parse_expr: remove visited: List parameter entirely. The cycle guard was over-broad β€” it rejected any production re-entry regardless of position, breaking right-recursive grammars like type_expr's generic parameter recursion. Termination is guaranteed by grammar_fuel measure (decrements per Nonterminal expansion; left-recursive grammars are pre-rejected by grammar_has_left_recursion). grammar_validation.dag: add TestClaim rows pinning the validator boundary: left-recursion detected, right-recursion accepted by validator. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 88 +++++++++---------- .../test/claim/parse/grammar_validation.dag | 60 +++++++++++++ 2 files changed, 102 insertions(+), 46 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 37ad709101a..5f5e84c6e1b 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -13,8 +13,10 @@ // Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. // Zero Annotation Mandate applied: fold-based fixpoint for nullable/left-corner sets; -// parse_expr Nonterminal arm uses grammar_fuel measure + visited: List -// (nat_monus semantics β€” measure = production_count βˆ’ expansion_depth); +// parse_expr Nonterminal arm uses grammar_fuel measure (nat_monus semantics: +// measure = production_count βˆ’ expansion_depth); visited guard removed β€” +// grammar_has_left_recursion validates cycles pre-parse; right-recursive grammars +// are supported up to grammar_fuel expansion depth. // all fuel: Nat parameters removed. T-22 complexity analysis: 0 diagnostics. @@ -443,10 +445,9 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { // grammar_fuel: production count as Nat β€” initial measure for parse_expr's Nonterminal arm. -// Semantics: nat_monus(production_count, length(visited)) β€” remaining expansion budget. -// With visited: List guarding re-entry of any production, expansion depth ≀ -// production_count for well-formed non-left-recursive grammars. P4 concern from prior -// fuel-only scheme is resolved: visited cycle guard makes the bound tight. +// Semantics: nat_monus(production_count, expansion_depth) β€” remaining expansion budget. +// Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs, +// so grammar_fuel bounds right-recursive descent: expansion depth ≀ production_count. fn grammar_fuel(root: GrammarRoot) -> Nat { fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) } @@ -743,14 +744,14 @@ fn parse_token_first(tokens: List) -> TokenPeek { // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. // parse_expr: recursive-descent parse walk. // measure: Nat β€” initial value grammar_fuel(root); decrements once per Nonterminal expansion. -// visited: List β€” productions entered on this path; guards against cycles. -// Semantics: measure = nat_monus(production_count, length(visited)) β€” remaining expansion budget. +// Semantics: measure = nat_monus(production_count, expansion_depth) β€” remaining expansion budget. +// Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs; +// right-recursive grammars terminate via measure exhaustion (depth ≀ grammar_fuel). fn parse_expr( expr: GrammarExpr, tokens: List, root: GrammarRoot, - measure: Nat, - visited: List + measure: Nat ) -> ParseExprResult { match expr { Terminal { token_class: class } => @@ -775,42 +776,37 @@ fn parse_expr( } } Nonterminal { production: prod_name } => - if contains(xs: visited, item: prod_name, eq: fn(a, b) { a == b }) { - ParseExprRejected { diagnostics: [] } - } else { - match measure { - Zero => ParseExprRejected { diagnostics: [] } - Succ { prev: rest_measure } => - let new_visited = list_snoc_item(xs: visited, item: prod_name) - match grammar_lookup_production(root: root, name: prod_name) { - GrammarProductionMissing => - ParseExprRejected { diagnostics: [] } - GrammarProductionFound { production: production } => - match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: rest_measure, visited: new_visited) { - ParseExprRejected { diagnostics: diags } => - ParseExprRejected { diagnostics: diags } - ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => - ParseExprAccepted { - remaining: remaining, - captured: Node { - kind: TypeNode { connective: Conj }, - children: [ - grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), - grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) - ] - }, - diagnostics: diags - } - } - } - } + match measure { + Zero => ParseExprRejected { diagnostics: [] } + Succ { prev: rest_measure } => + match grammar_lookup_production(root: root, name: prod_name) { + GrammarProductionMissing => + ParseExprRejected { diagnostics: [] } + GrammarProductionFound { production: production } => + match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: rest_measure) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => + ParseExprAccepted { + remaining: remaining, + captured: Node { + kind: TypeNode { connective: Conj }, + children: [ + grammar_named_edge(name: grammar_production_identity_node_projection, target: production.emitted), + grammar_named_edge(name: grammar_production_captured_node_projection, target: captured) + ] + }, + diagnostics: diags + } + } + } } Sequence { left: left, right: right } => - match parse_expr(expr: left, tokens: tokens, root: root, measure: measure, visited: visited) { + match parse_expr(expr: left, tokens: tokens, root: root, measure: measure) { ParseExprRejected { diagnostics: diags } => ParseExprRejected { diagnostics: diags } ParseExprAccepted { remaining: rest1, captured: cap1, diagnostics: diags1 } => - match parse_expr(expr: right, tokens: rest1, root: root, measure: measure, visited: visited) { + match parse_expr(expr: right, tokens: rest1, root: root, measure: measure) { ParseExprRejected { diagnostics: diags2 } => ParseExprRejected { diagnostics: list_append(left: diags1, right: diags2) } ParseExprAccepted { remaining: rest2, captured: cap2, diagnostics: diags2 } => @@ -828,14 +824,14 @@ fn parse_expr( } } Choice { left: left, right: right } => - match parse_expr(expr: left, tokens: tokens, root: root, measure: measure, visited: visited) { + match parse_expr(expr: left, tokens: tokens, root: root, measure: measure) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => - parse_expr(expr: right, tokens: tokens, root: root, measure: measure, visited: visited) + parse_expr(expr: right, tokens: tokens, root: root, measure: measure) } Optional { element: element } => - match parse_expr(expr: element, tokens: tokens, root: root, measure: measure, visited: visited) { + match parse_expr(expr: element, tokens: tokens, root: root, measure: measure) { ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } => ParseExprAccepted { remaining: rest, captured: cap, diagnostics: diags } ParseExprRejected { diagnostics: _ } => @@ -856,7 +852,7 @@ fn parse_expr( match acc.done { true => acc false => - match parse_expr(expr: element, tokens: acc.remaining, root: root, measure: measure, visited: visited) { + match parse_expr(expr: element, tokens: acc.remaining, root: root, measure: measure) { ParseExprRejected { diagnostics: _ } => ParseRepeatAcc { remaining: acc.remaining, @@ -896,7 +892,7 @@ fn parse_expr( fn parse_production(tokens: List, root: GrammarRoot, production: GrammarProduction) -> Outcome { let at = port_locus(port: parse_stage_locus_port) - match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: grammar_fuel(root: root), visited: []) { + match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: grammar_fuel(root: root)) { ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { Accepted { diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag index 601faba6e65..71ee8d9ad17 100644 --- a/src/v4/test/claim/parse/grammar_validation.dag +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -18,10 +18,13 @@ import v4.compiler.parse { GrammarProduction, GrammarRoot, Nonterminal, + Optional, + Sequence, Terminal, grammar_atom, grammar_empty_sync_tokens, grammar_has_duplicate_productions, + grammar_has_left_recursion, grammar_has_undefined_nonterminals, parse_skip_to_sync } @@ -43,6 +46,7 @@ import v4.std.verification { data validation_tok_class: Symbol = validation_tok_class data validation_start: Symbol = validation_start data validation_other: Symbol = validation_other +data validation_rec_start: Symbol = validation_rec_start data validation_file: Symbol = validation_file data validation_bool_true: Symbol = validation_bool_true data validation_bool_false: Symbol = validation_bool_false @@ -106,6 +110,44 @@ data validation_dangling_ref_root: GrammarRoot = GrammarRoot { } +// Left-recursive grammar: A = A "x" β€” grammar_has_left_recursion should detect this. +data validation_left_recursive_root: GrammarRoot = GrammarRoot { + start: validation_rec_start, + productions: Cons { + head: GrammarProduction { + name: validation_rec_start, + expression: Sequence { + left: Nonterminal { production: validation_rec_start }, + right: Terminal { token_class: validation_tok_class } + }, + emitted: grammar_atom(identity: validation_rec_start) + }, + tail: Empty + }, + sync_tokens: grammar_empty_sync_tokens() +} + + +// Right-recursive grammar: A = "x" A? β€” not left-recursive; grammar_has_left_recursion returns false. +// This exercises the validator boundary: right-recursive grammars are accepted and parse_expr +// handles them via grammar_fuel measure (depth-bounded, not cycle-rejected). +data validation_right_recursive_root: GrammarRoot = GrammarRoot { + start: validation_rec_start, + productions: Cons { + head: GrammarProduction { + name: validation_rec_start, + expression: Sequence { + left: Terminal { token_class: validation_tok_class }, + right: Optional { element: Nonterminal { production: validation_rec_start } } + }, + emitted: grammar_atom(identity: validation_rec_start) + }, + tail: Empty + }, + sync_tokens: grammar_empty_sync_tokens() +} + + // Non-empty token list for the sync-recovery claim. data validation_one_token_list: List = Cons { head: validation_token(class: validation_tok_class), tail: Empty } @@ -147,3 +189,21 @@ data claim_empty_sync_set_no_token_drain: TestClaim = EqualsClaim { rhs: validation_bool_atom(b: false), classification: TestClassification { tier: Tier1, layer: Unit } } + + +data claim_left_recursion_detected: TestClaim = EqualsClaim { + label: "grammar_has_left_recursion returns true for A = A 'x' (direct left recursion)", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: grammar_has_left_recursion(root: validation_left_recursive_root)), + rhs: validation_bool_atom(b: true), + classification: TestClassification { tier: Tier1, layer: Unit } +} + + +data claim_right_recursion_not_left_recursive: TestClaim = EqualsClaim { + label: "grammar_has_left_recursion returns false for A = 'x' A? (right-recursive, non-left)", + anchor: manual_claim_anchor(anchor: ManualAnchorAbsent), + lhs: validation_bool_atom(b: grammar_has_left_recursion(root: validation_right_recursive_root)), + rhs: validation_bool_atom(b: false), + classification: TestClassification { tier: Tier1, layer: Unit } +} From f027c04a25f055fdff98510f63172412783657db Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:38:41 +0000 Subject: [PATCH 49/66] =?UTF-8?q?fix(parse):=20inline=20Sequence=20arm=20?= =?UTF-8?q?=E2=80=94=20put=20nullable-conditional=20inside=20list=5Fappend?= =?UTF-8?q?=20right:=20arg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The v2 bootstrap compiler fails to unify if/else branch types when the if-branch calls list_append and the else-branch calls a recursive function: if nullable { list_append(left: recursive, right: recursive) } else { recursive } β†’ Coproduct(FreeMonoid) vs Container(List,Primitive(Symbol)) Fix: remove expr_direct_left_corner_step helper entirely; inline the Sequence arm using list_append where the nullable-conditional is the right: argument: list_append( left: expr_direct_left_corner_list(expr: left, ...), right: if nullable { expr_direct_left_corner_list(expr: right, ...) } else { Empty } ) Both branches of the inner if/else are now List (recursive call and Empty), and list_append anchors the outer type. Semantically equivalent: appending Empty is identity. --- src/v4/compiler/02_parse.dag | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 2a4cb019aaf..de523462267 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -5,7 +5,7 @@ // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, // parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_step, -// compute_nullable_set, expr_direct_left_corner_step, expr_direct_left_corner_list, +// compute_nullable_set, expr_direct_left_corner_list, // compute_left_corner_closure, expr_has_undefined_nonterminal, // grammar_has_undefined_nonterminals, grammar_has_left_recursion_step, // grammar_has_undefined_nonterminals_step, parse_sync_step, grammar_fuel, @@ -501,28 +501,25 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { } -fn expr_direct_left_corner_step(lhs: GrammarExpr, rhs: GrammarExpr, nullable_set: Set) -> List { - if expr_is_nullable_given_set(expr: lhs, nullable_set: nullable_set) { - list_append( - left: expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set), - right: expr_direct_left_corner_list(expr: rhs, nullable_set: nullable_set) - ) - } else { - expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set) - } -} - - // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr left-corner query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-corner reachability morphism over GrammarExpr coproduct; forbidden: duplicating left-corner logic or inlining nullable check outside this function. // expr_direct_left_corner_list: direct (non-transitive) left-corner nonterminals of expr. // Structurally recursive on GrammarExpr (finite tree) β€” no fuel needed. // Sequence: when left is nullable, both left and right contribute left corners. +// Note: Sequence arm uses list_append with the nullable-conditional inside right: to avoid +// a top-level if/else type-unification failure in the v2 bootstrap compiler. fn expr_direct_left_corner_list(expr: GrammarExpr, nullable_set: Set) -> List { match expr { Terminal { token_class: _ } => Empty Nonterminal { production: name } => Cons { head: name, tail: Empty } Sequence { left: left, right: right } => - expr_direct_left_corner_step(lhs: left, rhs: right, nullable_set: nullable_set) + list_append( + left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), + right: if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { + expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) + } else { + Empty + } + ) Choice { left: left, right: right } => list_append( left: expr_direct_left_corner_list(expr: left, nullable_set: nullable_set), From 3195052f26f5c77a4ec09b1b499738263bc56b34 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:39:23 +0000 Subject: [PATCH 50/66] fix(parse): convert if/else to match in expr_direct_left_corner_step Lens-CI enforces that if/else branches have the same type representation. `list_append` returns Coproduct(FreeMonoid) while `expr_direct_left_corner_list` returns Container(List,Symbol); match arms are checked against the declared return type instead of against each other, eliminating the mismatch. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 2a4cb019aaf..45dc8adaf75 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -502,13 +502,14 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { fn expr_direct_left_corner_step(lhs: GrammarExpr, rhs: GrammarExpr, nullable_set: Set) -> List { - if expr_is_nullable_given_set(expr: lhs, nullable_set: nullable_set) { - list_append( - left: expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set), - right: expr_direct_left_corner_list(expr: rhs, nullable_set: nullable_set) - ) - } else { - expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set) + match expr_is_nullable_given_set(expr: lhs, nullable_set: nullable_set) { + true => + list_append( + left: expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set), + right: expr_direct_left_corner_list(expr: rhs, nullable_set: nullable_set) + ) + false => + expr_direct_left_corner_list(expr: lhs, nullable_set: nullable_set) } } From 02e15ab50a53875075016650f202aa26f95532d7 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 14:44:46 +0000 Subject: [PATCH 51/66] fix(parse): use grammar_empty_corner_list() to anchor List in if/else else-branch The v2 bootstrap compiler infers Empty as Coproduct(FreeMonoid) (unknown element type) when used in an if/else else-branch where the if-branch returns List. This causes 'if branches resolve to incompatible types'. Fix: wrap Empty in grammar_empty_corner_list() -> List so the else-branch type is unambiguously List. The if/else branch types now unify. --- src/v4/compiler/02_parse.dag | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index de523462267..f51053053dd 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -5,7 +5,7 @@ // Node projection functions, left-recursion check, error-recovery helpers, // ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, // parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_step, -// compute_nullable_set, expr_direct_left_corner_list, +// compute_nullable_set, grammar_empty_corner_list, expr_direct_left_corner_list, // compute_left_corner_closure, expr_has_undefined_nonterminal, // grammar_has_undefined_nonterminals, grammar_has_left_recursion_step, // grammar_has_undefined_nonterminals_step, parse_sync_step, grammar_fuel, @@ -501,6 +501,13 @@ fn compute_nullable_set(root: GrammarRoot) -> Set { } +// v2 bootstrap compiler workaround: Empty literal has unknown element type in if/else context; +// a typed wrapper anchors the type to List so branch unification succeeds. +fn grammar_empty_corner_list() -> List { + Empty +} + + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr left-corner query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-corner reachability morphism over GrammarExpr coproduct; forbidden: duplicating left-corner logic or inlining nullable check outside this function. // expr_direct_left_corner_list: direct (non-transitive) left-corner nonterminals of expr. // Structurally recursive on GrammarExpr (finite tree) β€” no fuel needed. @@ -517,7 +524,7 @@ fn expr_direct_left_corner_list(expr: GrammarExpr, nullable_set: Set) -> right: if expr_is_nullable_given_set(expr: left, nullable_set: nullable_set) { expr_direct_left_corner_list(expr: right, nullable_set: nullable_set) } else { - Empty + grammar_empty_corner_list() } ) Choice { left: left, right: right } => From 02f5a0160f7f0756fa8b9901d0224224e5727296 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:01:31 +0000 Subject: [PATCH 52/66] fix(dag): use wave1_canonical_symbols in dag_language_model_wave1_modeled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wave1_modeled() was using dag_language_model_surface_prelude_atoms() for canonical_symbols, omitting grammar_carries_symbol(dag_wave1_grammar(), sym). Resolve consumes canonical_symbols to gate symbol emission β€” grammar-owned symbols (dag_surface_module etc.) would be accepted by the parser but then rejected as unbound by the pipeline LM. Use dag_language_model_wave1_canonical_symbols() to match wave1(). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/languages/dag.dag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v4/extdeps/languages/dag.dag b/src/v4/extdeps/languages/dag.dag index 05806877397..8da9e8dd110 100644 --- a/src/v4/extdeps/languages/dag.dag +++ b/src/v4/extdeps/languages/dag.dag @@ -739,6 +739,6 @@ fn dag_language_model_wave1_modeled() -> DagLanguageModel { lex: dag_wave1_lex(), grammar: dag_wave1_grammar(), language_identity: dag_language_model_surface_id, - canonical_symbols: dag_language_model_surface_prelude_atoms() + canonical_symbols: dag_language_model_wave1_canonical_symbols() } } From fc41e2c33695695cdc9bea7ea3773cb6c0e02e0f Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:19:56 +0000 Subject: [PATCH 53/66] WIP: wartime --- src/v4/extdeps/runtimes/v4_evaluator.dag | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 197ae6771ec..396019a28c3 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -51,7 +51,8 @@ import v4.std.runtime { Suspend, TransformInterpreter, ValueInterpreter, - ValueRepresentationModel + ValueRepresentationModel, + runtime_value_resolved_type } import v4.std.witness { Violates, Witness } From 698dc1a9755d6afc5e10c801b2317a2d9b5d197d Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:20:08 +0000 Subject: [PATCH 54/66] fix(eval): thread RuntimeValue through transfer via runtime_value_resolved_type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Continue and Return arms were returning the unchanged frame, discarding the carried RuntimeValue β€” violating P2 (facts-flow-forward). Update frame.current to runtime_value_resolved_type(value: v) so the value flows forward into the next EvaluationFrame. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/runtimes/v4_evaluator.dag | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 396019a28c3..b7c2c2392d4 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -184,10 +184,10 @@ fn v4_eval_wave1_return_value(value: RuntimeValue, _frame: EvaluationFrame) -> O fn v4_eval_wave1_transfer(control: ControlTransfer, frame: EvaluationFrame) -> Outcome { match control { - Continue { value: _ } => - Accepted { value: frame, diagnostics: None } - Return { value: _ } => - Accepted { value: frame, diagnostics: None } + Continue { value: v } => + Accepted { value: EvaluationFrame { current: runtime_value_resolved_type(value: v), environment: frame.environment }, diagnostics: None } + Return { value: v } => + Accepted { value: EvaluationFrame { current: runtime_value_resolved_type(value: v), environment: frame.environment }, diagnostics: None } Raise { diagnostic: d } => outcome_rejected(d: d) Suspend { continuation: c } => From 515848992f83a5e4e9176774dcdab53f687558fc Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:30:05 +0000 Subject: [PATCH 55/66] fix(parse): grammar_fuel = production_count + token_count for correct parse bound MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit production_count alone fails right-recursive grammars: A = "x" A? with 1 production and N tokens needs N Nonterminal expansions, but grammar_fuel=1 exhausted after the first recursive call, leaving remaining tokens. Fix: grammar_fuel(root, tokens) = nat_add(production_count, token_count). - token_count bounds right-recursive chains (each successful non-nullable Nonterminal expansion consumes β‰₯1 token β†’ depth ≀ token_count) - production_count bounds nullable-nonterminal indirection chains (A=B, B="x" needs 2 expansions for 1 token; production_count covers the slack) - Combined sum covers all non-left-recursive grammars on any input Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 38 +++++++++++-------- .../test/claim/parse/grammar_validation.dag | 2 +- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index f51053053dd..ef643ee5856 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -13,10 +13,10 @@ // Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. // Zero Annotation Mandate applied: fold-based fixpoint for nullable/left-corner sets; -// parse_expr Nonterminal arm uses grammar_fuel measure (nat_monus semantics: -// measure = production_count βˆ’ expansion_depth); visited guard removed β€” -// grammar_has_left_recursion validates cycles pre-parse; right-recursive grammars -// are supported up to grammar_fuel expansion depth. +// parse_expr Nonterminal arm uses grammar_fuel measure (production_count + token_count); +// visited guard removed β€” grammar_has_left_recursion validates cycles pre-parse; +// right-recursive grammars supported up to token_count expansion depth; +// nullable-nonterminal chains bounded by production_count. // all fuel: Nat parameters removed. T-22 complexity analysis: 0 diagnostics. @@ -29,7 +29,7 @@ import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_forme import v4.std.collection { List, Set } import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } import v4.std.logic { Bool } -import v4.std.nat { Nat, Zero, Succ } +import v4.std.nat { Nat, Zero, Succ, nat_add } // 🟑 gated β€” feature:CP-1b-bidirectional-grammar-carrier β€” bind TASKS.md T-6/T-7 β€” dissolve-on: GrammarExpr converges with LexPattern on single declarative bidirectional grammar model; forbidden: parallel production algebras without explicit structural justification. @@ -444,12 +444,20 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } -// grammar_fuel: production count as Nat β€” initial measure for parse_expr's Nonterminal arm. -// Semantics: nat_monus(production_count, expansion_depth) β€” remaining expansion budget. -// Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs, -// so grammar_fuel bounds right-recursive descent: expansion depth ≀ production_count. -fn grammar_fuel(root: GrammarRoot) -> Nat { - fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) +// grammar_fuel: production_count + token_count as Nat β€” initial measure for parse_expr's Nonterminal arm. +// Two components cover distinct expansion modes: +// - production_count: bounds nullable-nonterminal chains (non-token-consuming expansions). +// Without left-recursion (pre-rejected), each distinct production appears at most once in such chains. +// - token_count: bounds right-recursive chains (token-consuming expansions). +// Each successful non-nullable Nonterminal expansion consumes β‰₯1 token β†’ depth ≀ token count. +// Combined, production_count + token_count bounds all Nonterminal expansion sequences for any +// non-left-recursive grammar on any input. Left-recursive grammars are rejected by +// grammar_has_left_recursion before parse_expr runs. +fn grammar_fuel(root: GrammarRoot, tokens: List) -> Nat { + nat_add( + a: fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }), + b: fold_list(xs: tokens, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) + ) } @@ -747,10 +755,10 @@ fn parse_token_first(tokens: List) -> TokenPeek { // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. // parse_expr: recursive-descent parse walk. -// measure: Nat β€” initial value grammar_fuel(root); decrements once per Nonterminal expansion. -// Semantics: measure = nat_monus(production_count, expansion_depth) β€” remaining expansion budget. +// measure: Nat β€” initial value grammar_fuel(root, tokens); decrements once per Nonterminal expansion. +// Semantics: measure = nat_monus(production_count + token_count, expansion_depth). // Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs; -// right-recursive grammars terminate via measure exhaustion (depth ≀ grammar_fuel). +// right-recursive grammars terminate via measure exhaustion (depth ≀ production_count + token_count). fn parse_expr( expr: GrammarExpr, tokens: List, @@ -896,7 +904,7 @@ fn parse_expr( fn parse_production(tokens: List, root: GrammarRoot, production: GrammarProduction) -> Outcome { let at = port_locus(port: parse_stage_locus_port) - match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: grammar_fuel(root: root)) { + match parse_expr(expr: production.expression, tokens: tokens, root: root, measure: grammar_fuel(root: root, tokens: tokens)) { ParseExprAccepted { remaining: remaining, captured: captured, diagnostics: diags } => if is_empty(xs: remaining) { Accepted { diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag index 71ee8d9ad17..c903e29efda 100644 --- a/src/v4/test/claim/parse/grammar_validation.dag +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -130,7 +130,7 @@ data validation_left_recursive_root: GrammarRoot = GrammarRoot { // Right-recursive grammar: A = "x" A? β€” not left-recursive; grammar_has_left_recursion returns false. // This exercises the validator boundary: right-recursive grammars are accepted and parse_expr -// handles them via grammar_fuel measure (depth-bounded, not cycle-rejected). +// handles them via grammar_fuel measure (production_count + token_count, not cycle-rejected). data validation_right_recursive_root: GrammarRoot = GrammarRoot { start: validation_rec_start, productions: Cons { From 1048764ec3dd5b8c52230478a25f61f264d818b2 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:32:43 +0000 Subject: [PATCH 56/66] chore(parse): remove unused parse_walk_not_realized dead code parse_walk_not_realized symbol and parse_walk_not_realized_diagnostic were never called after the VoidGrammar path was wired to parse_g0_tokens_remain_diagnostic. P5 hygiene cleanup flagged by cursor review 17798. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index ef643ee5856..791fc98995c 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -126,8 +126,6 @@ data grammar_production_captured_node_projection: Symbol = grammar_production_ca data parse_stage_locus_port: Symbol = parse_stage_locus_port -data parse_walk_not_realized: Symbol = parse_walk_not_realized - data parse_grammar_not_well_formed: Symbol = parse_grammar_not_well_formed data parse_g0_tokens_remain: Symbol = parse_g0_tokens_remain @@ -141,15 +139,6 @@ data parse_grammar_duplicate_production: Symbol = parse_grammar_duplicate_produc data parse_e1_syntax_error: Symbol = parse_e1_syntax_error -fn parse_walk_not_realized_diagnostic(at: Locus) -> Diagnostic { - Diagnostic { - reason: parse_walk_not_realized, - at: at, - correction: Unavailable { reason: ExternalContractUnknown } - } -} - - fn parse_grammar_not_well_formed_diagnostic(at: Locus) -> Diagnostic { Diagnostic { reason: parse_grammar_not_well_formed, From aa2c52acf42788091bb00b11100f7b562a197a06 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 15:41:19 +0000 Subject: [PATCH 57/66] fix(parse): restore NodeFold and fold_node to v4.std.node import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both are used at 02_parse.dag:359 (grammar_symbol_fold return type) and 02_parse.dag:389 (grammar_carries_symbol body), but were missing from the import list β€” unresolved references caught by codex review 17805. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 791fc98995c..28eddfcc027 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -25,7 +25,7 @@ module v4.compiler.parse import v4.compiler.tokenize { Token, TokenStream } import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } -import v4.std.node { Atom, Conj, Edge, Named, Node, Symbol, TypeNode, well_formed } +import v4.std.node { Atom, Conj, Edge, Named, Node, NodeFold, Symbol, TypeNode, fold_node, well_formed } import v4.std.collection { List, Set } import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } import v4.std.logic { Bool } From 7e5d3fdb05af8e9f50eeedd16db1f2a005387640 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 16:17:37 +0000 Subject: [PATCH 58/66] =?UTF-8?q?docs(eval):=20add=20=F0=9F=9F=A1=20gate?= =?UTF-8?q?=20to=20v4=5Feval=5Fwave1=5Ftransfer=20with=20dissolve-on=20con?= =?UTF-8?q?dition?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documents the wave-1 interim: step_loop is fail-closed so transfer is structurally unreachable in wave-1 execution. Continue/Return thread runtime_value_resolved_type(v) (the value's type Node) into frame.current β€” maximum Node-level fidelity before T-22/T-8 RuntimeValueβ†’Node reification. Forbidden clauses capture both prior failure modes (unchanged frame = P2 violation; reject = more severe P2 violation). Co-Authored-By: Claude Sonnet 4.6 --- src/v4/extdeps/runtimes/v4_evaluator.dag | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index b7c2c2392d4..83d081cd45b 100644 --- a/src/v4/extdeps/runtimes/v4_evaluator.dag +++ b/src/v4/extdeps/runtimes/v4_evaluator.dag @@ -182,6 +182,15 @@ fn v4_eval_wave1_return_value(value: RuntimeValue, _frame: EvaluationFrame) -> O Accepted { value: Return { value: value }, diagnostics: None } } +// 🟑 gated β€” wave-1 interim (Practice 10) β€” feature: faithful RuntimeValue-to-EvaluationFrame reification β€” +// dissolve-on-arrival: T-22 or T-8 providing RuntimeValueβ†’Node reification (runtime_value_node_projection +// returns non-Unrepresentable) or EvaluationFrame gains a RuntimeValue result slot. +// Wave-1 rationale: step_loop is fail-closed (always rejects), so transfer is structurally unreachable +// through the normal eval loop (bind_outcome short-circuits on Rejected before transfer is called). +// Continue/Return thread runtime_value_resolved_type(v) into frame.current β€” the type Node of v, +// which is the maximum Node-level fidelity available before full value reification lands. +// Forbidden: returning the unchanged frame (discards value, violates P2 facts-flow-forward); +// rejecting Continue/Return (more severe P2 violation β€” facts completely absent from output). fn v4_eval_wave1_transfer(control: ControlTransfer, frame: EvaluationFrame) -> Outcome { match control { Continue { value: v } => From 1a309d37fa19e1bee3e2302171a5df2b825dbda4 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 16:28:52 +0000 Subject: [PATCH 59/66] WIP: wartime --- src/v4/compiler/01_tokenize.dag | 14 +++++- src/v4/compiler/02_parse.dag | 45 ++++++++++--------- src/v4/std/algebra.dag | 5 ++- src/v4/std/text.dag | 7 ++- .../test/claim/parse/grammar_validation.dag | 2 +- 5 files changed, 47 insertions(+), 26 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 5138deaf56f..65225a2093a 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -20,7 +20,7 @@ module v4.compiler.tokenize import v4.std.collection { List } import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, Unavailable, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } -import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_skip, list_snoc_item } +import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_snoc_item } import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } import v4.std.nat { Nat, nat_lte, nat_gte } import v4.std.logic { Bool } @@ -164,9 +164,19 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { // lex_match_prefix: match a literal string prefix against source. // Uses is_prefix_of (stdlib terminal) to avoid direct structural recursion on FreeMonoid. +// Advances source by folding over prefix β€” each step pops the head of the remaining source. +// Safe because is_prefix_of guarantees source has at least length(prefix) elements. fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { if is_prefix_of(prefix: prefix, xs: source, eq: fn(a, b) { a == b }) { - LexMatchAccepted { remaining: list_skip(xs: source, n: length(xs: prefix)), lexeme: prefix } + LexMatchAccepted { + remaining: fold_list(xs: prefix, empty: source, cons: fn(remaining, _) { + match remaining { + Empty => Empty + Cons { head: _, tail: t } => t + } + }), + lexeme: prefix + } } else { LexMatchRejected } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 28eddfcc027..53252f51192 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -13,10 +13,9 @@ // Consumes: std diagnostic, std node, std algebra, std collection, std nat, compiler tokenize. // Status: T-7 parse walk realized; sync_tokens field staged for T-8 error-recovery trigger. // Zero Annotation Mandate applied: fold-based fixpoint for nullable/left-corner sets; -// parse_expr Nonterminal arm uses grammar_fuel measure (production_count + token_count); +// parse_expr Nonterminal arm uses grammar_fuel measure K*(N+1) where K=production_count N=token_count; // visited guard removed β€” grammar_has_left_recursion validates cycles pre-parse; -// right-recursive grammars supported up to token_count expansion depth; -// nullable-nonterminal chains bounded by production_count. +// right-recursive grammars and wrapper-nonterminal chains bounded by K*(N+1). // all fuel: Nat parameters removed. T-22 complexity analysis: 0 diagnostics. @@ -27,9 +26,9 @@ import v4.compiler.tokenize { Token, TokenStream } import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } import v4.std.node { Atom, Conj, Edge, Named, Node, NodeFold, Symbol, TypeNode, fold_node, well_formed } import v4.std.collection { List, Set } -import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_skip, list_snoc_item } +import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_snoc_item } import v4.std.logic { Bool } -import v4.std.nat { Nat, Zero, Succ, nat_add } +import v4.std.nat { Nat, Zero, Succ, nat_add, nat_mul } // 🟑 gated β€” feature:CP-1b-bidirectional-grammar-carrier β€” bind TASKS.md T-6/T-7 β€” dissolve-on: GrammarExpr converges with LexPattern on single declarative bidirectional grammar model; forbidden: parallel production algebras without explicit structural justification. @@ -433,19 +432,26 @@ fn set_symbol_insert(s: Set, item: Symbol) -> Set { } -// grammar_fuel: production_count + token_count as Nat β€” initial measure for parse_expr's Nonterminal arm. -// Two components cover distinct expansion modes: -// - production_count: bounds nullable-nonterminal chains (non-token-consuming expansions). -// Without left-recursion (pre-rejected), each distinct production appears at most once in such chains. -// - token_count: bounds right-recursive chains (token-consuming expansions). -// Each successful non-nullable Nonterminal expansion consumes β‰₯1 token β†’ depth ≀ token count. -// Combined, production_count + token_count bounds all Nonterminal expansion sequences for any -// non-left-recursive grammar on any input. Left-recursive grammars are rejected by -// grammar_has_left_recursion before parse_expr runs. +// grammar_fuel: K*(N+1) as Nat β€” initial measure for parse_expr's Nonterminal arm. +// K = production_count, N = token_count. +// +// Correctness argument: +// Each token in the input can trigger at most K Nonterminal expansions before consuming +// it (via wrapper nonterminal chains like A = B; B = "x" A?). The +1 accounts for at most +// one additional nullable/empty-matching chain after all tokens are consumed. So K*(N+1) +// bounds the total Nonterminal expansion count for any non-left-recursive grammar on any input. +// +// Counter-example that breaks K+N: A = B; B = "x" A? with N=4 tokens needs up to 2*(4+1)=10 +// expansions (K+N=6 is too small). K*(N+1) is the tight bound. +// +// Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs. fn grammar_fuel(root: GrammarRoot, tokens: List) -> Nat { - nat_add( + nat_mul( a: fold_list(xs: root.productions, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }), - b: fold_list(xs: tokens, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }) + b: nat_add( + a: fold_list(xs: tokens, empty: Zero, cons: fn(acc, _) { Succ { prev: acc } }), + b: Succ { prev: Zero } + ) ) } @@ -744,10 +750,9 @@ fn parse_token_first(tokens: List) -> TokenPeek { // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarExpr structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived recursive-descent parse morphism over GrammarExpr coproduct (per-variant fold eliminating hand-written match arms); forbidden: duplicating parse walk logic or adding new GrammarExpr arms outside this function. // parse_expr: recursive-descent parse walk. -// measure: Nat β€” initial value grammar_fuel(root, tokens); decrements once per Nonterminal expansion. -// Semantics: measure = nat_monus(production_count + token_count, expansion_depth). +// measure: Nat β€” initial value grammar_fuel(root, tokens) = K*(N+1); decrements once per Nonterminal expansion. // Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs; -// right-recursive grammars terminate via measure exhaustion (depth ≀ production_count + token_count). +// right-recursive and wrapper-nonterminal chains terminate via measure exhaustion (depth ≀ K*(N+1)). fn parse_expr( expr: GrammarExpr, tokens: List, @@ -766,7 +771,7 @@ fn parse_expr( // edge kind; carrying those facts requires a substrate literal-carrier or Stringβ†’Symbol projection. // Dissolve-on: T-8 source-text anchor feature or substrate literal-value edge support. ParseExprAccepted { - remaining: list_skip(xs: tokens, n: 1), + remaining: match tokens { Empty => Empty, Cons { head: _, tail: t } => t }, captured: Node { kind: TypeNode { connective: Atom { identity: tok.class } }, children: [] diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 8f85335b2b7..ccef4b9f2e7 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -277,9 +277,12 @@ fn is_prefix_of( // n = 0: returns xs unchanged (correct no-op). // 🟑 gated β€” P3-boundary-dissolution interim β€” feature: list_skip-non-negative-precondition β€” // nat.dag imports algebra.dag so Nat/UInt is not expressible at this layer to make n < 0 -// unrepresentable at the type level. Production callers guarantee n >= 0 (literals or length). +// unrepresentable at the type level. // n < 0: returns Empty (caller contract violation; visibly wrong β€” fails fast at callers // rather than silently producing the same result as n=0). +// Compiler callers (01_tokenize.dag, 02_parse.dag, std/text.dag) have been migrated to +// structural match / fold-based alternatives that do not pass n<0; list_skip is retained +// as a utility for external callers that can guarantee n >= 0. // Dissolve-on: shared PositiveInt/NonNegativeInt module extractable above algebra.dag, // or callers supply Nat directly. type ListSkipState { diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 4bccd1cc05b..562b2919b25 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -9,7 +9,7 @@ module v4.std.text -import v4.std.algebra { FreeMonoid, fold_list_right, is_empty, list_skip } +import v4.std.algebra { Cons, Empty, FreeMonoid, fold_list_right, is_empty } import v4.std.logic { Bool } import v4.std.nat { Nat } type Char = Nat @@ -26,5 +26,8 @@ fn string_head(s: String) -> CharResult { fold_list_right(xs: s, empty: CharAbsent, snoc: fn(_acc, c) { CharFound { value: c } }) } fn string_tail(s: String) -> String { - list_skip(xs: s, n: 1) + match s { + Empty => Empty + Cons { head: _, tail: t } => t + } } diff --git a/src/v4/test/claim/parse/grammar_validation.dag b/src/v4/test/claim/parse/grammar_validation.dag index c903e29efda..fbf81ba9e02 100644 --- a/src/v4/test/claim/parse/grammar_validation.dag +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -130,7 +130,7 @@ data validation_left_recursive_root: GrammarRoot = GrammarRoot { // Right-recursive grammar: A = "x" A? β€” not left-recursive; grammar_has_left_recursion returns false. // This exercises the validator boundary: right-recursive grammars are accepted and parse_expr -// handles them via grammar_fuel measure (production_count + token_count, not cycle-rejected). +// handles them via grammar_fuel measure K*(N+1) where K=production_count N=token_count. data validation_right_recursive_root: GrammarRoot = GrammarRoot { start: validation_rec_start, productions: Cons { From ad53b95b111ab6f4472ee05d7b17e8bf9e665cca Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 16:31:37 +0000 Subject: [PATCH 60/66] fix(algebra): list_skip n<0 returns xs (identity) not Empty; update text.dag header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit n<0 returning Empty fabricated a valid-looking FreeMonoid from an invalid call (P3 violation). Returning xs (the identity for n<=0) is a proper gated interim under the caller-guarantees-non-negative contract. n=0 case is unchanged (still identity/correct). Compiler callers (01_tokenize, 02_parse, text.dag) already migrated to structural match / fold-based alternatives in 1a309d37f β€” list_skip is retained for external callers. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/std/algebra.dag | 15 +++++---------- src/v4/std/text.dag | 2 +- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index ccef4b9f2e7..94c0c2168c5 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -274,15 +274,12 @@ fn is_prefix_of( // Drop the first n elements; O(|xs|). Uses fold rather than Empty/Cons matching. -// n = 0: returns xs unchanged (correct no-op). +// n <= 0: returns xs unchanged (identity β€” n=0 correct, n<0 acceptable gated interim under +// caller-guarantees-non-negative contract; returns original list, not fabricated Empty). // 🟑 gated β€” P3-boundary-dissolution interim β€” feature: list_skip-non-negative-precondition β€” // nat.dag imports algebra.dag so Nat/UInt is not expressible at this layer to make n < 0 -// unrepresentable at the type level. -// n < 0: returns Empty (caller contract violation; visibly wrong β€” fails fast at callers -// rather than silently producing the same result as n=0). -// Compiler callers (01_tokenize.dag, 02_parse.dag, std/text.dag) have been migrated to -// structural match / fold-based alternatives that do not pass n<0; list_skip is retained -// as a utility for external callers that can guarantee n >= 0. +// unrepresentable at the type level. Callers guarantee n >= 0; n<0 returns xs (identity, +// not fabrication). Compiler callers migrated to structural match / fold-based alternatives. // Dissolve-on: shared PositiveInt/NonNegativeInt module extractable above algebra.dag, // or callers supply Nat directly. type ListSkipState { @@ -290,9 +287,7 @@ type ListSkipState { result: FreeMonoid } fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { - if n < 0 { - Empty - } else if n == 0 { + if n <= 0 { xs } else { fold_list( diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 562b2919b25..a1922f497a1 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,7 +1,7 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. // Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. -// Consumes: std/algebra.dag (FreeMonoid, is_empty, fold_list_right, list_skip); std/logic.dag (Bool); std/nat.dag (Nat). +// Consumes: std/algebra.dag (Cons, Empty, FreeMonoid, is_empty, fold_list_right); std/logic.dag (Bool); std/nat.dag (Nat). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode From e6097d79e0a27a275563fe8e0829742eb758b59b Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 16:43:03 +0000 Subject: [PATCH 61/66] chore(algebra): delete orphaned list_skip and ListSkipState MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All three compiler callers (01_tokenize.dag, 02_parse.dag, std/text.dag) were migrated to structural match / fold-based alternatives in 1a309d37f. list_skip now has zero consumers β€” shipping orphaned std substrate with a known n<0 partial-function gap would be worse than deletion. ListSkipState is internal to list_skip and goes with it. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/std/algebra.dag | 32 +------------------------------- 1 file changed, 1 insertion(+), 31 deletions(-) diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 94c0c2168c5..30c3af42d52 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -1,7 +1,7 @@ // src/v4/std/algebra.dag // Scope: algebraic structures and canonical carrier constructions. // Anchor: https://en.wikipedia.org/wiki/Algebraic_structure -// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, list_skip, ListSkipState, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. +// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. // Consumes: std node. // Status: T-2 modeled. // Ledger: Part 6 β€” SL-P6-FREEMONOID-IS-EMPTY-VPRED. @@ -273,36 +273,6 @@ fn is_prefix_of( } -// Drop the first n elements; O(|xs|). Uses fold rather than Empty/Cons matching. -// n <= 0: returns xs unchanged (identity β€” n=0 correct, n<0 acceptable gated interim under -// caller-guarantees-non-negative contract; returns original list, not fabricated Empty). -// 🟑 gated β€” P3-boundary-dissolution interim β€” feature: list_skip-non-negative-precondition β€” -// nat.dag imports algebra.dag so Nat/UInt is not expressible at this layer to make n < 0 -// unrepresentable at the type level. Callers guarantee n >= 0; n<0 returns xs (identity, -// not fabrication). Compiler callers migrated to structural match / fold-based alternatives. -// Dissolve-on: shared PositiveInt/NonNegativeInt module extractable above algebra.dag, -// or callers supply Nat directly. -type ListSkipState { - remaining: Int - result: FreeMonoid -} -fn list_skip(xs: FreeMonoid, n: Int) -> FreeMonoid { - if n <= 0 { - xs - } else { - fold_list( - xs: xs, - empty: ListSkipState { remaining: n, result: Empty }, - cons: fn(acc, item) { - if acc.remaining != 0 { - ListSkipState { remaining: acc.remaining - 1, result: acc.result } - } else { - ListSkipState { remaining: 0, result: list_snoc_item(xs: acc.result, item: item) } - } - } - ).result - } -} type PointwisePower { From 82fd874aeddeff027fd46319cf0ce2ff59e12dcb Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 17:03:21 +0000 Subject: [PATCH 62/66] =?UTF-8?q?fix(algebra):=20add=20list=5Ftail=20?= =?UTF-8?q?=E2=80=94=20move=20FreeMonoid=20head-pop=20to=20stdlib?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lens-CI --target rust compile rejects Empty/Cons variant match patterns outside the module where FreeMonoid is defined (algebra.dag). The three call sites that pattern-matched directly on FreeMonoid after list_skip was deleted (text.dag:string_tail, 01_tokenize.dag:lex_match_prefix fold lambda, 02_parse.dag:parse_expr Terminal arm) now call list_tail instead. list_tail is defined in algebra.dag where coproduct matching is valid. Empty/Cons remain imported as value constructors in caller modules. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 10 +++++----- src/v4/compiler/02_parse.dag | 4 ++-- src/v4/std/algebra.dag | 8 +++++++- src/v4/std/text.dag | 9 +++------ 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 65225a2093a..bc23538ba89 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -20,7 +20,7 @@ module v4.compiler.tokenize import v4.std.collection { List } import v4.std.diagnostic { Accepted, ByteRange, Diagnostic, ExternalContractUnknown, Locus, None, Outcome, Textual, Unavailable, UserInputBoundary, WholeFile, diagnostics_singleton } import v4.std.node { Symbol } -import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_snoc_item } +import v4.std.algebra { Cons, Empty, fold_list, is_empty, is_prefix_of, length, list_append, list_snoc_item, list_tail } import v4.std.text { Char, CharAbsent, CharFound, String, string_head, string_is_empty, string_tail } import v4.std.nat { Nat, nat_lte, nat_gte } import v4.std.logic { Bool } @@ -35,6 +35,7 @@ type LexCharClass | StringTextChar | LineCommentTextChar | BlockCommentTextChar + | BlockCommentAfterStarChar // 🟑 coproduct dissolution β€” CP-1b item 13b; declarative parse/emit pattern data is modeled, bidirectional grammar carrier convergence remains gated. @@ -158,6 +159,8 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { c != 10 BlockCommentTextChar => c != 42 + BlockCommentAfterStarChar => + c != 47 } } @@ -170,10 +173,7 @@ fn lex_match_prefix(prefix: String, source: String) -> LexMatchResult { if is_prefix_of(prefix: prefix, xs: source, eq: fn(a, b) { a == b }) { LexMatchAccepted { remaining: fold_list(xs: prefix, empty: source, cons: fn(remaining, _) { - match remaining { - Empty => Empty - Cons { head: _, tail: t } => t - } + list_tail(xs: remaining) }), lexeme: prefix } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 53252f51192..5f00d4096a8 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -26,7 +26,7 @@ import v4.compiler.tokenize { Token, TokenStream } import v4.std.diagnostic { Accepted, Diagnostic, Diagnostics, ExternalContractUnknown, Locus, NonEmptyDiagnostics, None, Outcome, Some, Unavailable, UserInputBoundary, diagnostics_singleton, port_locus } import v4.std.node { Atom, Conj, Edge, Named, Node, NodeFold, Symbol, TypeNode, fold_node, well_formed } import v4.std.collection { List, Set } -import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_snoc_item } +import v4.std.algebra { Cons, Empty, contains, fold_list, fold_list_right, is_empty, length, list_append, list_snoc_item, list_tail } import v4.std.logic { Bool } import v4.std.nat { Nat, Zero, Succ, nat_add, nat_mul } @@ -771,7 +771,7 @@ fn parse_expr( // edge kind; carrying those facts requires a substrate literal-carrier or Stringβ†’Symbol projection. // Dissolve-on: T-8 source-text anchor feature or substrate literal-value edge support. ParseExprAccepted { - remaining: match tokens { Empty => Empty, Cons { head: _, tail: t } => t }, + remaining: list_tail(xs: tokens), captured: Node { kind: TypeNode { connective: Atom { identity: tok.class } }, children: [] diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 30c3af42d52..6ad6b6f233c 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -1,7 +1,7 @@ // src/v4/std/algebra.dag // Scope: algebraic structures and canonical carrier constructions. // Anchor: https://en.wikipedia.org/wiki/Algebraic_structure -// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. +// Owns: Magma, Semigroup, Monoid, CommutativeMonoid, Group, AbelianGroup, Semiring, CommutativeSemiring, Ring, CommutativeRing, OrderedRing, Field, ApproximateField, Lattice, BoundedLattice, BooleanAlgebra, FreeMonoid, FreeMonoidUniqueState, fold_list, fold_list_right, fold_list_node, list_tail, is_empty, non_empty, length, for_all, count_where, count_equal, unique, list_append, list_snoc_item, bag_eq, zip_eq, is_prefix_of, PointwisePower, Ordering, Homomorphism. // Consumes: std node. // Status: T-2 modeled. // Ledger: Part 6 β€” SL-P6-FREEMONOID-IS-EMPTY-VPRED. @@ -102,6 +102,12 @@ fn fold_list_right(xs: FreeMonoid, empty: A, snoc: fn(A, T) -> A) -> A Cons { head: h, tail: t } => snoc(fold_list_right(xs: t, empty: empty, snoc: snoc), h) } } +fn list_tail(xs: FreeMonoid) -> FreeMonoid { + match xs { + Empty => Empty + Cons { head: _, tail: t } => t + } +} fn fold_list_node( xs: FreeMonoid, item_node: fn(T) -> Node diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index a1922f497a1..d47f866fdf1 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,7 +1,7 @@ // src/v4/std/text.dag // Scope: Unicode text carriers. // Owns: Char, CharResult, String, string_is_empty, string_head, string_tail. -// Consumes: std/algebra.dag (Cons, Empty, FreeMonoid, is_empty, fold_list_right); std/logic.dag (Bool); std/nat.dag (Nat). +// Consumes: std/algebra.dag (FreeMonoid, is_empty, fold_list_right, list_tail); std/logic.dag (Bool); std/nat.dag (Nat). // Status: T-3 modeled; string scanning primitives added for T-6 lexer walk. // Anchor: https://en.wikipedia.org/wiki/Unicode @@ -9,7 +9,7 @@ module v4.std.text -import v4.std.algebra { Cons, Empty, FreeMonoid, fold_list_right, is_empty } +import v4.std.algebra { FreeMonoid, fold_list_right, is_empty, list_tail } import v4.std.logic { Bool } import v4.std.nat { Nat } type Char = Nat @@ -26,8 +26,5 @@ fn string_head(s: String) -> CharResult { fold_list_right(xs: s, empty: CharAbsent, snoc: fn(_acc, c) { CharFound { value: c } }) } fn string_tail(s: String) -> String { - match s { - Empty => Empty - Cons { head: _, tail: t } => t - } + list_tail(xs: s) } From 2e1a517c74f884a4efefe44046e56ea9eb7eb424 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 17:03:23 +0000 Subject: [PATCH 63/66] WIP: wartime --- src/v4/extdeps/languages/dag.dag | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/v4/extdeps/languages/dag.dag b/src/v4/extdeps/languages/dag.dag index 8da9e8dd110..fcfb8f66ee1 100644 --- a/src/v4/extdeps/languages/dag.dag +++ b/src/v4/extdeps/languages/dag.dag @@ -26,8 +26,11 @@ import v4.compiler.parse { grammar_carries_symbol } import v4.compiler.tokenize { + BlockCommentAfterStarChar, BlockCommentTextChar, CharClassPattern, + CharPattern, + ChoicePattern, DelimitedPattern, DigitChar, IdentContinueChar, @@ -207,7 +210,13 @@ fn dag_block_comment_trivia_rule() -> LexRule { TriviaRule { pattern: DelimitedPattern { open: LiteralPattern { text: "/*" }, - body: RepeatPattern { element: CharClassPattern { class: BlockCommentTextChar } }, + body: RepeatPattern { element: ChoicePattern { + left: CharClassPattern { class: BlockCommentTextChar }, + right: SequencePattern { + left: CharPattern { char: 42 }, + right: CharClassPattern { class: BlockCommentAfterStarChar } + } + }}, close: LiteralPattern { text: "*/" } } } From 17a391f0d9febd665dd3b0be83d69dafb491a25d Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 17:19:15 +0000 Subject: [PATCH 64/66] fix(parse): bind grammar_root_to_node P2-boundary gate to T-8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gate on grammar_root_to_node lacked a concrete dissolution receipt β€” it named a generic future substrate capability rather than a bounded task. P5 requires scaffolds to name a concrete dissolution lane. Bind to TASKS.md T-8: sync_tokens projection dissolves when Set is reified as an explicit membership list type at T-8, which is the same milestone that wires sync_tokens into the error-recovery flow. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 5f00d4096a8..bf22d20b5d5 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -328,12 +328,12 @@ fn grammar_productions_to_node(productions: List) -> Node { } -// 🟑 gated β€” P2-boundary-dissolution interim β€” feature: grammar-root-node-projection-completeness β€” -// GrammarRoot.sync_tokens: Set is a predicate closure { member: fn(Symbol) -> Bool }; -// the Node substrate has no edge kind for function values, so sync_tokens cannot be materialized -// as a Node child. The projection constant grammar_root_sync_tokens_node_projection is declared -// above to name the intended edge. Dissolve-on: substrate literal-value edge support for -// predicate sets, or Set reified as an explicit membership list type. +// 🟑 gated T-8 β€” P2-boundary interim β€” feature: grammar-root-node-projection-completeness β€” +// bind TASKS.md T-8 β€” GrammarRoot.sync_tokens: Set is a predicate closure +// { member: fn(Symbol) -> Bool }; the Node substrate has no edge kind for function values, so +// sync_tokens cannot be materialized as a Node child here. grammar_root_sync_tokens_node_projection +// names the intended edge. Dissolve-on: T-8, when Set is reified as an explicit membership +// list type (or substrate gains literal-value edge support), enabling the edge to be emitted. fn grammar_root_to_node(root: GrammarRoot) -> Node { Node { kind: TypeNode { From 5d8a11419f522926c3e51dc59602f48b7d36bf8c Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 17:28:08 +0000 Subject: [PATCH 65/66] fix(parse): replace GrammarDupCheckState with coproduct; add Practice 10 tags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two cursor review findings on PR #3655: 1. GrammarDupCheckState { seen, has_duplicate: Bool } was a hand-rolled in-band sum (Practice 2 / P5 violation) β€” invalid states (has_duplicate true with valid seen) remained representable. Replaced with a declared coproduct: GrammarDupCheckUnique { seen } | GrammarDupCheckDuplicate. grammar_dup_check_step now matches on variants; grammar_has_duplicate_productions matches the fold result instead of projecting .has_duplicate. 2. grammar_has_left_recursion, grammar_has_undefined_nonterminals, and grammar_has_duplicate_productions were has_*β†’Bool validators with no Practice 10 receipt, while neighboring expr-level walkers are tagged. Add 🟑 gated Practice 10 tags bound to node://adhoc-2145db6b-69a. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/02_parse.dag | 38 +++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index bf22d20b5d5..f432fcfdc1b 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -81,10 +81,10 @@ type ParseSyncState { result: List } -type GrammarDupCheckState { - seen: Set - has_duplicate: Bool -} +// 🟑 coproduct dissolution β€” feature: GrammarRoot duplicate-name scan accumulator β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived membership fold over production names eliminates the hand-written accumulator; invalid-state-representable Bool flag dissolved into coproduct branches. +type GrammarDupCheckResult + = GrammarDupCheckUnique { seen: Set } + | GrammarDupCheckDuplicate // 🟑 coproduct dissolution β€” feature: FreeMonoid substrate first accessor; dissolves when stdlib provides a substrate-derived head projection that returns Option directly, eliminating the per-use carrier type. type TokenPeek @@ -595,6 +595,7 @@ fn grammar_has_left_recursion_step(acc: Bool, p: GrammarProduction, root: Gramma } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarRoot left-recursion validator substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived left-recursion reachability morphism over GrammarRoot productions; forbidden: duplicating left-recursion check logic outside this function. fn grammar_has_left_recursion(root: GrammarRoot) -> Bool { let nullable_set = compute_nullable_set(root: root) fold_list( @@ -635,6 +636,7 @@ fn grammar_has_undefined_nonterminals_step(acc: Bool, p: GrammarProduction, root } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarRoot structure validity query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived undefined-reference scan morphism over GrammarRoot; forbidden: duplicating undefined-nonterminal check logic outside this function. fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { match grammar_lookup_production(root: root, name: root.start) { GrammarProductionMissing => true @@ -648,25 +650,29 @@ fn grammar_has_undefined_nonterminals(root: GrammarRoot) -> Bool { } -fn grammar_dup_check_step(acc: GrammarDupCheckState, p: GrammarProduction) -> GrammarDupCheckState { - if acc.has_duplicate { - acc - } else { - if acc.seen.member(p.name) { - GrammarDupCheckState { seen: acc.seen, has_duplicate: true } - } else { - GrammarDupCheckState { seen: set_symbol_insert(s: acc.seen, item: p.name), has_duplicate: false } - } +fn grammar_dup_check_step(acc: GrammarDupCheckResult, p: GrammarProduction) -> GrammarDupCheckResult { + match acc { + GrammarDupCheckDuplicate => GrammarDupCheckDuplicate + GrammarDupCheckUnique { seen: seen } => + if seen.member(p.name) { + GrammarDupCheckDuplicate + } else { + GrammarDupCheckUnique { seen: set_symbol_insert(s: seen, item: p.name) } + } } } +// 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: GrammarRoot structure validity query substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived duplicate-name scan morphism over GrammarRoot productions; forbidden: duplicating duplicate-check logic outside this function. fn grammar_has_duplicate_productions(root: GrammarRoot) -> Bool { - fold_list( + match fold_list( xs: root.productions, - empty: GrammarDupCheckState { seen: Set { member: fn(_) { false } }, has_duplicate: false }, + empty: GrammarDupCheckUnique { seen: Set { member: fn(_) { false } } }, cons: fn(acc, p) { grammar_dup_check_step(acc: acc, p: p) } - ).has_duplicate + ) { + GrammarDupCheckDuplicate => true + GrammarDupCheckUnique { seen: _ } => false + } } From 27927a6054f8f7dc464b24ff0cc46480d4240b60 Mon Sep 17 00:00:00 2001 From: Brian Searls Date: Mon, 25 May 2026 17:45:07 +0000 Subject: [PATCH 66/66] fix(tokenize): try-close-first DelimitedPattern; P3/P5 list_tail gate; P2 wave1_modeled delegation - DelimitedPattern arm rewritten with try-close-first fold semantics and DelimitedState accumulator, fixing /**/ and /***/ block comment tokenization. BlockCommentAfterStarChar class removed (no longer needed); dag_block_comment body simplified to single-char ChoicePattern. - list_tail in algebra.dag gets Practice 10 P3/P5 gate (bind node://adhoc-2145db6b-69a). - dag_language_model_wave1_modeled delegates to dag_language_model_wave1() instead of duplicating its body, eliminating the P2 second construction authority. Co-Authored-By: Claude Sonnet 4.6 --- src/v4/compiler/01_tokenize.dag | 66 ++++++++++++++++++++++++++------ src/v4/extdeps/languages/dag.dag | 17 ++------ src/v4/std/algebra.dag | 1 + 3 files changed, 59 insertions(+), 25 deletions(-) diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index bc23538ba89..41e966834ab 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -35,7 +35,6 @@ type LexCharClass | StringTextChar | LineCommentTextChar | BlockCommentTextChar - | BlockCommentAfterStarChar // 🟑 coproduct dissolution β€” CP-1b item 13b; declarative parse/emit pattern data is modeled, bidirectional grammar carrier convergence remains gated. @@ -159,8 +158,6 @@ fn char_in_class(c: Char, class: LexCharClass) -> Bool { c != 10 BlockCommentTextChar => c != 42 - BlockCommentAfterStarChar => - c != 47 } } @@ -190,6 +187,14 @@ type RepeatState { done: Bool } +// Accumulator for fold-based delimited matching (try-close-first) inside lex_match_pattern. +type DelimitedState { + remaining: String + lexeme: String + done: Bool + failed: Bool +} + // 🟑 gated β€” predicate-dissolution interim (docs/modeling-discipline.md Practice 10) β€” feature: LexPattern structural morphism substrate β€” bind node://adhoc-2145db6b-69a β€” dissolve-on-arrival: substrate-derived pattern-matching morphism over LexPattern coproduct (per-variant fold eliminating hand-written match arms); forbidden: adding new match arms outside the substrate derivation path. // lex_match_pattern: structurally recursive on LexPattern (finite tree) β€” no fuel parameter needed. @@ -339,20 +344,57 @@ fn lex_match_pattern(pattern: LexPattern, source: String) -> LexMatchResult { LexMatchAccepted { remaining: result.remaining, lexeme: result.lexeme } } DelimitedPattern { open: open, body: body, close: close } => + // Try-close-first semantics: at each position, attempt close before consuming a body element. + // fold_list(xs: after_open) bounds iterations to length(after_open); body consumes β‰₯1 char + // per step (zero-width guard) or sets done:true. Fixes greedy over-consumption for comments + // like /**/ and /***/ where close shares chars with body (e.g. the star in `*/`). match lex_match_pattern(pattern: open, source: source) { LexMatchRejected => LexMatchRejected LexMatchAccepted { remaining: after_open, lexeme: open_lex } => - match lex_match_pattern(pattern: body, source: after_open) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: after_body, lexeme: body_lex } => - match lex_match_pattern(pattern: close, source: after_body) { - LexMatchRejected => LexMatchRejected - LexMatchAccepted { remaining: after_close, lexeme: close_lex } => - LexMatchAccepted { - remaining: after_close, - lexeme: list_append(left: open_lex, right: list_append(left: body_lex, right: close_lex)) + let init = DelimitedState { remaining: after_open, lexeme: open_lex, done: false, failed: false } + let result = fold_list( + xs: after_open, + empty: init, + cons: fn(state, _) { + match state.done { + true => state + false => + match lex_match_pattern(pattern: close, source: state.remaining) { + LexMatchAccepted { remaining: after_close, lexeme: close_lex } => + DelimitedState { + remaining: after_close, + lexeme: list_append(left: state.lexeme, right: close_lex), + done: true, + failed: false + } + LexMatchRejected => + match lex_match_pattern(pattern: body, source: state.remaining) { + LexMatchRejected => + DelimitedState { remaining: state.remaining, lexeme: state.lexeme, done: true, failed: true } + LexMatchAccepted { remaining: after_body, lexeme: body_lex } => + match string_is_empty(s: body_lex) { + true => + DelimitedState { remaining: state.remaining, lexeme: state.lexeme, done: true, failed: true } + false => + DelimitedState { + remaining: after_body, + lexeme: list_append(left: state.lexeme, right: body_lex), + done: false, + failed: false + } + } + } } } + } + ) + match result.done { + false => LexMatchRejected + true => + match result.failed { + true => LexMatchRejected + false => LexMatchAccepted { remaining: result.remaining, lexeme: result.lexeme } + } } } } diff --git a/src/v4/extdeps/languages/dag.dag b/src/v4/extdeps/languages/dag.dag index fcfb8f66ee1..809a7190b07 100644 --- a/src/v4/extdeps/languages/dag.dag +++ b/src/v4/extdeps/languages/dag.dag @@ -26,7 +26,6 @@ import v4.compiler.parse { grammar_carries_symbol } import v4.compiler.tokenize { - BlockCommentAfterStarChar, BlockCommentTextChar, CharClassPattern, CharPattern, @@ -210,13 +209,10 @@ fn dag_block_comment_trivia_rule() -> LexRule { TriviaRule { pattern: DelimitedPattern { open: LiteralPattern { text: "/*" }, - body: RepeatPattern { element: ChoicePattern { + body: ChoicePattern { left: CharClassPattern { class: BlockCommentTextChar }, - right: SequencePattern { - left: CharPattern { char: 42 }, - right: CharClassPattern { class: BlockCommentAfterStarChar } - } - }}, + right: CharPattern { char: 42 } + }, close: LiteralPattern { text: "*/" } } } @@ -744,10 +740,5 @@ fn dag_wave1_sync_tokens() -> Set { // Pipeline-facing LM that wires the full modeled grammar β€” use this for T-7/T-8+ pipeline calls. fn dag_language_model_wave1_modeled() -> DagLanguageModel { - DagLanguageModel { - lex: dag_wave1_lex(), - grammar: dag_wave1_grammar(), - language_identity: dag_language_model_surface_id, - canonical_symbols: dag_language_model_wave1_canonical_symbols() - } + dag_language_model_wave1() } diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 6ad6b6f233c..4526b1f848a 100644 --- a/src/v4/std/algebra.dag +++ b/src/v4/std/algebra.dag @@ -102,6 +102,7 @@ fn fold_list_right(xs: FreeMonoid, empty: A, snoc: fn(A, T) -> A) -> A Cons { head: h, tail: t } => snoc(fold_list_right(xs: t, empty: empty, snoc: snoc), h) } } +// 🟑 gated β€” P3/P5 interim (docs/modeling-discipline.md Practice 10) β€” feature: FreeMonoid head-pop stdlib projection β€” bind node://adhoc-2145db6b-69a β€” dissolve-on: stdlib Option-returning tail projection; Emptyβ†’Empty is caller-guaranteed unreachable (all call sites guard with is_empty or Cons match before calling); forbidden: calling with empty list without a prior guard. fn list_tail(xs: FreeMonoid) -> FreeMonoid { match xs { Empty => Empty