diff --git a/src/v4/compiler/01_tokenize.dag b/src/v4/compiler/01_tokenize.dag index 25731eb3fc6..41e966834ab 100644 --- a/src/v4/compiler/01_tokenize.dag +++ b/src/v4/compiler/01_tokenize.dag @@ -1,19 +1,28 @@ // 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, 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. 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 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, Unavailable, 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, 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 } // 🟑 coproduct dissolution β€” CP-1b item 13a; lexical data is modeled, per-arm lexer morphism witness remains gated. @@ -28,7 +37,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 +63,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 +79,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 +114,406 @@ 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 } } } +// 🟑 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 => + c == 32 || c == 9 || c == 10 || c == 13 + DigitChar => + nat_gte(a: c, b: 48) && nat_lte(a: c, b: 57) + HexDigitChar => + (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 => + (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 => + (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 => + c != 10 + BlockCommentTextChar => + c != 42 + } +} + + +// 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: fold_list(xs: prefix, empty: source, cons: fn(remaining, _) { + list_tail(xs: remaining) + }), + lexeme: prefix + } + } else { + LexMatchRejected + } +} + + +// Accumulator for fold-based greedy repeat matching inside lex_match_pattern. +type RepeatState { + remaining: String + lexeme: String + 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. +// 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 } + 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 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 } + } + } + } + } + CharPattern { char: expected } => + match string_is_empty(s: source) { + true => LexMatchRejected + false => + 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 + } + } + } + CharClassPattern { class: class } => + match string_is_empty(s: source) { + true => LexMatchRejected + false => + 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 + } + } + } + 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 } => + // 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 } => + // 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 } => + 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 } + } + } + } + } +} + + +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 { + 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 } + } + } + ) +} + + +// 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. +// 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 } + } +} + + fn tokenize(text: String, file: Symbol, rules: LexRules) -> Outcome { let at = Textual { file: file, @@ -120,13 +522,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, file: file, rules: rule_set) } } diff --git a/src/v4/compiler/02_parse.dag b/src/v4/compiler/02_parse.dag index 21fd05e8f4c..f432fcfdc1b 100644 --- a/src/v4/compiler/02_parse.dag +++ b/src/v4/compiler/02_parse.dag @@ -1,19 +1,34 @@ // 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, grammar_carries_symbol. -// 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, +// ParseSyncState, TokenPeek, ParseRepeatAcc, parse_diag_cons, parse_token_first, +// parse_e1_syntax_error, expr_is_nullable_given_set, compute_nullable_step, +// 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, +// grammar_carries_symbol. +// 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 K*(N+1) where K=production_count N=token_count; +// visited guard removed β€” grammar_has_left_recursion validates cycles pre-parse; +// right-recursive grammars and wrapper-nonterminal chains bounded by K*(N+1). +// all fuel: Nat parameters removed. T-22 complexity analysis: 0 diagnostics. 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, NodeFold, Symbol, TypeNode, fold_node, 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, 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 } // 🟑 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. @@ -33,9 +48,13 @@ type GrammarProduction { } +// 🟑 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 + sync_tokens: Set } @@ -47,17 +66,40 @@ 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: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-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 } + +type ParseSyncState { + found_sync: Bool + result: List +} + +// 🟑 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 + = 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 +} type GrammarSymbolFoldState { found: Bool @@ -77,37 +119,73 @@ 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 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 +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_syntax_error: Symbol = parse_e1_syntax_error -fn parse_walk_not_realized_diagnostic(at: Locus) -> Diagnostic { + +fn parse_grammar_not_well_formed_diagnostic(at: Locus) -> Diagnostic { Diagnostic { - reason: parse_walk_not_realized, + reason: parse_grammar_not_well_formed, at: at, correction: Unavailable { reason: ExternalContractUnknown } } } -fn parse_grammar_not_well_formed_diagnostic(at: Locus) -> Diagnostic { +fn parse_g0_tokens_remain_diagnostic(at: Locus) -> Diagnostic { Diagnostic { - reason: parse_grammar_not_well_formed, + reason: parse_g0_tokens_remain, + at: at, + correction: Unavailable { reason: UserInputBoundary } + } +} + + +fn parse_grammar_left_recursive_diagnostic(at: Locus) -> Diagnostic { + Diagnostic { + reason: parse_grammar_left_recursive, at: at, correction: Unavailable { reason: ExternalContractUnknown } } } -fn parse_g0_tokens_remain_diagnostic(at: Locus) -> Diagnostic { +fn parse_grammar_undefined_nonterminal_diagnostic(at: Locus) -> Diagnostic { Diagnostic { - reason: parse_g0_tokens_remain, + reason: parse_grammar_undefined_nonterminal, + at: at, + correction: Unavailable { reason: ExternalContractUnknown } + } +} + + +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, at: at, correction: Unavailable { reason: UserInputBoundary } } @@ -132,6 +210,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 { @@ -245,6 +328,12 @@ fn grammar_productions_to_node(productions: List) -> Node { } +// 🟑 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 { @@ -333,23 +422,511 @@ fn grammar_lookup_production(root: GrammarRoot, name: Symbol) -> GrammarProducti } -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 +// --- Left-recursion detection --- + +// 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) } + } +} + + +// 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_mul( + a: fold_list(xs: root.productions, 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 } + ) + ) +} + + +// 🟑 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_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: name } => nullable_set.member(name) + Sequence { left: left, right: right } => + 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_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 + } +} + + +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 { + fold_list( + xs: root.productions, + empty: Set { member: fn(_) { false } }, + cons: fn(acc, _) { + fold_list( + xs: root.productions, + empty: acc, + cons: fn(ns, p) { + compute_nullable_step(ns: ns, p: p) + } + ) + } + ) +} + + +// 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. +// 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 } => + 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 { + grammar_empty_corner_list() + } + ) + Choice { left: left, right: right } => + 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_direct_left_corner_list(expr: element, nullable_set: nullable_set) + Repeat { element: element } => + expr_direct_left_corner_list(expr: element, nullable_set: nullable_set) + } +} + + +// 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 || + 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 } + ) +} + + +// 🟑 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( + xs: root.productions, + empty: false, + cons: fn(acc, p) { grammar_has_left_recursion_step(acc: acc, p: p, root: root, nullable_set: nullable_set) } + ) +} + + +// 🟑 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 { + 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_step(acc: Bool, p: GrammarProduction, root: GrammarRoot) -> Bool { + acc || expr_has_undefined_nonterminal(expr: p.expression, root: 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 + GrammarProductionFound { production: _ } => + fold_list( + xs: root.productions, + empty: false, + cons: fn(acc, p) { grammar_has_undefined_nonterminals_step(acc: acc, p: p, root: root) } + ) + } +} + + +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 { + match fold_list( + xs: root.productions, + empty: GrammarDupCheckUnique { seen: Set { member: fn(_) { false } } }, + cons: fn(acc, p) { grammar_dup_check_step(acc: acc, p: p) } + ) { + GrammarDupCheckDuplicate => true + GrammarDupCheckUnique { seen: _ } => false + } +} + + +// --- Diagnostic list helpers --- + +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 parse_diags_to_diagnostics(diags: diags) { + None => NonEmptyDiagnostics { head: default, tail: [] } + Some { diagnostics: ned } => ned + } +} + + +// --- Parse walk helpers --- + +fn parse_repeat_captured_node(acc_nodes: List) -> Node { + Node { + kind: TypeNode { connective: Conj }, + children: fold_list( + xs: acc_nodes, + empty: Empty, + cons: fn(acc, n) { + list_snoc_item( + xs: acc, + item: Edge { + label: Named { name: grammar_repeat_element_node_projection }, + target: n + } + ) + } + ) + } +} + + +// 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) -> 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) } + ) +} + + +fn parse_token_first(tokens: List) -> TokenPeek { + fold_list_right(xs: tokens, empty: TokenPeekAbsent, snoc: fn(_acc, tok) { TokenPeekFirst { value: tok } }) +} + + +// 🟑 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) = K*(N+1); decrements once per Nonterminal expansion. +// Left-recursive grammars are rejected by grammar_has_left_recursion before parse_expr runs; +// right-recursive and wrapper-nonterminal chains terminate via measure exhaustion (depth ≀ K*(N+1)). +fn parse_expr( + expr: GrammarExpr, + tokens: List, + root: GrammarRoot, + measure: Nat +) -> ParseExprResult { + match expr { + Terminal { token_class: class } => + match parse_token_first(tokens: tokens) { + TokenPeekAbsent => ParseExprRejected { diagnostics: [] } + 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_tail(xs: tokens), + captured: Node { + kind: TypeNode { connective: Atom { identity: tok.class } }, + children: [] + }, + diagnostics: [] + } + false => ParseExprRejected { diagnostics: [] } + } + } + Nonterminal { production: prod_name } => + 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) { + ParseExprRejected { diagnostics: diags } => + ParseExprRejected { diagnostics: diags } + ParseExprAccepted { remaining: rest1, captured: cap1, diagnostics: diags1 } => + 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 } => + 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, 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) + } + Optional { element: element } => + 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: _ } => + ParseExprAccepted { + remaining: tokens, + captured: grammar_empty_node(), + diagnostics: [] + } + } + Repeat { element: element } => + // 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, tokens: acc.remaining, root: root, measure: measure) { + 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) { - ParseExprAccepted { remaining: remaining } => + 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 { value: production.emitted, diagnostics: None } + Accepted { + value: 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: 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_e1_syntax_error_diagnostic(at: at) + ) + } } } @@ -369,11 +946,26 @@ 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_undefined_nonterminals(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_undefined_nonterminal_diagnostic(at: at)) } + } else { + if grammar_has_duplicate_productions(root: root) { + Rejected { diagnostics: diagnostics_singleton(d: parse_grammar_duplicate_production_diagnostic(at: at)) } + } else { + 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)) } + } + } + } } } } diff --git a/src/v4/extdeps/languages/dag.dag b/src/v4/extdeps/languages/dag.dag index 38d96d0cf2f..809a7190b07 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; dag_language_model_wave1_void; dag_language_model_surface_empty_prelude; dag_language_model_canonical_symbols; dag_language_model_wave1_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; dag_language_model_wave1_void; dag_language_model_wave1_modeled; dag_language_model_surface_empty_prelude; dag_language_model_canonical_symbols; dag_language_model_wave1_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 @@ -28,6 +28,8 @@ import v4.compiler.parse { import v4.compiler.tokenize { BlockCommentTextChar, CharClassPattern, + CharPattern, + ChoicePattern, DelimitedPattern, DigitChar, IdentContinueChar, @@ -207,7 +209,10 @@ fn dag_block_comment_trivia_rule() -> LexRule { TriviaRule { pattern: DelimitedPattern { open: LiteralPattern { text: "/*" }, - body: RepeatPattern { element: CharClassPattern { class: BlockCommentTextChar } }, + body: ChoicePattern { + left: CharClassPattern { class: BlockCommentTextChar }, + right: CharPattern { char: 42 } + }, close: LiteralPattern { text: "*/" } } } @@ -626,7 +631,8 @@ fn dag_wave1_grammar_root() -> GrammarRoot { type_alias_rhs, block, data_value - ] + ], + sync_tokens: dag_wave1_sync_tokens() } } @@ -716,3 +722,23 @@ 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 { + dag_language_model_wave1() +} diff --git a/src/v4/extdeps/languages/java.dag b/src/v4/extdeps/languages/java.dag index 3cbc3041ba4..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] } + 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 02c2fd486ec..db4a3c58c89 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 { @@ -1361,7 +1362,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: grammar_empty_sync_tokens() } } fn rust_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/languages/swift.dag b/src/v4/extdeps/languages/swift.dag index b27d53d545f..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] } + 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 5bc6e344f99..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] } + 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 dfbc7457b9a..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] } + GrammarRoot { start: wasm_production_mvp1_fn_add, productions: [start], sync_tokens: grammar_empty_sync_tokens() } } fn wasm_wave1_grammar() -> Grammar { diff --git a/src/v4/extdeps/runtimes/v4_evaluator.dag b/src/v4/extdeps/runtimes/v4_evaluator.dag index 4c6c4ed7eb3..83d081cd45b 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 } @@ -181,14 +182,23 @@ 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: _ } => - outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: frame.current)) - 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)) + 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 } => outcome_rejected(d: v4_eval_wave1_runtime_diagnostic(node: c.current)) } @@ -243,7 +253,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 { diff --git a/src/v4/std/algebra.dag b/src/v4/std/algebra.dag index 946712b065c..4526b1f848a 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,13 @@ 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 + Cons { head: _, tail: t } => t + } +} fn fold_list_node( xs: FreeMonoid, item_node: fn(T) -> Node @@ -273,6 +280,8 @@ fn is_prefix_of( } + + type PointwisePower { member: fn(T) -> Bool } diff --git a/src/v4/std/nat.dag b/src/v4/std/nat.dag index 0794e5adebf..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_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. @@ -55,6 +55,33 @@ 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 + Equal => true + 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 + Equal => true + 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 } }, diff --git a/src/v4/std/text.dag b/src/v4/std/text.dag index 58adc5f7078..d47f866fdf1 100644 --- a/src/v4/std/text.dag +++ b/src/v4/std/text.dag @@ -1,15 +1,30 @@ // 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, CharResult, String, string_is_empty, string_head, string_tail. +// 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 module v4.std.text -import v4.std.algebra { FreeMonoid } +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 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 + +fn string_is_empty(s: String) -> Bool { + is_empty(xs: s) +} +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_tail(xs: s) +} 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..fbf81ba9e02 --- /dev/null +++ b/src/v4/test/claim/parse/grammar_validation.dag @@ -0,0 +1,209 @@ +// 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 (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.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, + 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 +} +import v4.std.algebra { Cons, Empty } +import v4.std.collection { List } +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_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 + + +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: 0, end: 0 } +} + + +// 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() +} + + +// 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() +} + + +// 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 K*(N+1) where K=production_count N=token_count. +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 } + + +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_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), + 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 } +} + + +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 } +}