diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bddacee..160fb13 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,9 +28,10 @@ jobs: echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - name: Show toolchain run: lake --version - # Default targets: the generator, the language server, and VerifiedSmoke - # (calc proofs, lexer/parser roundtrips). VerifiedMid and VerifiedHeavy are - # not built here; they are minutes-to-hours of native_decide. + # Default targets: the generator and its library, LeanParserGeneratorRuntime, the + # language server and LspDiagnosticsTest, the Asm and RustActions fixtures, and + # VerifiedSmoke (the calc, asm and spanuse proofs and the calc and + # spanuse roundtrips). VerifiedMid and VerifiedHeavy are not built here. - name: Build default targets (includes VerifiedSmoke) run: lake build # Build the runtime library's static archive on its own. This is the diff --git a/.gitignore b/.gitignore index 13c132a..6495356 100644 --- a/.gitignore +++ b/.gitignore @@ -17,9 +17,6 @@ __pycache__/ .vscode/ *.swp -# local build logs and agent/tooling state +# local build logs *.log -.kiro/ -.research/ -next.md test/asm/large/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b592ce..6e721ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,149 +6,77 @@ versions may change the CLI, the `.lig` syntax, and the generated module API. ## [Unreleased] +Changes since `0.1.0-alpha.1`. + ### Added -- the list macro `separated_list_trailing(sep, X)`: zero or more `X` separated by `sep`, - with an optional trailing `sep`, built as a left-recursive `Array` (`Vec` in Rust). It - accepts what `separated_list` accepted before this release. -- a streaming parser option, `%option parseStr`. When a `%lexer` block is also present, - `Parser` also defines `parseStr : String → …`, which pulls one token at a time from the - byte lexer instead of building the token list. `Verified` relates `parseStr` to - `tokenize`, `parse_eq_dependent` and `parser_sound`. The stream stops at the first error, - lex or parse. -- `PosLexerAgrees` (the positioned byte lexer `lexPos` and `tokenize` succeed on the same - inputs with the same tokens and spans) is proved for every generated lexer, multi-mode - lexers included: `Lexer.posLexerAgrees`, from a Boolean check over every Unicode - scalar value, `Lexer.byteUnicodeValidated : Lexer.byteValidAll cbyte = true` - (`native_decide`, 70 ms for Cedar). Library: `Lexer/ByteUnicode.lean`, - `Lexer/ByteAgree.lean`. -- End-to-end theorems in `Verified` for `%option parseStr`: - `parseStr_eq_none_of_tokenize_error` (lexing fails → `parseStr` is `none`), - `runStream_ne_ok_of_tokenize_error`, `parseStr_sound_tokenize`, - and, for a lexer with one mode whose rules all stay, `parseStr_sound_tokenization` (an - accepted `parseStr s` comes with a maximal-munch `Lexer.Tokenization` of `s`, the spec - tokenizer's tokens and a parse tree) and `tokenize_parse_sound` (the same for `tokenize` - then `parse`). Library: `Lexer/LexerSound.lean`, `Runtime/ParseEnd.lean`. -- Lexer modules emit `noEofEmit` (no rule emits the `%eof` token) and, for one mode whose - rules all stay, `stay0`, `textIndep0` and `tokenize_sound`. -- Spans in the verified specification. `Runtime.SpanGrammar` (`Runtime/SpanGrammar.lean`): - a grammar whose parse trees have positioned tokens and whose actions receive the spans - of their right-hand-side symbols; `ptSpan`/`ptSem`, `ptSpan_endPos`, `ptSpan_startPos`, - `allSpanFacts`, and `SpanGrammar.parseCorrect`, `parseComplete`, `unambiguity`, which - transfer the generic theorems through the derived grammar `SpanGrammar.toGrammar` - (`ptSem_toGrammar`). The refinement simulation (`Runtime/Refinement.lean`) relates the - executable parser to it on real spans. `Span.fold`, `Span.listEnd`, - `Positioned.wordEnd`. -- String-level completeness and unambiguity. Library (`Lexer/Lexing.lean`): `Lexing` - (a maximal-munch tokenization with its steps), `Lexing.unique`, `tokenize_complete`, - `tokenize_lexing`, `tokenizeFlatStrPos_complete`; `PosLexing` (the positioned - tokenization: spans delimit lexemes, skip rules consume the bytes between tokens), - `tokenizeFlatStrPos_iff_posLexing`, `PosLexing.unique`, `PosLexing.spans_ordered`, - `lexPos_ok_iff`. Lexer modules (one mode, all rules stay): `tokenize_complete`, - `Lexes`, `tokenize_iff_lexes`, `lexPos_iff_lexes`, `lexes_unique`. `Verified`: - `parseStr_complete`, `parseStr_complete_lexing`, `parseStr_unambiguous`, - `parseStr_sound_lexes`, `parseStr_complete_lexes`, `parseStr_unambiguous_lexes`, - `parseStr_node_spans`. -- `spanuse.SpanUseVerified`, a grammar whose action reads a span, is in `VerifiedSmoke`. -- Soundness over the whole input. `Verified` (with `%option parseStr`, a lexer with - one mode whose rules all stay, and a valueless `%eof` token): `endMarker_last` - (`native_decide`: `$` is the last symbol of every start production, and no other - right-hand-side position holds `$` or the start symbol), `word_eq_of_lexes` (a start - tree whose word begins the stream of `ts`, for `Lexes s ts`, has the word `ts`) and - `parseStr_sound_exact` (an accepted `parseStr s` gives `tokenize s = .ok ts`, - `Lexes s ts` and a parse tree over exactly `ts`). Lexer modules: `lexes_eof_last`. - Library: `Runtime.EndMarkerLast`, `Runtime.parseTree_start_word`, - `Runtime.start_word_eq` (`Runtime/ParseEnd.lean`), `Lexer.PosLexing.eof_last`, - `Lexer.modeAct_emit_of_agrees` (`Lexer/Lexing.lean`). -- Node spans as text of the input. Library (`Lexer/SpanText.lean`, new): - `Lexer.AllNodeText`, `Lexer.NodeText`, `Lexer.allNodeText`, - `Lexer.PosLexing.allNodeText`; in `Lexer/Lexing.lean`: `Lexer.SpanIn`, - `Lexer.TokenLexeme`, `Lexer.PosLexing.tokenLexeme`. -- Lexer modules emit `tokenizeByte_toOption`: `tokenizeByte` succeeds exactly when - `tokenize` does, with the same token values. Library: `Lexer.tokenizeByte_eq_lexPos` - (`tokenizeByte` is `lexPos` without spans) and `Lexer.tokenizeByte_toOption`. +- `%option parseStr`: `Parser.parseStr : String → …` parses while pulling tokens from + the byte lexer, without a token list. It stops at the first error, lex or parse. +- String-level theorems in `Verified` for `%option parseStr`, with no hypothesis: + - `parseStr_eq`, `parseStr_eq_dependent`, `parseStr_sound`: `parseStr` agrees with + `tokenize` followed by `parse`. + - `parseStr_eq_none_of_tokenize_error`, `runStream_ne_ok_of_tokenize_error`: a lex error + is never an accept. + - `parseStr_sound_exact`: an accepted `parseStr s` gives `tokenize s = .ok ts`, the + positioned tokenization `Lexes s ts`, and a parse tree over exactly `ts`. + - `parseStr_complete`, `parseStr_complete_lexing`, `parseStr_complete_lexes`: a + tokenization of `s` plus a parse tree within the fuel make `parseStr` return its value. + - `parseStr_unambiguous`, `parseStr_unambiguous_lexes`: two derivations of `s` have the + same tokens and value. + - `parseStr_node_spans`: every leaf's span is its lexeme in `s`; every node's span is a + byte range of `s` that ends at the node's last token. + - Conditions: the theorems that use the `Tokenization`/`Lexes` specification need a + lexer with one mode whose rules all stay; the soundness and lex-failure theorems need a + `%eof` token without a value. See `docs/GUARANTEES.md`. +- Lexer modules: `posLexerAgrees` (the positioned byte lexer `lexPos` and `tokenize` give + the same result, for every lexer, multi-mode included), from the `native_decide` check + `byteUnicodeValidated` over every Unicode scalar value; `noEofEmit`; `tokenize_complete`, + `Lexes`, `lexes_unique`, `lexes_eof_last`; `tokenizeByte_toOption`. +- Spans in the verified specification (`Runtime/SpanGrammar.lean`): parse trees over + positioned tokens, actions that receive the spans of their right-hand side, and the + generic theorems transferred to them. Grammars whose actions read spans + (`test/spanuse`) now have all theorems. +- The list macro `separated_list_trailing(sep, X)`: zero or more `X` separated by `sep`, + with an optional trailing `sep` (BNFC's `separator`). +- `leanparsergenerator --list-errors `: prints the parser states that can reject + a token, as a template for per-state messages to `errorMessage`. ### Changed -- Breaking: the generated specification is a `Runtime.SpanGrammar` (`spanGrammarInst`); - `grammarInst` is its derived `Grammar`, with token type `Runtime.Positioned Tok`. Each - `semanticAction

` takes the right-hand-side spans first. `ParserStartTree`, - `toStream` and the dependent `parse` take positioned tokens. `parse_eq_dependent`, - `parser_sound`, `parser_complete`, `parser_err_free` and `parser_ne_err` are stated on - positioned tokens with their real spans (`E.parse input`, not - `E.parse (input.map (⟨·, Span.dummy⟩))`); the tree value is - `Runtime.SpanGrammar.ptSem ⟨0⟩ tree`. `parser_unambiguous` takes a start position - (default byte 0) and also equates the spans. `parseStr_*` theorems state - `toStream ts` instead of `toStream (ts.map (·.val))`. No generated theorem takes `hspan`. +- Breaking: the generated specification is over positioned tokens. `parse_eq_dependent`, + `parser_sound`, `parser_complete`, `parser_err_free` and `parser_ne_err` are stated for + the real token spans (`E.parse input`, not `E.parse (input.map (⟨·, Span.dummy⟩))`); a + tree's value is `Runtime.SpanGrammar.ptSem ⟨0⟩ tree`; `parser_unambiguous` also equates + spans and returns a conjunction. Each `semanticAction

` takes the right-hand-side + spans first. `%option roundtrip_parser` constructors build trees over + `Positioned.dummy` words. - Breaking: the span of an empty right-hand side is the empty span at the end of the last - shifted token (byte 0 at the start), as in the Rust backend, instead of `Span.dummy`. - This changes `run` results and span values read by actions, not `parse` values of - span-free grammars. -- Breaking (runtime API): `ExecTable.sem` and `FlatTable.sem` take the stack below the - popped cells (`Nat → Stack V → List V → V`); generated parsers define - `sem := Runtime.Exec.spanSem semV` with `semV : Nat → List Span → List V → V`. - `StackOps` has a new field `endPos` with the law `endPos_eq`; generated stacks define - `Stk.endPos` and `Stk.withTop`. `Runtime.Refinement.ExecRefinement` is over a - `SpanGrammar`, with the new fields `semV` and `sem_agrees`, and `semantic_agrees` takes a - span list. `Runtime.Refinement.Values` is now `Runtime.SpanGrammar.Values`. -- Breaking: parse-tree constructors of `%option roundtrip_parser` build trees over - dummy-positioned words (`(w : List Tok).map Positioned.dummy`), their `_sem` lemmas are - stated for `SpanGrammar.ptSem pe`, and `Certificate.tree` is over - `(tokens ++ [EOF]).map Positioned.dummy` with `semantics : SpanGrammar.ptSem ⟨0⟩ tree = value`. -- The dependent `parse` is evaluated by `decide +kernel` in tests; plain `decide` does not - finish on the derived span semantics. -- Breaking: `parseStr_unambiguous` in `Verified` takes two derivations of `s`, - `tokenize s = .ok ts₁` with a tree over `ts₁` and `tokenize s = .ok ts₂` with a tree over - `ts₂`, and gives `ts₁ = ts₂` and equal values. It no longer takes two `Lexer.Lexing` - derivations and two trees over an unrelated `ts`; `Lexer.Lexing.unique` gives the - uniqueness of the steps. -- Breaking: `parseStr_node_spans` concludes `Lexer.AllNodeText … s ⟨0⟩ tree` (every leaf - is its lexeme in `s`, every node's span is a substring of `s` with `SpanFacts`) instead of - `Lexes s ts ∧ SpanGrammar.AllSpanFacts ⟨0⟩ tree`. -- Breaking: `parseStr_eq`, `parseStr_eq_dependent`, `parseStr_sound` and - `parseStr_of_tokenize_error` in `Verified` no longer take `hlex : PosLexerAgrees`. - A caller that passed `hlex` must drop that argument. `PosLexerAgrees` stays as an - `abbrev`, with `posLexerAgrees : PosLexerAgrees`. -- A `noEofEmit` proof for a rule that calls a helper falls back to `simp` with every - `%lexerheader` definition when unfolding the helper alone fails, so a helper that calls - another helper or branches on a `let` no longer makes the lexer fail to compile - (`docs/LEXER.md`). - -- The list macros (`list`, `nonempty_list`, `separated_list`, `separated_nonempty_list`) - are left-recursive and produce an `Array` in Lean and a `Vec` in Rust, instead of a - `List` and a `VecDeque`. Grammars whose actions take a macro list as a `List` need - `.toList` (Lean) or `.into()` (Rust, to a `VecDeque`). The LR stack no longer grows with - the length of a list. -- `separated_list(sep, X)` no longer accepts a trailing separator (`a, b,`), as documented; - it is `ε` or `separated_nonempty_list(sep, X)`. A grammar that relies on the trailing - separator, for example one translated from BNFC's `separator`, uses - `separated_list_trailing(sep, X)` instead. -- Generated Lean lexers read their actions from a table, `fastActs`, with - `fastActs_agree` and `tokenize_eq_flat` proving the results unchanged. Lexing is - 11–15% faster on the benchmarks. + shifted token, as in the Rust backend, not `Span.dummy`. +- Breaking (runtime API): `ExecTable.sem`/`FlatTable.sem` take the stack below the popped + cells; generated parsers define `sem := Runtime.Exec.spanSem semV`; `StackOps` has a new + field `endPos`. +- Breaking: the list macros are left-recursive and produce `Array` (Lean) / `Vec` (Rust) + instead of `List` / `VecDeque`. The LR stack no longer grows with the length of a list. +- Breaking: `separated_list(sep, X)` no longer accepts a trailing separator; use + `separated_list_trailing`. +- Generated lexers read their actions from a table (`fastActs`); lexing is 11–15% faster. +- The CLI's `wrote …` lines give the dotted module name (`module MyProject.ExprParser`). +- Tests evaluate the dependent `parse` with `decide +kernel`; plain `decide` does not finish. ### Removed -- `Runtime.Exec.SpanIndependent`, `SemSpanFree`, `SemSpanFree.of_split`, - `SpanIndependent.of_run`, `run_erase` and its helpers (`Runtime/ExecStream.lean`), - `Runtime.Exec.runFast_ok_dummy` (`Runtime/ParseEnd.lean`); in generated modules, - `semS`, `semSpanFree`, `parse_spanIndependent`, `SpanIndependent`, `spanIndependent`, - `parse_eq_dependent_spans`, the `hspan` arguments, and the dummy-span form of - `parse_eq_dependent`. They are not needed now that the specification has spans. -- Lexer modules no longer emit `byteValidated{m}` (`Lexer.byteValidate`, a - one-character-per-class check of the byte tables, `native_decide`). It does not imply - that the byte and flat lexers agree, and no theorem used it; `byteUnicodeValidated` - checks every character. It is removed rather than deprecated because nothing depends on - it and versions before 1.0 may change the generated module API. `Lexer.byteValidate` - stays in the library. +- Lexer modules no longer emit `byteValidated{m}`; `byteUnicodeValidated` replaces it. + +### Fixed + +- The language server reports the tool version (`0.1.0-alpha.1`) instead of `0.1.0`. ### Experimental -- Pull-based Rust API is always emitted: `TokenSource`, `SliceSource`, `NodeSink`, +- Pull-based Rust API, always emitted: `TokenSource`, `SliceSource`, `NodeSink`, `StreamError`, `parse_from`, `parse_values_from` and, with a `%lexer`, `Lexer` - (`next_token`, `finish`), `parse_str` and `parse_values_str`. `tokenize`, `parse` - and `parse_values` keep their signatures and results. `tokenize` alone is 3–4% - slower, because it is now a loop over `Lexer::next_token`; lex+parse is unchanged. + (`next_token`, `finish`), `parse_str`, `parse_values_str`. `tokenize`, `parse` and + `parse_values` keep their signatures. ## [0.1.0-alpha.1] - 2026-11-27 diff --git a/LeanParserGenerator/Construct/Analysis.lean b/LeanParserGenerator/Construct/Analysis.lean index f278a5d..2ba4a47 100644 --- a/LeanParserGenerator/Construct/Analysis.lean +++ b/LeanParserGenerator/Construct/Analysis.lean @@ -22,8 +22,6 @@ Construct the nullable and FIRST sets by a fixpoint over the grammar. Both iterate a monotone fixpoint. They feed Pager closure and the generated `nullableNt`/`firstNt` certificate annotations. - -See tests in `test/pager/ConstructionRegressionTest.lean`. -/ public import LeanParserGenerator.IR.Grammar @@ -35,9 +33,8 @@ namespace Construct open IR /-- Sorted-insert into a sorted, duplicate-free list of nats (our set repr). - TODO: can we improve that repr and maintain the decidability of the generated - proof obligations? --/ + Another set representation would have to keep the generated proof obligations + decidable. -/ def insertNat (x : Nat) : List Nat → List Nat | [] => [x] | y :: ys => diff --git a/LeanParserGenerator/Emit/Builder.lean b/LeanParserGenerator/Emit/Builder.lean index 0490076..c825314 100644 --- a/LeanParserGenerator/Emit/Builder.lean +++ b/LeanParserGenerator/Emit/Builder.lean @@ -32,14 +32,6 @@ namespace Emit.Builder /-- A Lean string literal for `value` (`reprStr` gives a `"…"` with standard escapes). -/ def strLit (value : String) : String := reprStr value -/-- A `Nat` literal. -/ -def natLit (n : Nat) : String := toString n - -/-- An `Option Nat` literal (`none` / `some n`). -/ -def optNatLit : Option Nat → String - | none => "none" - | some n => s!"some {n}" - /-- Join fragments with a single separator. -/ def joinWith (sep : String) (parts : List String) : String := sep.intercalate parts @@ -71,17 +63,6 @@ def publicizeImports (header : String) : String := else ln "\n".intercalate ((header.splitOn "\n").map rewrite) -/-- A Lean array literal `#[a, b, c]` from already-rendered element strings. -/ -def arrayLit (elems : List String) : String := "#[" ++ commaSep elems ++ "]" - -/-- A `Nat` list literal `[1, 2, 3]`. -/ -def natListLit (l : List Nat) : String := listLit (l.map natLit) - -/-- A top-level array-table def: `def {name} : Array {ty} := #[{elems}]`. Used for - the flat action/goto/length tables. -/ -def arrayDef (name ty : String) (elems : List String) : String := - s!"def {name} : Array {ty} := " ++ arrayLit elems - /-- Names defined with `def` (or `abbrev`) in header text. -/ def headerDefs (header : String) : List String := let ws := (header.replace "\n" " ").splitOn " " |>.filter (!·.isEmpty) diff --git a/LeanParserGenerator/Emit/Codegen.lean b/LeanParserGenerator/Emit/Codegen.lean index bc43658..f901001 100644 --- a/LeanParserGenerator/Emit/Codegen.lean +++ b/LeanParserGenerator/Emit/Codegen.lean @@ -244,13 +244,6 @@ def emitSem (s : Surface) (e : TyEnv) (augProd : Nat) : let semDef ← `(command| def $(mkIdent `sem) : $semSig := $semBody) return #[semV, semDef] -/-- Whether some action names a span variable (`_span` or `__s`), so its value - may depend on token spans. -/ -def actionsReadSpans (s : Surface) : Bool := - s.rules.any fun r => r.alts.any fun alt => - alt.elems.zipIdx.any fun (elem, i) => - (alt.action.splitOn (spanVarName elem i)).length > 1 - /-- The `Stk` cell constructor for a `V` constructor: `cUnit` for `unit`, `c` for `v`. -/ def cellFor (ctor : String) : String := diff --git a/LeanParserGenerator/Emit/CodegenLexer.lean b/LeanParserGenerator/Emit/CodegenLexer.lean index 2d9e5a6..1d0745f 100644 --- a/LeanParserGenerator/Emit/CodegenLexer.lean +++ b/LeanParserGenerator/Emit/CodegenLexer.lean @@ -310,8 +310,9 @@ def generateLexerFrom (surface : Surface) (moduleName : String) : s!" ∀ s, ({moduleName}.fastActs.get 0 r).toAct s = ({moduleName}.fastActs.get 0 r).toAct \"\" :=\n" ++ s!" Lexer.FastActs.textIndep_of_forall₂ {moduleName}.fastActs ({moduleName}.cflat.textDep.getD 0 #[]) 0\n" ++ s!" {textChain}\n\n" ++ - s!"/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec\n" ++ - s!" tokenizer `Lexer.tokenize` returns the same token values. -/\n" ++ + s!"/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization\n" ++ + s!" (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values\n" ++ + s!" of `ts`. -/\n" ++ s!"theorem {moduleName}.tokenize_sound \{input : String} \{ts : List (Runtime.Positioned {tokTy})}\n" ++ s!" (h : {moduleName}.tokenize input = .ok ts) :\n" ++ s!" Lexer.Tokenization {moduleName}.rules0 input.toList ∧\n" ++ diff --git a/LeanParserGenerator/Emit/CodegenVerified.lean b/LeanParserGenerator/Emit/CodegenVerified.lean index 7abdf9e..ffaedc5 100644 --- a/LeanParserGenerator/Emit/CodegenVerified.lean +++ b/LeanParserGenerator/Emit/CodegenVerified.lean @@ -361,27 +361,6 @@ def emitToken (s : Surface) (eofIdx : Nat) : EmitM (Array (TSyntax `command)) := /-! ### Emitting the dependent `Automaton` instance -/ -/-- Emit an `Action` value for state `st` from the Pager tables. Either a - `Default_reduce` (when the state has a default reduction) or a `Lookahead` - function matching on the terminal index. Shift arms carry the `rfl` proof - `Symbol.T term = lastSymb' target`; reduce arms name the production; `Fail` - otherwise. -/ -def emitActionValue (tables : Tables) (numT' : Nat) (st : Nat) : String := Id.run do - match tables.defaultReduce.getD st none with - | some p => s!"Action.DefaultReduce ⟨{p}, of_decide_eq_true rfl⟩" - | none => - let row := tables.action.getD st #[] - let mut arms : Array String := #[] - for t in [0:numT'] do - let arm := match row.getD t Act.error with - | .shift j => s!"LookaheadAction.Shift ⟨{j-1}, of_decide_eq_true rfl⟩ (by rfl)" - | .reduce p => s!"LookaheadAction.Reduce ⟨{p}, of_decide_eq_true rfl⟩" - | .error => "LookaheadAction.Fail" - arms := arms.push s!" | ⟨{t}, _⟩ => {arm}" - let body := "fun term => match term with\n" ++ "\n".intercalate arms.toList - ++ "\n | _ => LookaheadAction.Fail" - "Action.Lookahead (" ++ body ++ ")" - /-- Number of bits needed to store every value in `0 … n`. -/ def bitWidth (n : Nat) : Nat := Nat.log2 n + 1 @@ -820,8 +799,9 @@ def emitRefinement (s : Surface) (g' : IR.Grammar) (execModule : String) : Strin " Grammar.ParseTree (G := grammarInst)", " (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word", "", - "/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value,", - " at the start of the input, is the result. -/", + "/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input`", + " (`toStream input`) starts with the word of a parse tree whose value, at the start of the", + " input, is the result. -/", "theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat)", s!" (semantic : {nontermTy s s.ntNames realStart})", s!" (accepted : {execModule}.parse input logNSteps = some semantic) :", @@ -846,6 +826,8 @@ def emitRefinement (s : Surface) (g' : IR.Grammar) (execModule : String) : Strin " refine ⟨word, tree, rest, inputEq, ?_⟩", " rw [← valueEq, semanticEq]", "", + "/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of", + " inconsistent tables), on every token list and fuel. -/", "theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) :", s!" Runtime.Exec.ResultErrFree ({execModule}.run input logNSteps) := by", " have related := parserRunRefines input logNSteps", @@ -864,6 +846,7 @@ def emitRefinement (s : Surface) (g' : IR.Grammar) (execModule : String) : Strin " | timeout => trivial", " | error message => exact dependentFree", "", + "/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/", "theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat)", " (message : String) :", s!" {execModule}.run input logNSteps ≠ .err message := by", @@ -872,6 +855,7 @@ def emitRefinement (s : Surface) (g' : IR.Grammar) (execModule : String) : Strin " rw [isError] at errorFree", " exact errorFree", "", + "/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/", "theorem toStream_eq_appList (input : List grammarInst.Token) :", " toStream input = Runtime.AppStream.appList input (toStream []) := by", " funext index", @@ -1038,6 +1022,7 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) "", s!"theorem posLexerAgrees : PosLexerAgrees := {l}.posLexerAgrees", "", + "/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/", s!"theorem lexPos_eq_of_tokenize (s : String) (ts : {posToks}) (h : {l}.tokenize s = .ok ts) :", s!" Lexer.lexPos {l}.cbyte s = .ok ts := by", " have hagree := posLexerAgrees s", @@ -1047,16 +1032,21 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) " | error e => intro hc; simp [Except.toOption] at hc", " | ok v => intro hc; simp [Except.toOption] at hc; rw [hc]", "", + "/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/", s!"theorem parseStr_eq (s : String) (k : Nat) (ts : {posToks})", s!" (h : {l}.tokenize s = .ok ts) : {E}.parseStr s k = {E}.parse ts k := by", hp, s!" exact {E}.parseStr_eq_lexPos s k ts hp", "", + "/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/", "theorem parseStr_eq_dependent (s : String)", s!" (k : Nat) (ts : {posToks}) (h : {l}.tokenize s = .ok ts) :", s!" {E}.parseStr s k = parse ts k := by", " rw [parseStr_eq s k ts h, parse_eq_dependent]", "", + "/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s`", + " with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a", + " parse tree whose value is `p`. -/", "theorem parseStr_sound (s : String)", s!" (k : Nat) (ts : {posToks}) (h : {l}.tokenize s = .ok ts) (p : {startTy})", s!" (accepted : {E}.parseStr s k = some p) :", @@ -1065,23 +1055,7 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) " toStream ts = Runtime.NatStream.appList word rest ∧", " SpanGrammar.ptSem ⟨0⟩ tree = p := by", " rw [parseStr_eq s k ts h] at accepted", - " exact parser_sound ts k p accepted", - "", - "/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr`", - " is `none` or `parse` of an extension of `ts`. -/", - "theorem parseStr_of_tokenize_error (s : String) (k : Nat)", - s!" (e : Lexer.LexError) (h : {l}.tokenize s = .error e) :", - s!" ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux {l}.cbyte s.toUTF8))", - s!" ⟨false, s.toUTF8.size + 1, 0, [{l}.cbyte.flat.base.start]⟩ ts e' ∧", - s!" ∀ tail, {E}.parseStr s k = none ∨ {E}.parseStr s k = {E}.parse (ts ++ tail) k := by", - s!" rcases {E}.parseStr_total s k with ⟨ts, hD, _⟩ | hF", - " · exfalso", - s!" have hp : Lexer.lexPos {l}.cbyte s = .ok ts :=", - s!" Lexer.lexPosAux_of_denotes {l}.cbyte s.toUTF8 _ _ _ ts hD", - " have hagree := posLexerAgrees s", - " rw [hp, h] at hagree", - " simp [Except.toOption] at hagree", - " · exact hF" ] + " exact parser_sound ts k p accepted" ] let failBlock := match eofCtor with | none => "" | some eof => "\n\n" ++ lines [ @@ -1091,6 +1065,7 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) s!" Symbol.T (⟨{eofIdx}, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by", " native_decide", "", + s!"/-- Only the `{eof}` token has the terminal of the end marker `$`. -/", s!"theorem tokenTerm_eq_end (t : {tokenType})", s!" (h : tokenTerm' t = (⟨{eofIdx}, of_decide_eq_true rfl⟩ : Terminal)) : t = .{eof} := by", " cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl)", @@ -1107,6 +1082,7 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) s!" startProds_end input ⟨.{eof}, Runtime.Span.dummy⟩ rfl", " (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest", "", + s!"/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/", s!"theorem parse_eq_none_of_no_eof (input : {posToks}) (k : Nat)", s!" (hin : ∀ t ∈ input, t.val ≠ .{eof}) (hlen : 2 ^ k < input.length) : parse input k = none := by", " unfold parse", @@ -1115,7 +1091,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) " | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest)", " | _ => rfl", "", - s!"/-- A prefix of lexed tokens with no `{eof}`, padded with copies of its first token. -/", + s!"/-- A token list `t0 :: ts` with no `{eof}`, padded with `2^k + 1` copies of `t0`, has no", + s!" `{eof}` and is longer than `2^k`. -/", s!"theorem no_eof_pad (t0 : Runtime.Positioned {tokenType}) (ts : {posToks})", s!" (hts : ∀ t ∈ t0 :: ts, t.val ≠ .{eof}) (k : Nat) :", s!" (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .{eof}) ∧", @@ -1201,7 +1178,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) " exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep", "", "/-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to", - " `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/", + " `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse", + " tree whose value is `p`. -/", s!"theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : {startTy})", s!" (accepted : {E}.parseStr s k = some p) :", s!" ∃ ts, {l}.tokenize s = .ok ts ∧", @@ -1217,8 +1195,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) (if !tokSound then "" else "\n\n" ++ lines [ "/-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`,", " then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer", - " returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse", - " tree whose value is `p`. -/", + " returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts`", + " (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/", s!"theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : {startTy})", s!" (accepted : {E}.parseStr s k = some p) :", s!" ∃ ts, {l}.tokenize s = .ok ts ∧ Lexer.Tokenization {l}.rules0 s.toList ∧", @@ -1233,7 +1211,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) let tokParse := if !tokSound then "" else "\n\n" ++ lines [ "/-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with", " value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token", - " values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/", + " values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of", + " a parse tree whose value is `p`. -/", s!"theorem tokenize_parse_sound (s : String) (k : Nat) (ts : {posToks}) (p : {startTy})", s!" (h : {l}.tokenize s = .ok ts) (accepted : {E}.parse ts k = some p) :", s!" Lexer.Tokenization {l}.rules0 s.toList ∧ Lexer.tokenize {l}.lexer s = .ok (ts.map (·.val)) ∧", @@ -1244,8 +1223,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) s!" obtain ⟨htok, hspec⟩ := {l}.tokenize_sound h", " exact ⟨htok, hspec, parser_sound ts k p accepted⟩", "", - "/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol", - " spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/", + "/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word", + " exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/", s!"theorem parseStr_complete (s : String) (k : Nat) (ts : {posToks})", s!" (h : {l}.tokenize s = .ok ts) (tree : ParserStartTree ts)", " (fuel : Grammar.ptSize tree ≤ 2 ^ k) :", @@ -1276,8 +1255,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) " exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩", "", "/-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s`", - s!" (`{l}.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel,", - " `parseStr` returns the tree's value. -/", + s!" (`{l}.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr`", + " returns the tree's value. -/", s!"theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : {posToks})", s!" (h : {l}.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) :", s!" {E}.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) :=", @@ -1299,9 +1278,9 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) s!" `s` (`{l}.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's", " action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the", " end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions", - " `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start", - " of the lexeme of its first token or, when its word is empty or its leftmost children", - " derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/", + " `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before", + " the node when the word is empty) and `a` is `pe` or the start of the first token of the", + " word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/", s!"theorem parseStr_node_spans (s : String) (ts : {posToks}) (h : {l}.Lexes s ts)", " (tree : ParserStartTree ts) :", s!" Lexer.AllNodeText (Lexer.modeAct {l}.lexer {l}.lexer.start) {l}.lexer.eofToken s ⟨0⟩ tree :=", @@ -1309,8 +1288,8 @@ def emitStreamTransfer (tokenType startTy E l : String) (eofIdx : Nat) let eofC := eofCtor.getD "EOF" let lexesSound := if tokSound && eofCtor.isSome then "\n\n" ++ lines [ "/-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then", - s!" `s` has a positioned tokenization `ts` (`{l}.Lexes`), and `ts` starts with the word of a", - " parse tree whose value is `p`. -/", + s!" `s` has a positioned tokenization `ts` (`{l}.Lexes`), and the EOF-padded stream of `ts`", + " (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/", s!"theorem parseStr_sound_lexes (s : String) (k : Nat) (p : {startTy})", s!" (accepted : {E}.parseStr s k = some p) :", s!" ∃ ts, {l}.Lexes s ts ∧", diff --git a/LeanParserGenerator/Frontend/File.lean b/LeanParserGenerator/Frontend/File.lean index 65e7305..c8329d8 100644 --- a/LeanParserGenerator/Frontend/File.lean +++ b/LeanParserGenerator/Frontend/File.lean @@ -708,7 +708,7 @@ def scanEscape : ScanM (Except String Char) := do | '"' => return .ok '"' | '\'' => return .ok '\'' | 'u' => - -- \uXXXX : exactly four hex digits + -- \u followed by one to four hex digits let mut cur ← get let mut n := 0 let mut count := 0 diff --git a/LeanParserGenerator/Frontend/Generated/LigVerified.lean b/LeanParserGenerator/Frontend/Generated/LigVerified.lean index 595e4a4..f7d110b 100644 --- a/LeanParserGenerator/Frontend/Generated/LigVerified.lean +++ b/LeanParserGenerator/Frontend/Generated/LigVerified.lean @@ -1293,8 +1293,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Frontend.LigResult) (accepted : LigParser.parse input logNSteps = some semantic) : @@ -1319,6 +1320,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (LigParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -1337,6 +1340,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : LigParser.run input logNSteps ≠ .err message := by @@ -1345,6 +1349,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index diff --git a/LeanParserGenerator/Frontend/LigLexer.lean b/LeanParserGenerator/Frontend/LigLexer.lean index 3b6b317..bfac7d5 100644 --- a/LeanParserGenerator/Frontend/LigLexer.lean +++ b/LeanParserGenerator/Frontend/LigLexer.lean @@ -18,7 +18,7 @@ module public import LeanParserGenerator.Frontend.File /- Hand-written lexer for the `.lig` structural language, the escape hatch half of -the bootstrap (DESIGN §15.4). +the bootstrap (DESIGN §15). The `.lig` grammar-file language is context-free in its *structure* (the sequence of `%`-directives, the rule/alternative/element shape), but its leaves are diff --git a/LeanParserGenerator/Frontend/LigParse.lean b/LeanParserGenerator/Frontend/LigParse.lean index a09dda4..08edc0d 100644 --- a/LeanParserGenerator/Frontend/LigParse.lean +++ b/LeanParserGenerator/Frontend/LigParse.lean @@ -18,7 +18,8 @@ module public import LeanParserGenerator.Frontend.LigLexer public import LeanParserGenerator.Frontend.Generated.LigParser /- -The verified `.lig` parser: its main entry point. +The `.lig` parser generated from `lig.lig`: its main entry point. Its `LigParser` has the +generated proofs; the lexer is hand-written. `parseLigGen` is the generated-parser counterpart of the hand-written `Frontend.parseLig`: it tokenizes `.lig` source with the hand-written diff --git a/LeanParserGenerator/LSP/Server.lean b/LeanParserGenerator/LSP/Server.lean index 0381d6e..d04eb1d 100644 --- a/LeanParserGenerator/LSP/Server.lean +++ b/LeanParserGenerator/LSP/Server.lean @@ -108,7 +108,7 @@ def initializeResult : Json := ]), ("serverInfo", Json.mkObj [ ("name", Json.str "lig-language-server"), - ("version", Json.str "0.1.0") + ("version", Json.str "0.1.0-alpha.1") ]) ] diff --git a/LeanParserGenerator/Lexer/SpanText.lean b/LeanParserGenerator/Lexer/SpanText.lean index 78819f1..c1b84d9 100644 --- a/LeanParserGenerator/Lexer/SpanText.lean +++ b/LeanParserGenerator/Lexer/SpanText.lean @@ -17,16 +17,17 @@ module /- The spans of a parse tree over a positioned tokenization, as text of the input -(docs/DESIGN.md §6.2). +(docs/DESIGN.md §4.4, §6.1). `SpanGrammar.allSpanFacts` relates each node's span to the tokens of its word, and `PosLexing` relates each token to its lexeme in the input `s`. This file combines the two. `AllNodeText act eof s pe t`: every leaf of `t` is a token with its lexeme in `s` (`TokenLexeme`), and every inner node's span delimits a substring of `s` (`SpanIn`) and -satisfies `SpanFacts`. So the substring ends at the end of the lexeme of the node's last -token, and starts at the start of the lexeme of its first token or, under the Rust -convention, at the end `pe` of the token before the node (an empty word, or leftmost -children that derive the empty word). +satisfies `SpanFacts`. So the substring ends at the end of the node's word (at the end `pe` +of the token before the node when the word is empty), and starts at `pe` or at the start of +the lexeme of its first token. `SpanFacts` does not state which of the two applies; the +parser takes `pe` for an empty word or leftmost children that derive the empty word (the +Rust convention). `PosLexing.allNodeText`: every tree over a `PosLexing` of `s` from `p` has `AllNodeText … p.offset`. diff --git a/LeanParserGenerator/Runtime/Alphabet.lean b/LeanParserGenerator/Runtime/Alphabet.lean index e5e833a..bd2d30b 100644 --- a/LeanParserGenerator/Runtime/Alphabet.lean +++ b/LeanParserGenerator/Runtime/Alphabet.lean @@ -20,7 +20,7 @@ Finite, comparable index types: the foundation of the runtime core. Terminals, non-terminals, states and productions are all `Alphabet`s. The classes here are Mathlib-free and built on Lean's native `Ordering`/`DecidableEq`. -Design decisions (see docs/DESIGN.md §5.1): +Design decisions: * `Comparable` gives a `cmp` with antisymmetry and transitivity laws. * `Finite` provides an enumeration `all` with a completeness proof. * `Numbered` is the cheap way to build all of the above: a bijection with diff --git a/LeanParserGenerator/Runtime/Automaton.lean b/LeanParserGenerator/Runtime/Automaton.lean index 116e844..1068b69 100644 --- a/LeanParserGenerator/Runtime/Automaton.lean +++ b/LeanParserGenerator/Runtime/Automaton.lean @@ -44,7 +44,7 @@ inductive State (InitState NonInitState : Type) where | Init : InitState → State InitState NonInitState | Ninit : NonInitState → State InitState NonInitState -/-! `State I N` is an alphabet whenever `I` and `N` are (it is essentially `I ⊕ N`). +/-! `State I N` is an alphabet whenever `I` and `N` are (it is isomorphic to `I ⊕ N`). The safety validator quantifies over all states (`Finite`), compares them (`singletonStatePred` uses `DecidableEq`), so we derive the full `Alphabet` stack here from the component alphabets. -/ diff --git a/LeanParserGenerator/Runtime/Buffer.lean b/LeanParserGenerator/Runtime/Buffer.lean index 3f89fea..aad55e4 100644 --- a/LeanParserGenerator/Runtime/Buffer.lean +++ b/LeanParserGenerator/Runtime/Buffer.lean @@ -18,7 +18,7 @@ module /- The input token stream, abstracted behind a type class so the interpreter observes the input only through sequential `head`/`tail` (see docs/DESIGN.md -§5.4). This is the `buffer` of §2.4 in Validating LR(1) Parsers, generalized +§4.3). This is the `buffer` of §2.4 in Validating LR(1) Parsers, generalized from a concrete coinductive stream to any instance of the class. * The interpreter and all correctness theorems are stated over an arbitrary diff --git a/LeanParserGenerator/Runtime/Diagnostic.lean b/LeanParserGenerator/Runtime/Diagnostic.lean index 1a34312..b82d00c 100644 --- a/LeanParserGenerator/Runtime/Diagnostic.lean +++ b/LeanParserGenerator/Runtime/Diagnostic.lean @@ -39,9 +39,11 @@ offending lookahead terminal. This module builds the Menhir-style layer on top: Like `Runtime.Exec` itself, this layer is **unverified** in the sense that it is not part of the trusted specification. It is, however, proved *consistent* with -the verified engine: `diagnose_run_agrees` shows the accept/reject/timeout -classification of `diagnose` is exactly that of the verified `Runtime.Exec.run`, -so an error is only ever reported when `run` genuinely rejects. +the executable engine: `diagnose_run_agrees` shows the accept/reject/timeout +classification of `diagnose` is exactly that of the executable `Runtime.Exec.run`, +which each `*Verified` module relates to the dependent parser (`parserRunRefines`; +for `parse`, `parse_eq_dependent`), so an error is only ever reported when `run` +rejects. -/ public import LeanParserGenerator.Runtime.Exec public import LeanParserGenerator.Runtime.Span @@ -196,12 +198,12 @@ def ParseError.format (e : ParseError) (terminalName : Nat → String) else "; expected one of: " ++ ", ".intercalate expected s!"syntax error at token {e.position}: unexpected {terminalName e.lookahead}{expectedStr} (in parser state {e.state})" -/-! ### Consistency with the verified engine +/-! ### Consistency with the executable engine The diagnostic runner reuses `step`, so its result agrees with `Runtime.Exec.run` by construction. We make that precise: erasing the extra remaining-input payload turns `parseFixD` back into `parseFix`, hence `runD` agrees with `run`. This -guarantees a syntax error is reported exactly when the verified parser rejects. -/ +guarantees a syntax error is reported exactly when `run` rejects. -/ theorem parseFixD_toResult (tbl : ExecTable V) : ∀ (stk : Stack V) (input : List (Nat × V)) (logN : Nat), @@ -239,7 +241,7 @@ theorem runD_fst_eq_run (tbl : ExecTable V) (input : List (Nat × V)) (logN : Na have : parseFix tbl [] input logN = .inr p := by rw [← h, hD]; rfl rw [this] -/-- `diagnose` classifies accept/reject/timeout exactly as the verified `run`: +/-- `diagnose` classifies accept/reject/timeout exactly as the executable `run`: it yields `.ok`/`.error`/`.timeout`/`.internal` iff `run` yields `.ok`/`.reject`/`.timeout`/`.err`. In particular a `ParseError` is produced precisely when `run` rejects. -/ diff --git a/LeanParserGenerator/Runtime/SpanGrammar.lean b/LeanParserGenerator/Runtime/SpanGrammar.lean index 685f4b1..fcf142c 100644 --- a/LeanParserGenerator/Runtime/SpanGrammar.lean +++ b/LeanParserGenerator/Runtime/SpanGrammar.lean @@ -301,9 +301,10 @@ theorem ptlSpans_listEnd (pe : Pos) : {heads : List Sym} → {word : List (Posit end mutual -/-- **A node's span starts at its first token or at `pe`.** When its word is empty the - span starts at `pe`. Otherwise it starts at the start of the first token of its word, - or, when the leftmost children of the node derive the empty word, at `pe`. -/ +/-- **A node's span starts at its first token or at `pe`.** The span starts at `pe`, or the + word is nonempty and the span starts at the start of its first token. (`ptSpan` takes + `pe` when the word is empty or the leftmost children derive the empty word; the theorem + does not state which case applies.) -/ theorem ptSpan_startPos (pe : Pos) : {head : Sym} → {word : List (Positioned SG.Tok)} → (t : ParseTree head word) → (ptSpan pe t).startPos = pe ∨ (∃ tok rest, word = tok :: rest ∧ (ptSpan pe t).startPos = tok.span.startPos) @@ -375,8 +376,9 @@ end mutual /-- **Every node's span is the span of its word.** In every tree, each node's span ends at the end of its last token (at the end `pe` of the token before it, when its word is - empty), and starts at the start of its first token, or at `pe` when its word is empty or - its leftmost children derive the empty word (the Rust convention). -/ + empty), and starts at `pe` or at the start of its first token (`SpanFacts`). The parser + takes `pe` when the word is empty or the leftmost children derive the empty word (the + Rust convention); `SpanFacts` does not state which case applies. -/ theorem allSpanFacts (pe : Pos) : {head : Sym} → {word : List (Positioned SG.Tok)} → (t : ParseTree head word) → AllSpanFacts pe t | _, _, .terminal tok => by diff --git a/Main.lean b/Main.lean index 4310c26..904e874 100644 --- a/Main.lean +++ b/Main.lean @@ -25,7 +25,7 @@ leanparsergenerator [options] One invocation generates every module for the grammar from one parse and one Pager construction. Output names come from the `.lig` stem, and the `.lig`'s `%option`s decide which optional modules are written. The flags below adjust the defaults. -`--print-grammar` and `--rust-report` inspect a grammar without writing files. +`--print-grammar`, `--list-errors` and `--rust-report` inspect a grammar without writing files. Exit codes: 0 on success, 1 on any error (bad arguments, unreadable input, `.lig` parse or generation error), 2 when Pager reports LR(1) conflicts. With exit code 2 @@ -36,6 +36,7 @@ public import LeanParserGenerator.Emit.CodegenVerified public import LeanParserGenerator.Emit.CodegenLexer public import LeanParserGenerator.Emit.CodegenRust public import LeanParserGenerator.Emit.Rust.Report +public import LeanParserGenerator.Emit.ErrorList public import LeanParserGenerator.Emit.CodegenLexerRoundtrip public import LeanParserGenerator.Emit.CodegenParserRoundtrip public import LeanParserGenerator.Frontend.File @@ -251,16 +252,16 @@ def generate (cfg : GenConfig) : IO UInt32 := do match Emit.generateLexerFrom surface lexerModule with | .error e => return ← fail s!"{ligPath}: lexer generation failed: {e}" | .ok lexSource => - writeOutput (dir ++ lexerModule ++ ".lean") lexSource s!"module {lexerModule}" + writeOutput (dir ++ lexerModule ++ ".lean") lexSource s!"module {qualify prefix_ lexerModule}" if wants .verified then - writeOutput (dir ++ verifiedModule ++ ".lean") verifiedSource s!"module {verifiedModule}" + writeOutput (dir ++ verifiedModule ++ ".lean") verifiedSource s!"module {qualify prefix_ verifiedModule}" if wants .parser then - writeOutput (dir ++ executableModule ++ ".lean") executableSource s!"module {executableModule}" + writeOutput (dir ++ executableModule ++ ".lean") executableSource s!"module {qualify prefix_ executableModule}" else if genLexer && wants .lexer then match Emit.generateLexerFrom surface lexerModule with | .error e => return ← fail s!"{ligPath}: lexer generation failed: {e}" | .ok lexSource => - writeOutput (dir ++ lexerModule ++ ".lean") lexSource s!"module {lexerModule}" + writeOutput (dir ++ lexerModule ++ ".lean") lexSource s!"module {qualify prefix_ lexerModule}" -- Rust. if wants .rust then if let some rp := rustPath then @@ -275,7 +276,7 @@ def generate (cfg : GenConfig) : IO UInt32 := do match Emit.generateRoundtripFrom surface lexerImport lexerModule rtModule with | .error e => return ← fail s!"{ligPath}: roundtrip generation failed: {e}" | .ok rtSource => - writeOutput (dir ++ rtModule ++ ".lean") rtSource s!"module {rtModule}" + writeOutput (dir ++ rtModule ++ ".lean") rtSource s!"module {qualify prefix_ rtModule}" -- The handwritten `Unparse` module defines `unparse`; a generated lexer -- is needed only for `%option roundtrip_format`. if surface.options.roundtripParser.isSome then @@ -285,7 +286,7 @@ def generate (cfg : GenConfig) : IO UInt32 := do executableImport executableModule unparseImport prtModule with | .error e => return ← fail s!"{ligPath}: parser roundtrip generation failed: {e}" | .ok prtSource => - writeOutput (dir ++ prtModule ++ ".lean") prtSource s!"module {prtModule}" + writeOutput (dir ++ prtModule ++ ".lean") prtSource s!"module {qualify prefix_ prtModule}" conflictExitCode ligPath prepared.tables /-- Print an inspectable view built from the same augmented grammar data emitted @@ -302,6 +303,15 @@ def printGrammarView (format : GrammarViewFormat) (ligPath : String) : IO UInt32 IO.println rendered conflictExitCode ligPath prepared.tables +/-- Print the parser states that can reject a token, as a Menhir `.messages`-style template + to fill with per-state messages for `errorMessage` (docs/ERROR_MESSAGES.md). -/ +def listErrors (ligPath : String) : IO UInt32 := do + match ← prepareFile ligPath with + | .error error => fail error + | .ok (surface, prepared) => + IO.println (Emit.renderErrorList surface prepared) + conflictExitCode ligPath prepared.tables + /-- Report which semantic actions the Rust backend could emit (docs/RUST_PARSER.md). The resolver imports the header's modules, so run this under `lake env` with those modules built. -/ @@ -319,6 +329,7 @@ def rustReport (verbose : Bool) (ligPath : String) : IO UInt32 := do private def usageText : String := "usage: leanparsergenerator [options] leanparsergenerator --print-grammar bnf|markdown + leanparsergenerator --list-errors leanparsergenerator --rust-report [-v] leanparsergenerator --help | --version @@ -335,6 +346,8 @@ options: --only write only this output; repeat to select several. is verified, parser, lexer, or rust. --print-grammar print the checked grammar as bnf or markdown; writes no files + --list-errors print the parser states that can reject a token, as a template + for per-state error messages; writes no files --rust-report [-v] report which actions the Rust backend can emit; writes no files -h, --help show this help --version show the version @@ -356,6 +369,7 @@ inductive Command where | version | generate (cfg : GenConfig) | printGrammar (format : GrammarViewFormat) (ligPath : String) + | listErrors (ligPath : String) | rustReport (verbose : Bool) (ligPath : String) /-- Split `--flag=value` into `(flag, some value)`. -/ @@ -374,6 +388,7 @@ private partial def parseArgs (args : List String) : Except String Command := do let mut positional : Array String := #[] let mut view : Option GrammarViewFormat := none let mut report : Option Bool := none + let mut errorList := false let mut verbose := false let mut help := false let mut version := false @@ -394,6 +409,7 @@ private partial def parseArgs (args : List String) : Except String Command := do | "--version" => version := true | "-v" | "--verbose" => verbose := true | "--rust-report" => report := some true + | "--list-errors" => errorList := true | "--out-dir" => cfg := { cfg with outDir := some (← value ()) } if consume then rest := rest.tail! @@ -424,6 +440,12 @@ private partial def parseArgs (args : List String) : Except String Command := do throw s!"expected one input file, got {positional.size}: {" ".intercalate positional.toList}" let some lig := positional[0]? | throw "missing input file" if verbose && report.isNone then throw "`-v` is only meaningful with `--rust-report`" + let inspections := [view.isSome, errorList, report.isSome].filter id + if inspections.length > 1 then + if view.isSome && report.isSome && !errorList then + throw "`--print-grammar` and `--rust-report` cannot be combined" + throw "only one of `--print-grammar`, `--list-errors` and `--rust-report` can be given" + if errorList then return .listErrors lig match view, report with | some _, some _ => throw "`--print-grammar` and `--rust-report` cannot be combined" | some f, none => return .printGrammar f lig @@ -437,6 +459,7 @@ def run (args : List String) : IO UInt32 := do | .ok .version => IO.println s!"leanparsergenerator {toolVersion} (Lean {Lean.versionString})"; return 0 | .ok (.generate cfg) => generate cfg | .ok (.printGrammar f lig) => printGrammarView f lig + | .ok (.listErrors lig) => listErrors lig | .ok (.rustReport v lig) => rustReport v lig def main (args : List String) : IO UInt32 := do diff --git a/README.md b/README.md index 66cab39..46d7b35 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeanParserGenerator: A Generator of Validated Parsers in Lean -`lean-parser-generator` turns an LR(1) grammar, written in a `.lig` file, into a Lean parser. The grammar carries ordinary Lean semantic actions, so parsing can produce whatever value is useful to the application: an abstract syntax tree, a policy, a command, or simply a number. +`lean-parser-generator` turns an LR(1) grammar, written in a `.lig` file, into a Lean parser. The grammar carries ordinary Lean semantic actions, so parsing can produce whatever value is useful to the application: an abstract syntax tree, a policy, a command, or a number. The generated parser is meant to be used as ordinary compiled Lean code. Alongside it, `lean-parser-generator` emits a dependent specification of the same grammar and a collection of certificates. Lean checks these certificates and proves that the parser agrees with the dependent specification. The LR(1) construction and the code generator are not trusted: if either produces a wrong table, Lean rejects the certificates. @@ -121,7 +121,7 @@ The generator infers the outputs from the input path and writes them next to the | `%option compress_tables` | none | Write the executable parser's tables in a compact form. The tables hold the same values at runtime and the proofs are unchanged, but the generated source is smaller and compiles faster. See [`docs/DESIGN.md`](docs/DESIGN.md) §10. | | `%option gen_rust ` | file path, relative to the `.lig` file | Also write the Rust parser to ``. Experimental. `--rust-out` overrides it. | | `%option roundtrip_lexer` | none | Also write `LexerRoundtrip.lean`. Experimental, see [`docs/ROUNDTRIP.md`](docs/ROUNDTRIP.md). | -| `%option parseStr` | none | With a `%lexer` block, also emit `parseStr : String → …` in `Parser`, which lexes and parses in one pass without building the token list, and stops at the first lex or syntax error. `Verified` relates it to `tokenize`, `parse` and `parser_sound`, proves that it returns `none` when `tokenize` fails, and, for a single-mode lexer, connects an accepted `parseStr` to a maximal-munch tokenization of the input (`parseStr_sound_tokenization`). For a single-mode lexer it also proves completeness and unambiguity from the string (`parseStr_complete_lexing`, `parseStr_unambiguous`, and the positioned forms `parseStr_*_lexes`, in which each token's span delimits its lexeme). None of these takes a hypothesis. See [`docs/DESIGN.md`](docs/DESIGN.md) §6.1, §13. Ignored without a `%lexer` block and by the Rust backend. | +| `%option parseStr` | none | With a `%lexer` block, also emit `parseStr : String → …` in `Parser`, which lexes and parses in one pass without building the token list, and stops at the first lex or syntax error. `Verified` relates it to `tokenize`, `parse` and `parser_sound`, and, when the `%eof` token carries no value, proves that it returns `none` when `tokenize` fails. For a lexer with one mode whose rules all stay, it proves completeness and unambiguity from the string (`parseStr_complete_lexing`, `parseStr_unambiguous`, and the positioned forms `parseStr_complete_lexes`, `parseStr_unambiguous_lexes`, in which each token's span delimits its lexeme) and `parseStr_node_spans`; if in addition the `%eof` token carries no value, it connects an accepted `parseStr` to a maximal-munch tokenization of the input (`parseStr_sound_tokenization`, `parseStr_sound_lexes`, `parseStr_sound_exact`). No theorem takes a hypothesis about spans or the lexer (no `hlex`, no `hspan`). See [`docs/DESIGN.md`](docs/DESIGN.md) §6.1, §13. Ignored without a `%lexer` block and by the Rust backend. | | `%option roundtrip_parser ` | Lean function name | Also write `ParserRoundtrip.lean`. Experimental. | | `%option roundtrip_format ` | Lean function name | Add `format`, `relex` and `fullRoundtrip` to the parser roundtrip module. Experimental. | @@ -130,6 +130,7 @@ The generator infers the outputs from the input path and writes them next to the ```text leanparsergenerator [options] leanparsergenerator --print-grammar bnf|markdown +leanparsergenerator --list-errors leanparsergenerator --rust-report [-v] leanparsergenerator --help | --version ``` @@ -141,6 +142,7 @@ leanparsergenerator --help | --version | `--rust-out ` | Also write the Rust parser to ``. Overrides `%option gen_rust`. Experimental. | | `--only ` | Write only this output: `verified`, `parser`, `lexer`, or `rust`. Repeat the flag to select several. Roundtrip modules are written only without `--only`. | | `--print-grammar bnf\|markdown` | Print the grammar that the proofs are about. Writes no files. See [`docs/GUARANTEES.md`](docs/GUARANTEES.md). | +| `--list-errors` | Print the parser states that can reject a token, as a template for per-state error messages. Writes no files. See [`docs/ERROR_MESSAGES.md`](docs/ERROR_MESSAGES.md). | | `--rust-report [-v]` | Report which semantic actions the Rust backend can emit. Writes no files. Experimental. | | `-h`, `--help`, `--version` | Show the usage text or the version. | @@ -231,16 +233,16 @@ lexer builds the same list; when it has no real positions it wraps each token wi `Runtime.Positioned.dummy` (the zero-width `Span.dummy`). An action can refer to the span of any bound symbol. For a binder `x=sym`, the -name `x_span : Runtime.Span` is in scope in the action body alongside `x`. So -`add := l=expr p=PLUS r=expr { … }` may use `p_span` for the operator's span or +name `x_span : Runtime.Span` is in scope in the action body alongside `x`. So in +`expr :: Ast | l=expr p=PLUS r=atom { … }` the action may use `p_span` for the operator's span or `l_span`/`r_span` for the operands'. A production's own span runs from the start of its first symbol to the end of its last; an empty right-hand side gets the empty span at the end of the last token before it (byte 0 at the start of the input), as in the Rust backend. The verified specification has the same spans: its parse trees have positioned tokens, its actions receive the spans of their right-hand side, and -the theorems hold for actions that read spans. An action that never mentions `_span` costs nothing—spans -ride in the parser value but the binder is only introduced where it is named, and -generated code does not warn about the ones you ignore. +the theorems hold for actions that read spans. The parser computes every node's span, but +an `x_span` binder is introduced only where the action names it, and generated code does +not warn about the spans an action ignores. `parse` returns the start value only and drops its span. Line and column are not stored; they are computed from the source at render time. The generated @@ -248,17 +250,18 @@ not stored; they are computed from the source at render time. The generated ```lean ExprParser.errorMessage tokens source --- some "43:30: unexpected PLUS; expected one of: NUM, LPAR (in parser state 12)" +-- on "1 + + 2": some "1:5: unexpected PLUS; expected one of: NUM (in parser state 4)" ``` Passing the `source` string renders `line:col`; without it the location is the token index. `diagnose`/`diagnoseSpanned` return the structured error if you want to build your own message. This diagnostic layer is unverified, but proved -consistent with the verified engine (`diagnose_run_agrees`); see -[`docs/ERROR_MESSAGES.md`](docs/ERROR_MESSAGES.md). The parser theorem itself is -unchanged: spans ride in the executable parser's value and are erased on the -dependent side, so the soundness, completeness, and error-freedom results in -[`docs/GUARANTEES.md`](docs/GUARANTEES.md) are exactly as before. +consistent with the executable parser `Runtime.Exec.run` (`diagnose_run_agrees`), which +each `*Verified` module relates to the dependent parser (`parserRunRefines`); see +[`docs/ERROR_MESSAGES.md`](docs/ERROR_MESSAGES.md). The soundness, completeness and +error-freedom theorems in [`docs/GUARANTEES.md`](docs/GUARANTEES.md) are stated on the +same positioned tokens, and the values in their parse trees are computed from the real +spans. ## Putting a generated parser in an existing project @@ -323,7 +326,7 @@ This is an alpha release, version 0.1.0-alpha.1. Before 1.0, a minor version may [`docs/USING_RUST_GENERATOR.md`](docs/USING_RUST_GENERATOR.md) explains the experimental Rust backend (`%option gen_rust`, `--rust-out`): what it generates, how to call it, and how it differs from the Lean lexer and parser. [`docs/RUST_PARSER.md`](docs/RUST_PARSER.md) has its design and the decisions behind it. -[`test/README.md`](test/README.md) lists the calculator, IMP, and Cedar fixtures, their generated modules, and the commands used to rebuild and test them. +[`test/README.md`](test/README.md) lists the test fixtures (calculator, IMP, Cedar policies, schemas and entities, C99, asm, spanuse and rustactions), their generated modules, and the commands used to rebuild and test them. To build this repository and its default regression suites: diff --git a/docs/DESIGN.md b/docs/DESIGN.md index d0a5c42..2e49985 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -38,7 +38,7 @@ The generic runtime proves: | Two parse trees for one word have equal semantics | `Complete` | `Runtime.unambiguity` | | Parser execution simulates the dependent interpreter at matching fuel | generated `ExecRefinement`, `Safe` | `Runtime.Refinement.run_refines`, generated `parse_eq_dependent` | | For a span grammar, the derived semantics of a tree is its span and value; the three theorems above hold over positioned trees | none / `Complete` | `Runtime.SpanGrammar.ptSem_toGrammar`, `SpanGrammar.parseCorrect`, `parseComplete`, `unambiguity` | -| Every node's span ends at its last token and starts at its first token (or at the end of the previous token, for an empty or leading-empty node) | none | `Runtime.SpanGrammar.allSpanFacts` | +| Every node's span ends at the end of its word (the end `pe` of the previous token for an empty word) and starts at `pe` or at its first token | none | `Runtime.SpanGrammar.allSpanFacts` | `Safe` and `Complete` are derived from executable Boolean validators: @@ -58,8 +58,10 @@ theorem completeness : Complete := `native_decide` discharges generated certificate and finite refinement-agreement checks. It trusts compiled Boolean evaluation; the parametric runtime theorems -themselves use no `sorry` and no custom axioms. `parser_complete` depends on -`Classical.choice`; the other exported theorems do not. +themselves use no `sorry` and no custom axioms. Of the six parser theorems, +`parser_complete` is the only one that depends on `Classical.choice`. The lexer's +`tokenize_sound` and `posLexerAgrees` and the `parseStr_*` theorems depend on it too +([`GUARANTEES.md`](GUARANTEES.md)). The validators establish that the emitted automaton satisfies the runtime properties. They do not prove that the untrusted frontend preserved the author's @@ -67,12 +69,16 @@ intended grammar; semantic correctness is relative to the emitted `Grammar`. ## 2. Trust boundary -**Trusted verified core** (`LeanParserGenerator/Runtime`, excluding `Exec.lean`): +**Trusted verified core** (`LeanParserGenerator/Runtime`, excluding `Exec.lean`, +`ExecFast.lean`, `ExecStream.lean` and `Diagnostic.lean`): - dependent grammar, parse-tree, automaton, and stream interfaces; - interpreter; - safety and completeness validators plus their linking theorems; -- soundness, operational safety, completeness, and unambiguity proofs. +- soundness, operational safety, completeness, and unambiguity proofs; +- the lexer specification that the string-level theorems are stated against: + `MatchStep` and `Tokenization` (`Lexer/Spec.lean`), `Lexing`, `PosLexing` and + `TokenLexeme` (`Lexer/Lexing.lean`), and `AllNodeText` (`Lexer/SpanText.lean`). **Untrusted implementation:** @@ -82,8 +88,10 @@ intended grammar; semantic correctness is relative to the emitted `Grammar`. - lexer DFA construction and table emission (the emitted tables are validated by `native_decide` and the scanner is proved sound, §9.7–9.8 — parallel to the parser: construction is untrusted, the checked tables are not; the `lexre` - frontend and the bytes-to-`Char` layer stay unverified); -- `Runtime/Exec.lean` and the executable backend. + frontend stays unverified; the byte tables are checked by `byteUnicodeValidated`, + and Lean's `String` decoding is trusted as part of the runtime); +- `Runtime/Exec.lean`, `Runtime/ExecFast.lean`, `Runtime/ExecStream.lean`, + `Lexer/StreamRun.lean`, `Runtime/Diagnostic.lean` and the executable backend. A malformed automaton certificate or refinement witness fails generated validation. `Runtime/Exec.lean` remains an implementation rather than part of the @@ -106,11 +114,13 @@ LeanParserGenerator/ │ ├─ Validator/Safe.lean │ ├─ Validator/Complete.lean │ ├─ Exec.lean # native non-dependent engine +│ ├─ ExecFast.lean # fused-reduce engine runFast, StackOps, FuseOK; runFast_eq_run │ ├─ ExecStream.lean # Source, goSrc/runSrc: the LR engine over a pull source = goFast │ ├─ ParseEnd.lean # parse consumes ≤ 1 token per step; no accept before `$` │ ├─ Span.lean # source spans on tokens/values, Span.fold, line:col rendering │ ├─ SpanGrammar.lean # span grammars: positioned trees, ptSpan/ptSem, derived Grammar │ ├─ Diagnostic.lean # Menhir-style syntax-error diagnostics (unverified) +│ ├─ GrammarView.lean # inspectable grammar view (§12) │ └─ Refinement.lean # generic native/dependent simulation, with spans ├─ IR/Grammar.lean ├─ Construct/ @@ -119,10 +129,19 @@ LeanParserGenerator/ │ ├─ LR1.lean # canonical LR(1) operations and Pager │ ├─ Tables.lean # Pager tables │ └─ Annotate.lean # validator certificate -├─ Frontend/File.lean # .lig parser -├─ Emit/Codegen.lean # parser backend -├─ Emit/CodegenVerified.lean # dependent specification backend -├─ Emit/CodegenLexer.lean # lexer backend +├─ Frontend/ +│ ├─ File.lean # hand-written .lig parser, prepareGrammar +│ ├─ Macros.lean # parameterized-rule macros (list, separated_list, …) +│ ├─ Diagnostics.lean # grammar checks shared by the CLI and the language server +│ ├─ LigLexer.lean, LigParse.lean, lig.lig, Generated/ # bootstrapped .lig parser (§15) +├─ Emit/ +│ ├─ Codegen.lean # parser backend +│ ├─ CodegenVerified.lean # dependent specification backend +│ ├─ CodegenLexer.lean # lexer backend +│ ├─ CodegenLexerRoundtrip.lean, CodegenParserRoundtrip.lean # roundtrip modules +│ ├─ CodegenRust.lean, Rust/ # Rust backend (experimental, no proofs) +│ └─ ErrorList.lean, Builder.lean, Quote.lean +├─ LSP/ # language server └─ Lexer/ ├─ Regex.lean # regex, CharClass, nullable/deriv, longestMatch ├─ Engine.lean # Tokenizer, Compiled tables, tokenize, tokenizeStr @@ -135,12 +154,14 @@ LeanParserGenerator/ ├─ FlatValidator.lean # a-posteriori flatValidate → the three agreements ├─ FlatTokenize.lean # tokenizeFlatStr = tokenize (the emitted runtime) ├─ FastAct.lean # FastActs action table, lexemeAt, tokenizeFlatStrPosF = tokenizeFlatStrPos + ├─ ByteScan.lean, ByteValidator.lean, ByteTokenize.lean # byte scanner, lexPos, tokenizeByte ├─ BytePull.lean # pullAux/pullAuxF byte pull step, pullSource, PosLexerAgrees ├─ ByteUnicode.lean # byteUnicodeValid → byte agreements for every Char ├─ ByteAgree.lean # byteScan = flatScanStr, lexPosAux = tokenizeFlatStrPosAux ├─ LexerSound.lean # tokenizeFlatStrPos_sound, pullSource_fails_tokens ├─ Lexing.lean # Lexing/PosLexing: completeness and uniqueness of tokenization ├─ SpanText.lean # AllNodeText: node spans of a tree over a PosLexing as text of s + ├─ Roundtrip.lean # lexer roundtrip theorem (docs/ROUNDTRIP.md) └─ StreamRun.lean # goStream/runStream (specialized stream engine) = goSrc, runStreamFast ``` @@ -206,7 +227,7 @@ List (Σ state : NonInitState, semT (lastSymb state)) The dependent stack's element type depends on a runtime state through `semT : Symbol → Type`. Lean therefore cannot compile the generic verified interpreter after type erasure. Generated dependent specification parsers run by kernel -reduction (`decide`), while their Boolean certificates use `native_decide`. +reduction (`decide +kernel`, §4.4), while their Boolean certificates use `native_decide`. ### 4.4 Span grammars @@ -297,7 +318,7 @@ automaton, is unchanged. Permanent tests cover: - an LR(1)-not-LALR grammar requiring split same-core states; -- a genuinely ambiguous grammar that must still report a conflict; +- an ambiguous grammar that must still report a conflict; - the no-incoming-edge invariant for state 0; - generated safety/completeness validation and parser behavior. @@ -331,8 +352,9 @@ are stated on the positioned tokens the executable parser reads: - `parse_eq_dependent input k : E.parse input k = parse input k` for every `input : List (Positioned Tok)`; -- `parser_sound`: an accepted input starts with the word of a tree whose value at byte 0, - `SpanGrammar.ptSem ⟨0⟩ tree`, is the result; +- `parser_sound`: the EOF-padded stream of an accepted input (`toStream input`) starts + with the word of a tree whose value at byte 0, `SpanGrammar.ptSem ⟨0⟩ tree`, is the + result; - `parser_complete`: a tree over `word` within the fuel is accepted with that value; - `parser_unambiguous tree₁ tree₂ pe`: two trees over the same word have the same span and value at every `pe`; @@ -349,9 +371,10 @@ spans or the lexer: - `parseStr_eq s k ts (h : L.tokenize s = .ok ts) : E.parseStr s k = E.parse ts k`; - `parseStr_eq_dependent … : E.parseStr s k = parse ts k`, the dependent parser on the positioned tokens; -- `parseStr_sound …`: an accepted `parseStr` has a parse tree, through `parser_sound`; -- `parseStr_of_tokenize_error … (h : L.tokenize s = .error e)`: the pull source delivers a - prefix `ts` and fails, and `parseStr` is `none` or `parse` of an extension of `ts`; +- `parseStr_sound …`: an accepted `parseStr` has a parse tree, through `parser_sound`. + +With a `%eof` token that carries no value, also: + - `parseStr_eq_none_of_tokenize_error s k e (h : L.tokenize s = .error e) : E.parseStr s k = none`, and `parseStr_eq_none_of_lexPos` for a failing `lexPos`; - `runStream_ne_ok_of_tokenize_error s k e h : ∀ v, E.runStream s k ≠ .ok v`. The result @@ -363,9 +386,10 @@ spans or the lexer: For a lexer with one mode whose rules all `stay`: -- `parseStr_sound_tokenization` adds `Lexer.Tokenization L.rules0 s.toList` and - `Lexer.tokenize L.lexer s = .ok (ts.map (·.val))`, and `tokenize_parse_sound s k ts p h - accepted` is the same for `L.tokenize s = .ok ts` followed by `E.parse ts k = some p`; +- `parseStr_sound_tokenization` (also needs the valueless `%eof` token) adds + `Lexer.Tokenization L.rules0 s.toList` and `Lexer.tokenize L.lexer s = .ok (ts.map (·.val))` + to `parseStr_sound_tokenize`, and `tokenize_parse_sound s k ts p h accepted` is the same + for `L.tokenize s = .ok ts` followed by `E.parse ts k = some p`; - completeness and unambiguity at the string level, value level (the tokenization is a `Lexer.Lexing` with its steps, §9.8): `parseStr_complete s k ts h tree fuel` (`E.parseStr s k = some (ptSem ⟨0⟩ tree)` for a tree over the tokens of `tokenize s`), @@ -380,9 +404,9 @@ For a lexer with one mode whose rules all `stay`: unique; - the same over positioned tokens, where `L.Lexes s ts` is the positioned tokenization of `s` (`Lexer.PosLexing`, §9.8: each token's span delimits its lexeme and skip rules - consume the bytes between tokens): `parseStr_sound_lexes` (an accepted `s` has - `L.Lexes s ts` and a tree over a prefix of `ts` with the result as value), - `parseStr_complete_lexes`, `parseStr_unambiguous_lexes` (two derivations of `s`, each a + consume the bytes between tokens): `parseStr_sound_lexes` (with a valueless `%eof` + token: an accepted `s` has `L.Lexes s ts` and a tree over a prefix of `ts` with the result + as value), `parseStr_complete_lexes`, `parseStr_unambiguous_lexes` (two derivations of `s`, each a positioned tokenization and a tree over it, have the same tokens, and their trees the same span and value), and `parseStr_node_spans s ts h tree` (`Lexer.AllNodeText (Lexer.modeAct L.lexer L.lexer.start) L.lexer.eofToken s ⟨0⟩ tree`, @@ -390,10 +414,11 @@ For a lexer with one mode whose rules all `stay`: rule's action emits its token from the lexeme `s.extract a b`, or it is the end-of-input token at the end of `s` (`Lexer.TokenLexeme`); every inner node's span is `[a, b)` for positions `a ≤ b` of `s` (`Lexer.SpanIn`) that satisfy `SpanFacts`: `b` is the end of the - lexeme of its last token, and `a` is the start of the lexeme of its first token or, when - its word is empty or its leftmost children derive the empty word, the end of the token - before it); -- the tree covers the tokens: `word_eq_of_lexes s ts h tree rest hs` (if `L.Lexes s ts` and + node's word, or the end `pe` of the token before the node when the word is empty, and `a` + is `pe` or the start of the lexeme of the first token of the word. `SpanFacts` does not + state which of the two `a` is; the parser takes `pe` when the word is empty or the + leftmost children derive the empty word); +- with a valueless `%eof` token, the tree covers the tokens: `word_eq_of_lexes s ts h tree rest hs` (if `L.Lexes s ts` and `toStream ts = appList word rest` for a start tree over `word`, then `word = ts`) and `parseStr_sound_exact s k p accepted` (an accepted `s` has `L.tokenize s = .ok ts`, `L.Lexes s ts` and a tree over exactly `ts` with value `p`). They use the lexer module's @@ -409,13 +434,16 @@ For a lexer with one mode whose rules all `stay`: The other soundness theorems (`parser_sound`, `parseStr_sound`, `parseStr_sound_tokenize`, `parseStr_sound_tokenization`, `tokenize_parse_sound`, `parseStr_sound_lexes`) give a tree -over a prefix of the EOF-padded token stream (`toStream ts = appList word rest`). They -hold at the token level, for any token list, without the lexer facts above. +over a prefix of the EOF-padded token stream (`toStream ts = appList word rest`). +`parser_sound` holds for any token list, without the lexer facts above; `parseStr_sound`, +`parseStr_sound_tokenize`, `parseStr_sound_tokenization`, `parseStr_sound_lexes` and +`tokenize_parse_sound` state the same prefix form for the tokens that `tokenize s` returns. -The lex-failure theorems use `startProds_end` (every production of `S'` has `$` on its +The theorems that need a valueless `%eof` token use `startProds_end` (every production of `S'` has `$` on its right-hand side, by `native_decide`), `tokenTerm_eq_end` (only the `%eof` token has terminal `$`, by a case split on the token type) and the lexer module's `L.noEofEmit`. -They are emitted when the `%eof` token carries no value. +They are emitted when the `%eof` token carries no value. The completeness, unambiguity +and node-span theorems need only the one-mode, `stay` condition. Here `L` is the lexer namespace and `E` the parser namespace. `#print axioms` on these theorems shows the standard axioms and per-grammar `native_decide` axioms only. @@ -439,8 +467,8 @@ The executable output contains: The fused reduces `fuse

` compute the same span inline from the cell offsets; for an empty right-hand side they read the top state and the end of the top cell with one match (`Stk.withTop`, with `Stk.withTop_eq`). An action that never mentions `x_span` - pays nothing — generated `semV`/`fuse

` set `linter.unusedVariables false` so an - ignored span binder is not a warning; + binds no span variable, and generated `semV`/`fuse

` set + `linter.unusedVariables false` so that an ignored span is not a warning; - flat Pager action/goto arrays; - `run : List (Runtime.Positioned Tok) → Runtime.Exec.Result VP` and `parse : List (Runtime.Positioned Tok) → Option StartTy`, which drops the span; @@ -448,7 +476,7 @@ The executable output contains: (logNSteps := 20) : Runtime.Exec.Result VP` and `parseStr (input : String) (logNSteps := 20) : Option StartTy`, which pull tokens from the byte lexer as the parser needs them (`Lexer.runStreamFast` instantiated with `flat`, `fuse`, `termOf`, - `L.cbyte` and `L.fastActs`), and five theorems with no hypothesis: + `L.cbyte` and `L.fastActs`), and five theorems with no lexer or span hypothesis: `runStream_eq_runSrc` (the specialized loop equals `runSrc` over `pullSource (pullAux L.cbyte input.toUTF8)`), `runStream_eq_lexPos` and `parseStr_eq_lexPos` (if `Lexer.lexPos L.cbyte input = .ok ts`, the stream entry @@ -459,7 +487,7 @@ The executable output contains: extension of the prefix). Each proof unfolds the entry points and applies one library lemma with `L.fastActs_agree_byte`; - Menhir-style diagnostics wrappers `terminalName`/`diagnose`/`diagnoseSpanned`/ - `errorMessage` (§ error messages), where `diagnoseSpanned` recovers the + `errorMessage` ([`ERROR_MESSAGES.md`](ERROR_MESSAGES.md)), where `diagnoseSpanned` recovers the offending token's span from `VP` for `line:col` rendering. Both modules are generated from identical augmented grammar, state graph, and @@ -642,8 +670,8 @@ lexers are written source files, not spliced definitions. `Compiled.ofTokenizer` cross-check reference used by `test/cedar/CedarBench.lean`, not as a generation path. -A verified bytes-to-tokens layer is later work and can remain independent of the -parser refinement. +The byte-level lexer was later proved equal to `tokenize` (`PosLexerAgrees`, §9.6.3, +§13), independently of the parser refinement. ### 9.1 Starting point and its cost @@ -734,7 +762,8 @@ unprovable. §9.7 has since been carried out (steps 0, 2–5; §9.8): the emitted lexer tables are validated by `native_decide` and the scanner's maximal-munch soundness is proved, so the lexer's DFA scan is on the verified path. The token→character *frontend* -(the `lexre` → `Regex` translation) and the bytes-to-`Char` layer remain unverified +(the `lexre` → `Regex` translation) remains unverified; the byte tables are checked by +`byteUnicodeValidated`, and Lean's `String` decoding is trusted as part of the runtime — see the §2 trust boundary and §9.7's "out of scope". ### 9.4 Properties to establish @@ -772,7 +801,7 @@ The target properties, in the order §9.7 builds them: token. A correct rendering emits canonical surface text for each token constructor (for example, the keyword spelling for `.IF`, a canonical decimal for `.NUMBER n`, a re-quoted-and-escaped form for `.STRINGLIT`), and skipped - tokens are simply absent from `T₁`. Stating and proving this cleanly is a reason + tokens are absent from `T₁`. Stating and proving this is a reason to keep token payloads carrying enough information to reprint, or to accept the documented lossy cases explicitly. @@ -786,7 +815,8 @@ in `FooLexer.lean`, removing the interpreter tokenizer; (4) verify per §9.7 (cl the blockers, define the `Tokenization` derivation, validator conditions, generic theorem, per-lexer `native_decide`), then the `String.Pos` runtime and the flat `state × class` scanner, each carried across a-posteriori without re-proving -soundness. The round-trip rendering (§9.4) is independent and not yet done. +soundness. The round-trip rendering (§9.4) was done later as the experimental +`%option roundtrip_lexer` (§16.4, [`ROUNDTRIP.md`](ROUNDTRIP.md)). ### 9.6 Measurements @@ -897,7 +927,7 @@ path on the 28-file corpus and all ran *slower* (0.95x, 0.88x, 0.47x). Removing intermediate `List Tok` recovers nothing here: the list is cheap (§9.6 put list building at ~0), and each fused loop re-boxes a lookahead per parser step. The `Array` stack was 2x slower because through `Id.run do`/`let mut` the array reference is not -provably unique, so `push`/`shrink` copy on nearly every step; a genuinely in-place +provably unique, so `push`/`shrink` copy on nearly every step; an in-place stack needs linearity (`ST` with a unique ref), not pursued once fusion showed no benefit. Fusion is not made the primary spec anyway — if ever wanted it can be a library-level equivalence `runFused = runFast (tokenize |>.map decode)`, keeping the @@ -959,7 +989,7 @@ state reaches that class's target uniformly over all continuations; it does not `Utf8Ranges.compile` correct, it checks its output. `agreements_of_byteUnicodeValid` derives all four agreements from it, and `Lexer/ByteAgree.lean` extends the scan simulation to the end positions, to scans from any position, and to the tokenizer loop -(§13, "The two hypotheses"). On Cedar the check takes 70 ms of `native_decide` +(§13, "No hypotheses"). On Cedar the check takes 70 ms of `native_decide` interpretation. The runtime `String.toUTF8` input is bridged to the `encodeChars` list model by `toUTF8_size_eq`/`toUTF8_getElem_eq` (via `String.utf8Encode_toList`), the one place `String`/`ByteArray` internals appear. @@ -1188,8 +1218,8 @@ it is proved in the library, not per lexer. **Step 5 — validate the emitted tables, not a rebuild.** Run the validator on the tables that actually run, discharged per lexer by `native_decide`, exactly as -`CalcVerified.lean:457` does for `safeValidator`. This subsumes -`test/LexerEmitAgreementTest.lean`: once the emitted tables are validated directly, +`CalcVerified.lean` does for `safeValidator` (`safetyValidation`). This subsumes +the former `test/LexerEmitAgreementTest.lean`: once the emitted tables are validated directly, comparing them against `Compiled.ofTokenizer` is redundant, and `Compiled.ofTokenizer` becomes purely untrusted scaffolding for the emitter. The `lexer` command then emits the tables, the certificate, the validation theorem, and @@ -1209,10 +1239,10 @@ points remains unverified, as for the `String.Pos` runtime generally. Steps 0 and 2–5 are done and build; step 1 (the flat-table throughput optimization) is now also done and is the emitted runtime (see the Step 1 bullet below). The verified tokenizer is -validated end-to-end for the generated lexers (calculator, Cedar, CedarSchema, -and CedarEntities — their generated modules emit `validated⟨m⟩`/`scanSound⟨m⟩` and +validated end-to-end for every generated lexer (test/README.md lists them; their +generated modules emit `validated⟨m⟩`/`scanSound⟨m⟩` and `flatValidated⟨m⟩`, discharged by `native_decide`), with no `sorry` and the same -axiom budget as the parser (`propext`, `Classical.choice`, `Quot.sound`, and one +axiom budget as `parser_complete` (`propext`, `Classical.choice`, `Quot.sound`, and one `native_decide` axiom per emitted Boolean). The scanner's maximal-munch soundness is stated against the specification object `MatchStep` (`scan_matchStep` and its converse `scan_of_matchStep`), and holds for `DFA.scan` — the scanner the emitted lexers @@ -1223,7 +1253,8 @@ code points — so no code-point budget gate is needed. - **Step 0.** `CharClass` is now the ranges-only structure `⟨neg, rs⟩` with `DecidableEq` (`Lexer/Regex.lean`); the opaque predicate and `opaqueWindow` are - gone, `Regex.asciiWhitespace` replaces `Char.isWhitespace` in the Cedar fixtures. + gone, `Regex.asciiWhitespace` was added to replace `Char.isWhitespace` in the Cedar fixtures + of that time; no current fixture uses it. `DFA.build?` returns `Option DFA`, `none` when the worklist did not empty (`Lexer/DFA.lean`). `DFA.repOf` documents that the theorem quantifies over valid scalar values, so the surrogate gap is never a match position. @@ -1265,11 +1296,11 @@ code points — so no code-point budget gate is needed. `⟨name⟩.rules⟨m⟩`, `⟨name⟩.dfa⟨m⟩`, `⟨name⟩.cert⟨m⟩` as data, `⟨name⟩.validated⟨m⟩ : Lexer.validate … = true := by native_decide`, and `⟨name⟩.scanSound⟨m⟩`. Because `V2`/`V4` are interval-based (§9.3), there is no - code-point budget gate: the calculator, Cedar, and CedarSchema lexers all emit - and discharge the validation and soundness theorems, with the same axiom budget - as the parser (`propext`, `Classical.choice`, `Quot.sound`, and one per-lexer + code-point budget gate: every generated lexer (test/README.md lists them) emits + and discharges the validation and soundness theorems, with the same axiom budget + as `parser_complete` (`propext`, `Classical.choice`, `Quot.sound`, and one per-lexer `native_decide` axiom). This subsumes the intent of - `test/LexerEmitAgreementTest.lean` for the lexers that validate directly. + the former `test/LexerEmitAgreementTest.lean` for the lexers that validate directly. - **Step 1** (flat-table optimization) is done and is the emitted runtime. The derivative-vector `DFA.scan`/`tokenizeAuxDFA` remain the specification; the fast `FlatDFA` scanner is a verified-equal running object. `Lexer/FlatValidator.lean`'s @@ -1280,7 +1311,7 @@ code points — so no code-point budget gate is needed. prove the emitted `FooLexer.tokenize := Lexer.tokenizeFlatStr FooLexer.cflat` equals the spec `tokenize`, so `tokenize_sound` transfers unchanged. Axioms are the same budget (`propext`/`Classical.choice`/`Quot.sound` + one per-lexer `native_decide` - axiom). The generated lexers (calc, Cedar, CedarSchema, CedarEntities) emit `cflat`, + axiom). Every generated lexer (test/README.md lists them) emits `cflat`, `flatValidated⟨m⟩`, and the flat `tokenize`, and compile. Measured ~2.2x lex-only on Cedar (145.7 → 66.8 us/policy), tokens identical (§9.6). The `List Char` removal (`Lexer/StringScan.lean`, `tokenizeStr_eq_tokenize`) is the `String.Pos` cursor the flat scanner builds on. @@ -1385,10 +1416,10 @@ lake build # library, CLI, verified smoke regressions (no heavy lake build parsers # regenerate both backends for every non-heavy fixture lake build heavyParsers # regenerate the heavy fixtures (c99) lake build Generated # compile executable calc/IMP/Cedar/... modules -lake build VerifiedSmoke # compile verified calc smoke and agreement tests (default) +lake build VerifiedSmoke # verified calc, asm and spanuse modules and calc agreement tests (default) lake build VerifiedMid # compile + cache the non-heavy *Verified proof modules lake build VerifiedHeavy # compile + cache the heavy *Verified module (c99) -lake build ParserTests # calc/imp end-to-end, span, error-message, and x_span tests +lake build ParserTests # calc/imp/cedar end-to-end, span, error-message, error-list and x_span tests ``` Lake 5.0.0 has no `-j` flag; bound build parallelism with the `LAKE_NUM_JOBS` @@ -1397,24 +1428,28 @@ for the heavy fixtures: build `VerifiedHeavy` alone (see below). The paired `*Verified` proof modules are split across two non-default `lean_lib`s so plain `lake build` never pays their cost: `VerifiedMid` roots the -ones that fit comfortably in memory (calc, imp, cedar, cedarschema, cedarentities), +ones that fit comfortably in memory (calc, imp, cedar, cedarschema, cedarentities, +rustactions; asm and spanuse are in `VerifiedSmoke`), and `VerifiedHeavy` roots the heavy one (c99), reached only through the separate `heavyParsers` regeneration target. Building either caches each module's `native_decide` certificates to `.olean`, so an unchanged rebuild is a Lake trace no-op (~0.9 s for Cedar) instead of the full re-check that `lake env lean test//Verified.lean` pays every time (~20 s for Cedar). -Neither is a default target — plain `lake build` (which builds `VerifiedSmoke` -only) must not pay the Cedar/c99 proof cost. Measured cold vs cached: Cedar +Neither is a default target — plain `lake build` (whose only verified library is +`VerifiedSmoke`) must not pay the Cedar/c99 proof cost. Measured cold vs cached: Cedar ~20 s → 0.9 s. -`c99` is split out for memory, not just time. `c99.C99Verified` checks -cold in ~30 s on 32 cores (~18 min before the changes in the next subsection). Its peak memory has not been re-measured. Build the heavy fixture +`c99` was split out for memory, not just time. `c99.C99Verified` checks +cold in ~30 s on 32 cores (~18 min before the changes in the next subsection). Its peak +RSS is 1.8 GB with one Lake job (end of this section). Build the heavy fixture one worker at a time on a host with enough RAM (or swap): `LAKE_NUM_JOBS=1 lake build VerifiedHeavy`, or one module at a time. The end-to-end functional tests are rooted in the `ParserTests` `lean_lib` -(`lake build ParserTests`): `calc`/`imp` acceptance, `test/calc/PositionTest.lean` -(span folding), `test/calc/ErrorMessageTest.lean` (diagnostics and `line:col`), and +(`lake build ParserTests`): `calc`/`imp` acceptance, `test/cedar/ParserTestCedar.lean` +(Cedar lexer and parser), `test/calc/PositionTest.lean` (span folding), +`test/calc/ErrorMessageTest.lean` (diagnostics and `line:col`), +`test/calc/ErrorListTest.lean` (the error-state enumerator), and `test/spanuse/` (an action reading `x_span`, and a sibling rule ignoring spans that compiles without a linter warning). @@ -1484,8 +1519,9 @@ The lexer rows add `fastActs`, `fastActs_agree` and `tokenize_eq_flat`; the pars verified rows add the stream entry points and their theorems. The differences are within the noise of the host. -The `semS`/`semV` split of `sem` and the span-independence theorems (§13) add a second -match over the productions to each parser module. Same measurement, after → with the +Before #20, the `semS`/`semV` split of `sem` and the span-independence theorems added a +second match over the productions to each parser module (#20 removed both; the parser +modules now have one `semV` match). Same measurement at the time, after → with the split: `CalcParser` 1.49 → 1.55 s, `CalcVerified` 2.04 → 2.04 s, `CedarParser` 13.52 → 14.4–14.7 s, `CedarVerified` 16.66 → 17.25 s, `CedarEntitiesParser` 3.78 → 4.01 s, `CedarEntitiesVerified` 4.13 → 4.23 s, `AsmParser` 6.83 → 7.2–7.3 s, `AsmVerified` @@ -1507,7 +1543,7 @@ Cedar, 29 ms for CedarEntities and 8 ms for calc. The new library modules Spans in the specification (§4.4) and the string-level completeness and unambiguity theorems (§6.1) change every verified module: a span grammar instance, actions over span lists, the span refinement, and seven `parseStr_*` theorems. Cold time as reported by -Lake under `taskset -c 0-7`, at `89a1931` → after: `CalcVerified` 1.3 → 1.4 s, +Lake under `taskset -c 0-7`, before #20 → after: `CalcVerified` 1.3 → 1.4 s, `AsmVerified` 8.1 → 7.8 s, `CedarVerified` 17 → 17 s, `CedarEntitiesVerified` 3.7 → 3.6 s; `SpanUseVerified` (did not compile before) 0.96 s; `C99Verified` 28 s, peak RSS 1.8 GB with one Lake job. @@ -1535,8 +1571,8 @@ The generic proof: Executable finite lists and dependent `NatStream`s both pad exhausted input with the generated EOF token. Every paired specification module exports -`parserRunRefines` and `parse_eq_dependent`; calculator, IMP, and -Cedar compile these generated proofs. The existing `parseCorrect`, +`parserRunRefines` and `parse_eq_dependent`; every fixture's specification module +compiles these generated proofs. The existing `parseCorrect`, `parseComplete`, `parse_err_free`, and `unambiguity` theorems remain unchanged and transfer through this equality. @@ -1592,8 +1628,8 @@ Paired specification modules export direct `parser_sound`, `parser_err_free` / `parser_ne_err`, `parser_complete`, and `parser_unambiguous` corollaries, so callers do not assemble refinement or validator witnesses. Existing-repository and automatic Lake generation workflows are documented in -[`INTEGRATION.md`](INTEGRATION.md). Later independent work includes a verified -lexer and `.lig` language-server diagnostics. +[`INTEGRATION.md`](INTEGRATION.md). The verified lexer (§9.7–9.8, §13) and `.lig` +language-server diagnostics ([`LANGUAGE_SERVER.md`](LANGUAGE_SERVER.md)) were added later. ## 13. Executable parser throughput: the inline and fused-reduce engines @@ -1645,9 +1681,9 @@ Because `table` is definitionally the same closures as before, every generated (`Emit/CodegenVerified.lean`) bridges `parserRunRefines` with one line — `simp only [run, table, runInline_eq_run]` rewrites the emitted `run` to `Exec.run table` — so `parse_eq_dependent` and the `parser_sound`/`parser_complete`/ -`parser_err_free`/`parser_unambiguous` corollaries transfer with the **same axiom -budget** (`propext`, `Quot.sound`, and the per-grammar `native_decide` safety and -refinement axioms; no new axioms, no `sorry`). +`parser_err_free`/`parser_unambiguous` corollaries transfer with the same axioms as +before (no new axioms, no `sorry`); [`GUARANTEES.md`](GUARANTEES.md) lists the axioms of +each theorem. Measured on Cedar: a direct A/B on the same tables (`Exec.run CedarParser.table` vs `Exec.runInline CedarParser.flat`, `cedar-spec/cedar-benchmarking/corpus`, @@ -1912,8 +1948,8 @@ spans to a run with dummy spans. were vacuous. `SpanIndependent`, `SemSpanFree`, `run_erase`, `runFast_ok_dummy`, `parse_eq_dependent_spans` and the `semS`/`semV` split were removed. -**Lex failure.** If the lexer fails, `parseStr` is `none` -(`parseStr_eq_none_of_tokenize_error`). `parseStr_total` gives, in that case, a prefix `ts` +**Lex failure.** If the lexer fails and the `%eof` token carries no value, `parseStr` is +`none` (`parseStr_eq_none_of_tokenize_error`). `parseStr_total` gives, in that case, a prefix `ts` that the pull lexer delivered before the error and, for every continuation `tail`, `parseStr = none` or `parseStr = E.parse (ts ++ tail) k`. Take `tail` to be `2^k + 1` copies of the first token. No token of `ts` is the `%eof` token @@ -1975,7 +2011,7 @@ have written. The refinement connects to the executable table only through `table.action s t = f.actionData.getD (st*w+t) .error`; since `actionData` has the identical value, `refinementLookaheadCheck` and the other `native_decide` agreement checks see identical values and stay true, and the runtime `Runtime/Exec.lean` `FlatTable` is -untouched. A genuinely sparse *table* — a lookup with an `.error` default evaluated per +untouched. A sparse *table* — a lookup with an `.error` default evaluated per `native_decide` entry — would instead trade the executable-side win for a verified-side cost (a binary search run ~57 000 times inside `native_decide`); compressing only the source literal avoids that tension. @@ -2029,15 +2065,15 @@ The design must support automatic regeneration and build. Two mechanisms already this repository are the template for it: - **Regenerate-on-stale.** The `parsers` Lake target (see the lakefile) fetches the - generator executable, compares mtimes of each `.lig`, the generator, and the two - committed outputs, and regenerates only stale pairs before the library compiles. + generator executable, compares mtimes of each `.lig`, the generator, and the + committed outputs, and regenerates only stale fixtures before the library compiles. A downstream package copies this target, pointing it at its own grammars. Committing the generated modules keeps them reviewable and makes a plain `lake build` enough on a clean checkout; a from-scratch checkout regenerates once before the first build. - **Cache the proofs; do not re-check them.** The dependent-specification modules (`*Verified`) carry the expensive `native_decide` certificates — ~20 s for Cedar, - minutes and multiple GB for the largest grammars. Re-running `lake env lean` on them every time is the + ~30 s and 1.8 GB for C99 (§10). Re-running `lake env lean` on them every time is the wrong workflow. Instead they are rooted in a non-default `lean_lib` (`VerifiedMid`/`VerifiedHeavy` here) so Lake caches each certificate to `.olean` and an unchanged rebuild is a @@ -2048,7 +2084,7 @@ this repository are the template for it: `lake build` away. This split — executable parser on the default path, proof modules in an opt-in cached library — is the intended integration shape. -A published version therefore ships (a) the generator as a Lake exe dependency, +A published version therefore consists of (a) the generator as a Lake exe dependency, (b) the runtime as a Lake lib dependency, and (c) a documented pair of Lake targets (regenerate-on-stale + a cached verified library) that a consumer instantiates for its own grammars. [`docs/INTEGRATION.md`](./INTEGRATION.md) carries the concrete setup. @@ -2056,14 +2092,16 @@ own grammars. [`docs/INTEGRATION.md`](./INTEGRATION.md) carries the concrete set ## 15. The bootstrapped `.lig` frontend -The `.lig` frontend is split in two. The structure of a `.lig` file — the sequence of +The generator and the LSP parse `.lig` files with the hand-written `parseLig`. A second +frontend, `parseLigGen`, is split in two. The structure of a `.lig` file — the sequence of `%`-directives, the rules, and the alternative/element shape of each rule — is parsed by -a parser LPG generates from a `.lig` grammar of its own. The embedded-Lean leaves — +a parser LPG generates from a `.lig` grammar of its own, `lig.lig`. The embedded-Lean leaves — `%header`, `%lexerheader`, `%lexer`, the `{ … }` action bodies, the rest-of-line `:: Type`, and the optional `!!rust{ … }` Rust counterparts of an action or a type — are read by a hand-written lexer. The leaves are brace-balanced Lean, not a regular language, so a DFA cannot tokenize them; everything else is context-free and -LR(1), so it does not need to be hand-written. +LR(1), so it does not need to be hand-written. `lig-bootstrap-test` checks that +`parseLig` and `parseLigGen` agree on the repository's `.lig` files (see below). The pieces: @@ -2095,9 +2133,8 @@ that shows up is `verifiedGrammarView` (§12), which the author has to read. A d grammar plus a focused lexer moves that structure out of control flow and into 59 lines that state it directly. The second reason is that a generated parser comes with the same proofs every generated parser gets — `LigVerified` proves `parser_sound`, -`parser_complete`, and `parser_unambiguous` for the `.lig` grammar, with the usual axiom -set (`propext`, `Classical.choice`, `Quot.sound`, and the safety/completeness/refinement -`native_decide` certs; no new axioms, no `sorry`). +`parser_complete`, and `parser_unambiguous` for the `.lig` grammar, with the axioms +[`GUARANTEES.md`](GUARANTEES.md) lists for each theorem (no new axioms, no `sorry`). That proof is a bonus, not the reason, and I want to be exact about what it does and does not say. It is not a soundness claim about LPG. We do not make one, and the a-posteriori @@ -2105,7 +2142,8 @@ architecture already makes a frontend bug unable to produce an unsound *user* pa frontend bug can only produce a parser for a different grammar than intended, never one that disagrees with its own emitted grammar. What the proof buys is an internal consistency check: `LigParser` matches the `.lig` grammar written in `lig.lig`, and -`parser_unambiguous` shows that grammar is unambiguous. +`parser_unambiguous` shows that two parse trees of one `.lig` token word have the same +value. The scope is the structure only. `%header`, `%lexerheader`, `%lexer`, and the `{ … }` action bodies stay behind the `LigLexer` balanced-brace escape hatch, outside the @@ -2156,7 +2194,7 @@ retired in favor of `parseLigGen`, spans have to be threaded through `LigLexer` `lig.lig` first, or the LSP loses precise error locations. -## 16. Other Features Planned +## 16. Other features ### 16.1 Code generation The emitters build the generated module as `Lean.Syntax` via quotation and pretty-print it, rather @@ -2223,7 +2261,7 @@ instance `{ field := … }` rendered by `ppCommand` daggers its field names (`in has nothing (only `Nat`s and `reprStr` strings) that string emission gets wrong — so `Syntax` there is net-negative. -This is verified end to end: all fixtures plus `lig.lig` regenerate through both backends with +This was checked on every fixture: all fixtures plus `lig.lig` regenerate through both backends with zero `✝` daggers, `lake build` is green, and the verified proof modules (calc, imp, cedarschema via the paired build, and cedar checked directly) discharge their `native_decide` certificates against the regenerated output. Nothing here moves the trust boundary: emission is @@ -2231,10 +2269,11 @@ untrusted, and the a-posteriori validator re-checks the output however it was pr ### 16.2 Module system -The library and the generated code use Lean 4.35's module system (`module` header, +The library and the generated code use Lean's module system (`module` header, `public`/`meta`/`import all` imports, `@[expose] public section`). Every `.lean` file -in the package is a `module`; a `module` file may only import other modules, so the -whole graph — the 48 library files, `Main`, the LSP server, the generated +in the package is a `module` except the executable roots `LeanParserGenerator/LSP/Main.lean` +and `test/cli/CliTest.lean`; a `module` file may only import other modules, so the +whole graph — the library files, `Main`, the LSP server, the generated parser/lexer/verified/roundtrip modules, and the hand-written test support — is ported together. The port follows the reference recipe (`module` first; `public import`; `@[expose] public section` for reasoned-about code, `public section` for programs) and @@ -2294,8 +2333,10 @@ their own per-`native_decide` axioms, with no `sorry` and no new custom axioms. ### 16.3 Nice Error Handling -We should work on providing nice error messages for when the lexer or parser fails. For the parser, -let us take inspiration from how Menhir handles error messages. See [ERROR_MESSAGES](./ERROR_MESSAGES.md). +Syntax-error messages follow Menhir's model: the parser reports the LR state and the expected +terminals, and a per-state message function can override the text. See +[ERROR_MESSAGES](./ERROR_MESSAGES.md). A lexer error (`Lexer.LexError`) carries the character offset +and the offending character. ### 16.4 Universal lexer roundtrip @@ -2347,7 +2388,7 @@ source-order `parseTreeToken*`, `parseTreeProductionN`, and and the reversed dependent `ParseTreeList`. `FooParserRoundtrip.lean` defines `Certificate tokens value`, computes sufficient logarithmic fuel from its tree, and proves `parse_certificate` by applying the existing `parser_complete` theorem. The input word is -`tokens ++ [EOF]`, matching the augmented start production. No corpus is generated. +`(tokens ++ [EOF]).map Positioned.dummy`, matching the augmented start production. No corpus is generated. The user supplies `FooUnparse.lean` with the named token function and a separate proof module. That proof selects productions with the generated helpers and constructs a diff --git a/docs/ERROR_MESSAGES.md b/docs/ERROR_MESSAGES.md index 7a2c606..11b97a4 100644 --- a/docs/ERROR_MESSAGES.md +++ b/docs/ERROR_MESSAGES.md @@ -39,8 +39,10 @@ lookahead. The layer built on top lives in `line:col` from the offending token's span against the source string. This layer is *unverified* (like the executable engine), but it is proved -**consistent** with the verified parser: `diagnose_run_agrees` shows `diagnose` -classifies accept/reject/timeout exactly as the verified `Runtime.Exec.run`, so a +**consistent** with the executable parser `Runtime.Exec.run`: `diagnose_run_agrees` shows +`diagnose` classifies accept/reject/timeout exactly as `run`, +which each `*Verified` module relates to the dependent parser (`parserRunRefines`; for +`parse`, `parse_eq_dependent`), so a syntax error is reported exactly when the parser rejects the input. ## Using it from a generated parser @@ -48,7 +50,7 @@ syntax error is reported exactly when the parser rejects the input. The engine runs at `VP := Span × V`: every token carries a source span (the generated lexer emits `List (Runtime.Positioned Tok)`, and a hand-written lexer wraps its tokens the same way — `Runtime.Span.dummy` when there are no real -positions). Every generated parser module emits, alongside `parse` and `run`: +positions). Every generated parser module emits, alongside `parse`: ```lean def terminalName (t : Nat) : String -- readable terminal names @@ -86,11 +88,11 @@ spanned variant, the offending `Span`) if you want to build your own message. ## Custom per-state messages To attach hand-written messages (Menhir's `.messages` step), first list the -error states: +error states with `leanparsergenerator --list-errors `. It writes no files. +The library function behind it is `Emit.renderErrorList` +(`LeanParserGenerator/Emit/ErrorList.lean`). -```sh -lake exe leanparsergenerator --list-errors grammar/Calc.lig -``` +For `leanparsergenerator --list-errors test/calc/calc.lig` this prints: ```text # Syntax-error states for this grammar (9 state(s) can reject). @@ -116,7 +118,9 @@ def messages : Nat → Option String - `test/calc/ErrorMessageTest.lean` — `terminalName`/`diagnose`/`diagnoseSpanned`/ `errorMessage` behavior, the custom per-state message override, span-based `line:col` rendering, and agreement with `parse`. +- `test/calc/ErrorListTest.lean` — the error-state enumerator (`Emit.errorStates`, + `Emit.renderErrorList`) on a one-rule grammar. - `Runtime/Diagnostic.lean` — the `diagnose_run_agrees` consistency theorem is checked whenever the module compiles. -`ErrorMessageTest` is rooted in the `ParserTests` library: `lake build ParserTests`. +`ErrorMessageTest` and `ErrorListTest` are rooted in the `ParserTests` library: `lake build ParserTests`. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 944c345..8af2f8b 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -15,7 +15,7 @@ parser_unambiguous parse_eq_dependent ``` -The theorems are stated on the positioned tokens `ExprParser.parse` reads, with their real spans. If `ExprParser.parse` returns a value, `parser_sound` gives a parse tree for the input whose semantics is that value. `parser_err_free` and its equality form `parser_ne_err` state that `ExprParser.run`, the internal function that `parse` is built on, never returns `.err`, the result that would mean the generated tables are inconsistent. +The theorems are stated on the positioned tokens `ExprParser.parse` reads, with their real spans. If `ExprParser.parse` returns a value, `parser_sound` gives a parse tree whose word is a prefix of the input padded with EOF, and whose semantics is that value. `parser_err_free` and its inequality form `parser_ne_err` state that `ExprParser.run`, the internal function that `parse` is built on, never returns `.err`, the result that would mean the generated tables are inconsistent. In the other direction, `parser_complete` says that the parser accepts any input that has a start parse tree (`ParserStartTree`), as long as `2 ^ logNSteps` is at least the size of the tree. The README section "Fuel" shows what this means for the size of the input. The type `ParserStartTree` is rooted at the augmented start symbol `S'`, so its word includes EOF. `parser_unambiguous` says that two start parse trees for the same token word have equal spans and semantics. `parse_eq_dependent` says that `ExprParser` and the dependent specification parser return the same result at the same fuel. @@ -25,7 +25,7 @@ A caller does not have to assemble a validator proof or a refinement witness. Th The `.lig` frontend is not verified. The theorems are about the grammar that the frontend emitted into the Lean file. If the frontend misreads the `.lig` file, the proofs hold for the grammar it misread. The generator parses `.lig` files with a hand-written parser. A second parser, generated from `lig.lig`, reads the structure of a `.lig` file (directives, rules, alternatives) and has the proofs that every generated parser has. The Lean code inside `%header`, `%lexer` and the action bodies is still read by a hand-written scanner, so the generated parser covers the structure only. `lig-bootstrap-test` checks that the two parsers give the same result on the `.lig` files in this repository. That is a test on those files, not a proof. To check what the generator read, use the grammar view in the next section. [`DESIGN.md`](DESIGN.md) §15 has the details. -The parser theorems start at tokens, not characters. The generated lexer has its own maximal-munch soundness theorem against its DFA tables, checked with `native_decide` (see [`LEXER.md`](LEXER.md)). For a grammar with `%option parseStr` and a lexer with one mode whose rules all stay in it, the specification module connects the two: `parseStr_sound_tokenization` states that when `parseStr s k = some v`, the input `s` has a maximal-munch tokenization, the lexer's `tokenize s` returns the tokens, and their values have a parse tree with semantics `v`. `parseStr_eq_none_of_tokenize_error` states that `parseStr` returns `none` when `tokenize` fails. For such a lexer the module also proves completeness and unambiguity at the string level: `parseStr_complete_lexing` (a maximal-munch tokenization of `s` and a parse tree over its tokens within the fuel make `parseStr` return the tree's value), `parseStr_unambiguous` (two derivations of `s`, each the tokens `tokenize s` returns and a parse tree over them, have the same tokens and the same value), and the same over positioned tokens with `L.Lexes s ts` (the positioned tokenization, in which each token's span delimits its lexeme in `s`): `parseStr_sound_lexes`, `parseStr_complete_lexes`, `parseStr_unambiguous_lexes` and `parseStr_node_spans` (every leaf's span is the byte range of its lexeme in `s`, from which a rule's action emits the token; every inner node's span is a byte range `[a, b)` of `s` with `a ≤ b`, where `b` is the end of the lexeme of its last token and `a` is the start of the lexeme of its first token, or the end of the token before it for a node whose word is empty or whose leftmost children derive the empty word, the convention of the Rust backend). `parseStr_sound_exact` states that when `parseStr s k = some v`, `tokenize s` returns `ts`, `ts` is the positioned tokenization of `s`, and a parse tree over exactly `ts` has semantics `v`. These theorems take no hypothesis, also when an action reads a token span ([`DESIGN.md`](DESIGN.md) §6.1, §13). The other soundness theorems give a tree over a prefix of the token stream padded with EOF; they hold for any token list. `parseStr_sound_exact` adds the per-grammar `native_decide` check `endMarker_last` (`$` is the last symbol of every start production, and no other right-hand-side position holds `$` or the start symbol). Without `%option parseStr` the connection is not emitted, though `tokenize_sound` is emitted in the lexer module. The `lexre` regex frontend is not verified. +The parser theorems start at tokens, not characters. The generated lexer has its own maximal-munch soundness theorem against its DFA tables, checked with `native_decide` (see [`LEXER.md`](LEXER.md)). For a grammar with `%option parseStr`, a lexer with one mode whose rules all stay in it, and a `%eof` token without a value, the specification module connects the two: `parseStr_sound_tokenization` states that when `parseStr s k = some v`, the input `s` has a maximal-munch tokenization, `tokenize s` returns positioned tokens `ts` whose values are the tokens the specification tokenizer returns, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse tree with semantics `v`. `parseStr_eq_none_of_tokenize_error` states that `parseStr` returns `none` when `tokenize` fails. For a lexer with one mode whose rules all stay, also when the `%eof` token carries a value, the module proves completeness and unambiguity at the string level: `parseStr_complete_lexing` (a maximal-munch tokenization of `s` and a parse tree over its tokens within the fuel make `parseStr` return the tree's value), `parseStr_unambiguous` (two derivations of `s`, each the tokens `tokenize s` returns and a parse tree over them, have the same tokens and the same value), and the same over positioned tokens with `L.Lexes s ts` (the positioned tokenization, in which each token's span delimits its lexeme in `s`): `parseStr_complete_lexes`, `parseStr_unambiguous_lexes` and `parseStr_node_spans` (every leaf's span is the byte range of its lexeme in `s`, from which a rule's action emits the token, or the leaf is the end-of-input token at the end of `s`; every inner node's span is a byte range `[a, b)` of `s` with `a ≤ b`, where `b` is the end of the node's word, or the end `pe` of the token before the node when the word is empty, and `a` is `pe` or the start of the lexeme of the first token of the word. The theorem does not state which of the two `a` is; the parser takes `pe` for a node whose word is empty or whose leftmost children derive the empty word, the convention of the Rust backend). With a valueless `%eof` token, `parseStr_sound_lexes` gives the positioned tokenization for an accepted `parseStr`, and `parseStr_sound_exact` states that when `parseStr s k = some v`, `tokenize s` returns `ts`, `ts` is the positioned tokenization of `s`, and a parse tree over exactly `ts` has semantics `v`. No theorem takes a hypothesis about spans or the lexer (no `hlex`, no `hspan`), also when an action reads a token span ([`DESIGN.md`](DESIGN.md) §6.1, §13). The other soundness theorems give a tree over a prefix of the token stream padded with EOF: `parser_sound` holds for any token list, and `parseStr_sound`, `parseStr_sound_tokenize`, `parseStr_sound_tokenization`, `parseStr_sound_lexes` and `tokenize_parse_sound` state the same prefix form for the tokens that `tokenize s` returns. `parseStr_sound_exact` adds the per-grammar `native_decide` check `endMarker_last` (`$` is the last symbol of every start production, and no other right-hand-side position holds `$` or the start symbol). Without `%option parseStr` the connection is not emitted, though `tokenize_sound` is emitted in the lexer module when the lexer has one mode whose rules all stay in it. The `lexre` regex frontend is not verified. ## Looking at the grammar that was checked @@ -58,11 +58,13 @@ The repository contains no `sorry`. I checked the axioms of the six exported the - `parser_unambiguous` depends on `propext`, `Quot.sound`, and the `native_decide` axiom of the generated completeness check. - `parser_complete` additionally depends on `Classical.choice` and on the `native_decide` axiom of the generated completeness check. +I also checked `tokenize_sound`, `posLexerAgrees` and the `parseStr_*` theorems on calc and cedar; they depend on `Classical.choice`. Each depends on `propext`, `Classical.choice`, `Quot.sound` and the `native_decide` axioms of the checks it uses: the lexer's `validated0`, `flatValidated0` and `byteUnicodeValidated`, the parser checks above, `startProds_end` for the soundness and lex-failure theorems, and `endMarker_last` for `parseStr_sound_exact`. `parseStr_node_spans` depends on the three standard axioms only. + ## The module system The library and every generated module use Lean's module system. Each file has a `module` header, and imports are `public import`. The generated code separates its public API from its internals: -- A generated parser exposes its value type, `parse`, `diagnose` and `errorMessage`. It also exposes `run`, because the theorems are stated about it, but `run` is not a stable interface. The LR tables, `decode` and `sem` are internal, so a caller that imports the parser sees only the API. The specification module reaches the internals with `import all`, which is allowed because both modules are in the same package, and uses them in its refinement proofs. +- A generated parser exposes its value type, `parse`, `diagnose` and `errorMessage`, and, with `%option parseStr`, `parseStr`. It also exposes `run`, because the theorems are stated about it, but `run` is not a stable interface. The LR tables, `decode` and `sem` are internal, so a caller that imports the parser sees only the API. The specification module reaches the internals with `import all`, which is allowed because both modules are in the same package, and uses them in its refinement proofs. - A generated lexer exposes the token type, `tokenize` and `tokenizeByte`. The DFA tables and validator certificates are internal. `tokenizeByte_toOption` relates `tokenizeByte` to `tokenize`: both succeed on the same inputs, with the same token values. - The specification module is exposed in full, because its grammar, automaton, dependent types and exported theorems are what proofs use. diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 6422736..a2ea5a5 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -67,7 +67,7 @@ declarations, and the EOF constructor must agree with `%eof`. ## 3. Choose a lexer regime -There are two regimes, and no third. +There are two regimes. **Generated (recommended).** Put a `%lexer { … }` block in the `.lig` (§4). The generator emits the token type and the tokenizer into `ExprLexer.lean`, and the @@ -157,7 +157,8 @@ of the modules, and `--rust-out` writes the Rust parser. The exit code is 0 on success, 1 on any error, and 2 when Pager reports LR(1) conflicts (the files are still written). Generated files should not be edited manually. -Application code normally imports the lexer and parser only: +Application code (here `MyProject/App.lean`, the `App` root of the Lake target in +§7) normally imports the lexer and parser only: ```lean import MyProject.Generated.ExprLexer @@ -189,14 +190,14 @@ import MyProject.Generated.ExprVerified It exports theorems stated about `ExprParser` (the ones about `run` are about the internal function that `parse` is built on): -- `parser_sound`: a successful `ExprParser.parse` result has an input-linked - `ParserStartTree` with the returned semantics; +- `parser_sound`: a successful `ExprParser.parse` result has a `ParserStartTree` + over a prefix of the EOF-padded input, with the returned semantics; - `parser_err_free`: `ExprParser.run` satisfies `Runtime.Exec.ResultErrFree`; - `parser_ne_err`: `ExprParser.run` cannot equal `.err message`; - `parser_complete`: a supplied `ParserStartTree` is accepted whenever `Grammar.ptSize tree ≤ 2 ^ logNSteps`; - `parser_unambiguous`: two start parse trees for one token word have equal - semantics; + spans and semantics; - `parse_eq_dependent`: the parser equals the dependent specification parser at matching logarithmic fuel. @@ -272,9 +273,9 @@ lean_lib MyProject where -- certificates. Keep it OFF the default path in its own non-default library so a -- plain `lake build` does not re-check the proofs, and so Lake caches each -- certificate to `.olean` — an unchanged `lake build MyProjectVerified` is then a --- trace no-op instead of a full re-check. For large grammars (Cedar/C99-scale) --- the difference is minutes-to-seconds; this repository's `VerifiedMid`/`VerifiedHeavy` --- targets are the same pattern (DESIGN §10, §14). +-- trace no-op instead of a full re-check. For Cedar the difference is about 20 s +-- cold against 1 s cached; this repository's `VerifiedMid`/`VerifiedHeavy` targets +-- are the same pattern (DESIGN §10, §14). lean_lib MyProjectVerified where roots := #[`MyProject.ExprAst, `MyProject.Generated.ExprLexer, `MyProject.Generated.ExprParser, diff --git a/docs/ITEMS.md b/docs/ITEMS.md deleted file mode 100644 index a5148f0..0000000 --- a/docs/ITEMS.md +++ /dev/null @@ -1,369 +0,0 @@ -# Item streaming for list-shaped grammars (design draft) - -Status: draft for discussion, nothing implemented. Option E of `next.md` (sub-entry points -that define items). The goal is higher throughput and bounded memory on inputs that are -mostly one long list, such as the `.code` section of `test/asm`, and a design that also -allows parsing one list in parallel chunks (§7). - -## 1. What the measurements say - -All numbers: `test/asm`, input from `gen_large.py --seed 1`, `BENCH_STREAM=1 -BENCH_ITERS=3`, one process on one core (`taskset -c 20`), HEAD fc356f7. These numbers predate the -left-recursive list macros (§9); §5.1 has the measurements of the fold and cursor -prototypes on the current macros. - -To bound the gain, I replaced the action of `code ::= code entry` so that it drops the -entry instead of pushing it (Rust: `std::hint::black_box(&e); drop(e); xs`; Lean: -`fuse26` and `semV 26` return `xs`). This is what an item sink that discards its items -costs: every entry is still built, then freed right away. - -| backend | input | variant | ns/token | MB/s | peak RSS | -|---|---|---|---|---|---| -| Rust | 10 MB | `parse_values_str` (AST kept) | 76.3, 76.6 | 47.7 | 124 MiB | -| Rust | 10 MB | entries dropped | 45.3 to 45.9 | 80.0 | 12 MiB | -| Rust | 100 MB | entries dropped | 45.2 | 80.8 | 98 MiB | -| Rust | 10 MB | trace parser (`parse_str`, no values) | 28.2, 30.3 | 120 to 129 | 12 MiB | -| Lean | 10 MB | `parseStr` (AST kept) | 221.1, 222.8, 222.0 | 16.4 | 195 MiB | -| Lean | 10 MB | entries dropped | 177.6 to 179.6 | 20.4 | 35 MiB | - -Rust is 40% faster and Lean 20% faster. In both, peak RSS falls to about the size of the -source. I think the time saved is mostly cache misses: a freed entry's memory is reused -for the next entry while it is still in cache, while a kept AST grows past the cache. I -did not count misses. In Rust, the remaining 15 to 17 ns/token above the trace parser is -building and freeing the values. A real -sink adds its own cost on top of these numbers. - -## 2. Automaton facts this relies on - -For a left-recursive list `L ::= L I | ε` in any LR automaton: if `L` is entered from -state `s` and `q = goto(s, L)`, then reducing `L ::= L I` pops back to `s` and pushes -`goto(s, L) = q` again. So between two items the stack is the same cells up to the value -in the `L` cell. I call `q` the loop state of `L` in context `s`. - -On `asm.lig` (computed from `ACTION` and `GOTO` in `rust/src/generated.rs`): `code` has one context, `goto(13, code) = 27`. State 27 shifts -`D_MARK`, `D_ALIGN`, `OPCODE` and `LBL`, which are `FIRST(entry)`, and reduces -`section ::= D_CODE code` (production 12) on the section directives and EOF. No other -state shifts any of these four terminals. Section 7 uses that. - -With right recursion (`list(X)`, `L ::= I L | ε`) there is no loop state: the stack grows -by one cell per item and the `L` reductions run at the end of the list, last item first. - -## 3. Proposal - -The user marks a list nonterminal `L` as itemized. In the item-streaming parser: - -- every reduction of a production of `L` passes each `I` argument, in order, to a sink, - with its span, and produces `empty_L` instead of running the `.lig` action; -- every other action runs unchanged, so the parent of `L` gets `empty_L`. On asm, - `section ::= D_CODE es=code { Section.code es }` gives `Section.code #[]`; -- the tables, the lexer, and accept/reject are the same as `parseStr`/`parse_values_str`. - -`empty_L` is the value of the `ε` alternative of `L` when it has one with no arguments -(`#[]` / `Vec::new()` for `code`). Otherwise, for example for a -`separated_nonempty_list`-shaped `L ::= L SEP I | I`, the user supplies it. - -A list must be left-recursive to be itemized: every production of `L` is either -`L ::= L α` or has no `L` on its right-hand side, and contains `I` exactly once, with -the other symbols terminals. The generator rejects right-recursive lists with a message -that shows the left-recursive form, which `test/asm/README.md` already recommends for -long lists. The built-in list macros are left-recursive (§9), so a macro list can be itemized too. - -Nesting works by marking several lists. If asm's top level were `sections ::= sections -section | ε` and both `sections` and `code` were itemized, the sink would receive the -entries of a `.code` section, then `Section.code #[]`, then the next section. Items -arrive in reduction order, which is input order, with an inner list's items before its -enclosing item. - -Items arrive one token late: an entry is reduced when the token after it is seen, since -asm instructions have no terminator. Items reduced before a syntax error have already -been given to the sink, so the sink sees a prefix of the input that the parser -eventually rejects. The final result tells the caller whether to discard them. - -### Why the value is replaced by a constant - -I considered two other designs. - -- **Begin/end events with no enclosing value** (next.md's version). This changes the - action interface, since `Section.code es` has no `es` to read. The hollow value keeps - every `.lig` action as it is. -- **Overridable fold actions**, where `L`'s cell holds a user accumulator updated by a - user step function. This is more general, but the parent action then receives the - accumulator type instead of `Array Entry`, and the `L` value differs between two - points of the list. The constant `empty_L` is what makes the stack at every item - boundary identical (§2), which is what §7 needs. - -### 3.1 Begin events - -When the base production of an itemized `L` reduces (the production with no `L` on its -right-hand side), the sink first receives `begin_L(pos)`, then that production's items -if it has any. For `code ::= ε` this happens right after `D_CODE` is shifted, before the -first entry. `pos` is the end offset of the last shifted token, or 0 at the start of the -input. Both backends know it without looking ahead: the Rust loop keeps `prev_end`, and -in Lean it is the `e` field of the top cell. A begin event carries no values from before -the list. A grammar that needs them, for a section name for example, factors the header -into its own nonterminal. - -With `sections` and `code` both itemized, the asm sink receives `begin_sections`, the -other sections, `begin_code`, the entries, `Section.code #[]`, and so on. Every list gets -one begin event, including an empty one. An end event is not needed: the enclosing -item, or the final result, closes the list. - -## 4. Rust API - -Generated per grammar, with one method per itemized list: - -```rust -pub trait ItemSink<'a> { - fn begin_code(&mut self, pos: u32); - fn code(&mut self, item: crate::ast::Entry<'a>, span: Span); -} -pub fn parse_items_from<'a, S: TokenSource>, K: ItemSink<'a>>( - source: &mut S, stacks: &mut Stacks<'a>, sink: &mut K, -) -> Result, StreamError>; -pub fn parse_items_str<'a, K: ItemSink<'a>>( - src: &'a str, stacks: &mut Stacks<'a>, sink: &mut K, -) -> Result, StreamError>; -``` - -The body is `parse_values_from` with the actions of `L`'s productions replaced by -`sink.code(e, e_span)` and a push of `empty_L`. The trait is generic, so each sink gets a -monomorphized copy and the call is inlined. `parse_values_from` stays as it is. The -generated file then holds two copies of the action `match`; merging them into one -function generic over a mode is possible later if code size matters. - -## 5. Lean API - -```lean -class ItemSink (σ : Type) where - beginCode : σ → Nat → σ - code : σ → Entry → Runtime.Span → σ - -def parseItems [ItemSink σ] (input : String) (init : σ) (logNSteps : Nat := 20) : - Runtime.Exec.Result VP × σ -``` - -The engine is `goStream` with one more loose argument `acc : σ`, `@[specialize]` on the -sink instance, so the sink is not called through `lean_apply`. The reduce of an itemized -production goes to a generated `@[inline]` function in continuation-passing style, -`(acc, stk) ↦ k (ItemSink.code acc e sp) (pushGoto … empty_L tl)`, so no pair is -allocated per item. Other productions use `fuse` as now. The accumulator is returned on -reject too: it holds the items of the prefix before the error. - -The sink is a pure fold. Processing items in `IO` as they arrive would need a monadic -engine or a resumable cursor (`next : Cursor → Step Item Cursor`, Menhir's incremental -API). Both are possible later; the cursor costs one allocation per item. - -### 5.1 Resumable cursor - -`goItems` is a tail-recursive loop whose state is its loose arguments: fuel, stack, -lookahead (`isEnd`, `t`, `a`, `b`) and lexer state (`lf`, `li`, `ls`, `lfin`). A cursor -is a structure holding those fields and the input bytes. `Cursor.next : Cursor → Event` -runs the same loop, but where `goItems` would call the sink, it returns -`.item it sp c'` or `.begin l pos c'` with the cursor saved at that point. When the run -ends it returns `.done r`. A consumer in `IO` loops over `next`, and the loop terminates -because the fuel stored in the cursor decreases between two events. The fold version is -then a loop over the cursor, or stays a separate specialized loop if that is faster. - -Cost: one `Cursor` and one `Event` allocation per item, about 6 tokens on asm. Proof: -`iterate (next c)` equals `goItems` with the list sink, by induction on the fuel, the same -shape as `goStream_eq_goSrc`. - -In Rust, the cursor is a struct holding `Stacks`, the token source, `ti` and `prev_end`, -and implementing `Iterator>`. `Event` is a generated enum with one item -variant and one begin variant per itemized list. `next` runs the loop until the next -event. The hot loop is unchanged, but its locals are reloaded from the struct once per -event. The final result is read from the struct after `None`. - -**Measured.** Prototypes for the `code` list of asm, patched by hand against the generated -parsers: the Lean `goItems` (fold) and `goCur` plus a driver loop (cursor), and the Rust -`parse_items_fold_from` with an `FnMut` sink and an `ItemCursor` implementing `Iterator`. -"ast" is `parseStr` / `parse_values_str` followed by the same work over the returned AST. -The per-entry work is the same in all three (count the entry and its operands), and all -three give the same total on the samples and the 1, 10 and 100 MB inputs. Five rounds, -interleaved, one process per row and round on core 20; medians in ns/token, the range -over the 5 processes, and the change against the fold. - -| backend | input | variant | ns/token | range | vs fold | peak RSS (MiB) | -|---|---|---|---|---|---|---| -| Rust | 1 MB | ast | 51.6 | 50.8–52.2 | +28.3% | 16 | -| Rust | 1 MB | fold | 40.2 | 39.9–40.3 | | 3 | -| Rust | 1 MB | cursor | 42.4 | 42.0–43.6 | +5.4% | 3 | -| Rust | 10 MB | ast | 68.4 | 67.9–68.7 | +70.5% | 127 | -| Rust | 10 MB | fold | 40.1 | 40.0–40.2 | | 12 | -| Rust | 10 MB | cursor | 42.2 | 41.9–42.3 | +5.2% | 12 | -| Rust | 100 MB | ast | 72.8 | 72.4–73.0 | +80.6% | 1364 | -| Rust | 100 MB | fold | 40.3 | 40.1–42.4 | | 98 | -| Rust | 100 MB | cursor | 42.2 | 41.9–43.6 | +4.8% | 98 | -| Lean | 1 MB | ast | 199.2 | 198.0–200.0 | +9.0% | 31 | -| Lean | 1 MB | fold | 182.7 | 181.7–183.6 | | 17 | -| Lean | 1 MB | cursor | 191.2 | 190.7–191.9 | +4.6% | 17 | -| Lean | 10 MB | ast | 217.5 | 217.1–218.8 | +17.7% | 195 | -| Lean | 10 MB | fold | 184.8 | 182.8–186.2 | | 35 | -| Lean | 10 MB | cursor | 191.1 | 190.2–192.1 | +3.4% | 35 | -| Lean | 100 MB | ast | 221.6 | 221.3–223.5 | +20.1% | 1593 | -| Lean | 100 MB | fold | 184.4 | 182.9–185.8 | | 207 | -| Lean | 100 MB | cursor | 192.6 | 192.0–195.6 | +4.4% | 207 | - -The cursor costs 3–5% over the fold in both backends at every size, and the ranges do not -overlap. Its peak RSS is the fold's. The fold takes 15–17% less time than building the AST -in Lean at 10 and 100 MB, and 41–45% less in Rust. - -The prototypes are not in the repository. They patch `AsmParser` and `generated.rs` -directly: production 26 is hard-coded, and there are no begin events and no proofs. - -### 5.2 What the cursor makes incremental, and what it does not - -"Incremental parsing" covers three different things. The cursor gives the first. It is -also the base the other two would build on. - -1. **Suspend and resume** (Menhir's incremental API). The consumer drives the parser - instead of the parser calling a sink: - - it can stop early, after the first N entries or at the first entry that matches a - condition, by dropping the cursor; the fold always runs to the end of the input; - - it can run effects (`IO`) between items at its own pace; the Lean fold is pure; - - in Lean a cursor is an immutable value, so it can be kept and resumed more than once, - for example one cursor per item boundary as a checkpoint. Resuming a cursor that is - still referenced elsewhere makes the engine copy the stack cells it would otherwise - reuse in place, so the second resume costs more than the first; not measured. The - Rust `ItemCursor` owns mutable `Stacks`, so a Rust checkpoint needs `Clone` on the - cursor (and on the values on the stacks). - - Cost: 3–5% over the fold (§5.1). - -2. **Input that arrives in pieces** (push-style input, a `NeedMore` result). The cursor - does not give this. It suspends when an item is reduced, not when the input runs out: - the pull lexer `Lexer.pullAuxF` (`Lexer/BytePull.lean`) reads from a `ByteArray` that - holds the whole input. Chunked input needs a resumable lexer that, at the end of a - buffer, keeps the DFA state, the start of the current token and the last accepting - position, because the token may continue into the next chunk. The statement to prove is - `tokenize (a ++ b) = resume (resume init a) b`. The cursor would get one more event, - `needInput c`, returned when the lexer suspends; the parser state is already in the - cursor. In Rust the tokens borrow `&'a str` slices of the source, so a token that spans - two chunks needs an owned copy or a source that keeps the chunks alive. - -3. **Re-parsing after an edit** (Wagner and Graham's incremental LR, tree-sitter). The - cursor does not give this either, but with item streaming it comes close. Because the - `L` value is the constant `empty_L`, the stack at every item boundary of `L` is the same - (§2). After an edit inside item `k`, the parser can resume from the checkpoint saved at - the boundary before item `k`, and stop at the first later boundary where it is back at - the loop state and the new token stream agrees with the old one, shifted by the length - of the edit. The items between are replaced, the rest are kept with shifted spans. The - check is the one of §7 (stack back at the base, lexer resynchronized), so the - correctness argument is the same. Not prototyped or measured. - -## 6. What is proved - -Plan, in stages. Each stage is useful without the next. - -1. **Same control.** The hollow table `fH` has the same `actionData`, `gotoData`, - `lenData`, `lhsData` and `defRedData` as `flat`, and differs only in `sem`. A generic - lemma: two runs over tables that differ only in `sem` take the same steps and give - the same `.reject s t`, `.timeout`, `.err`, or `.ok`. So `parseItems` accepts exactly - when `parseStr` does, and rejects at the same state and token. The existing - `run_erase` (spans only) is a special case. -2. **The stream is a writer run.** Define the writer table `fW` over `List Item × V`: - production `p` concatenates the writers of its arguments, appends its items if it is - an `L` production, and computes `semH p`. Generic theorem: `parseItems input init = - (r, items.foldl emit init)`, where `(items, r)` is `Exec.run fW` split. Per grammar, - the generator emits `FuseOK`-style proofs for the few itemized productions, the same - shape as `fuseOK

`. The invariant of the simulation is that `acc` is the fold of - the concatenated writers of the stack cells, bottom to top. It holds because a reduce - concatenates the writers of a contiguous run of top cells in order. -3. **Tree characterization.** The validators read only `GrammarSig` (Runtime/Grammar.lean), - so a dependent `Grammar` with the writer semantics reuses `safety` and `completeness` - unchanged. With the per-production refinement proofs for `fW` (the `rfl` proofs that - `CodegenVerified` already emits for `flat`), the target statement is: if `parse ts = - some v`, there is one parse tree `t` with `v = ⟦t⟧`, the items are the hollow values - of the `I`-children of the `L`-nodes of `t` in left-to-right order, and the returned - value is `t`'s hollow semantics. This needs nothing grammar-specific beyond the - emitted refinement. - -I do not plan to state "full value = hollow value with the items plugged back in", -because writing `plug` requires knowing how each action uses `es`, which the generator -does not know. Instead, CI checks that a sink collecting the items and a dump of the -hollow value reproduce `--dump` on the asm samples and large inputs. - -## 7. Parallel parsing of one list - -This is the reason for the constant `empty_L`. Take a list `L` with loop state `q` in -context `s`. Cut the input at byte offsets `b_1 < … < b_k` inside the list. - -- **Stack.** At every item boundary the sequential stack is the same `P ++ [(s, …), - (q, empty_L)]`, where `P` is the stack below. A chunk can therefore be parsed from - the two-cell base `[s, (q, empty_L)]`. It never pops below `s`: the only reduce that - pops the `q` cell is `L ::= L I`, which needs `s` for its goto, and the chunk stops - before any reduce that would pop `s` (production 12 on asm). -- **Chunk run.** Chunk `i` lexes and parses from `b_i`. It stops when its next token - starts at or after `b_{i+1}` and the stack is back at the base, and it passes when the - action of `q` on that token is a shift. Its items go to its own sink. -- **Lexer.** Chunk `i` lexes from `b_i` in the start mode. It agrees with the sequential - lexer when the sequential lexer has a lexeme boundary at `b_i`, or at least resumes - the same token sequence. Chunk `i-1` checks this: its last lexeme must end exactly - where chunk `i`'s first lexeme starts. -- **Result.** Chunk 0 is the sequential parse up to `b_1`, ending with `P ++ [s, q]`. If - every chunk passes, the sequential parse from `P ++ [s, q]` continues from `b_k` to - the end, and the item list is the concatenation of the chunks' lists. If a chunk fails - (the cut fell outside the list, or the lexer did not resynchronize), the parse - restarts sequentially from the last chunk that passed. The cut points are untrusted - heuristics. Correctness comes from the checks, by determinism of the automaton and of - the lexer, and is provable as a lemma about `goFast` on stacks with a common prefix. - -A generator-side check finds the cut points. A terminal is a *sync terminal* of `L` if -the only states that shift it are loop states of `L`. On asm, `OPCODE`, `LBL`, `D_MARK` -and `D_ALIGN` are sync terminals of `code` (§2), so any occurrence of one of them in a -valid input starts an entry. For asm, a cut at a line start before an uppercase letter, -`.mark` or `.align` always works lexically. Comments stop before `\n`, strings exclude -`\n`, and whitespace cannot extend into a letter. That is an argument about this lexer, -not a proof, so the runtime check above stays. - -Item sinks must then be combinable: each chunk folds from `init`, and the results are -combined in order. For a `List`/`Array` sink this is concatenation. For a general sink, -the user supplies the combine and its associativity. - -The expected speedup is up to the number of cores, minus the sequential prefix and -suffix and the cost of finding cuts. I have not measured it. - -## 8. Generator changes - -- Syntax: a way to mark `L`, and optionally its `empty_L` (Lean and `!!rust{…}`). See - open question 1. A new `%option` goes through `optionSpecs` (`Frontend/File.lean`) - and needs no `lig.lig` change. A new directive means regenerating `LigParser`. -- Checks (`Frontend/Diagnostics.lean`, so the language server reports them too): `L` - is left-recursive in the sense of §3, `I` occurs exactly once per production, and - `empty_L` exists. Report the sync terminals. -- Lean: `Emit/Codegen.lean` emits `ItemSink`, the itemized reduces and `parseItems`. - New engine `goItems` in `Lexer/StreamRun.lean` beside `goStream`. Stage-1 and stage-2 - lemmas in `Runtime/ExecStream.lean` or a new `Runtime/ExecItems.lean`. - `Emit/CodegenVerified.lean` gets the stage-3 refinement. -- Rust: `Emit/Rust/Values.lean` emits `ItemSink`, `parse_items_from` and - `parse_items_str`, and, if the cursor is chosen, `Event` and the cursor struct. The - prototype's cursor is the loop of `parse_values_from` moved into a function that takes - `ti` and `prev_end` by reference and returns `Step::Item` or `Step::Done`; the - generator can emit it the same way. -- Lean cursor (if chosen): `Cur`, `Ev`, `goCur` and `Cur.next` beside `goItems`, and the - lemma that iterating `next` equals `goItems` with the list sink. -- asm: make `code` itemized and add `BENCH_ITEMS=1` to both drivers, plus the - collect-and-dump agreement check in CI. - -## 9. Decisions and open questions - -Decided: - -1. The list is marked: `%items code`. A standalone sub-entry parser (`%start entry`) is a - separate feature, not part of this one. -2. Begin events are emitted (§3.1). -3. `list(X)` and the other list macros are left-recursive and produce `Array`/`Vec` - (implemented, see `Frontend/Macros.lean` and the CHANGELOG). `separated_list(sep, X)` - is `ε` or `separated_nonempty_list(sep, X)` and no longer accepts a trailing - separator. -4. Proof stage 3 (§6) is deferred. The first change proves stages 1 and 2. - -Open: - -- How to name a macro instance in `%items` (`%items list(entry)`?) if the user does not - write the list by hand. -- Lean sink: pure fold, cursor (§5.1), or both. Measured: the cursor costs 3–5% over - the fold in both backends, with the same peak RSS. If both are generated, the fold can - stay a separate loop, since a fold written as a loop over the cursor would pay that cost. -- Whether to design chunked input (§5.2, item 2) and edit re-parsing (§5.2, item 3) now, or - after the first change. diff --git a/docs/LANGUAGE_SERVER.md b/docs/LANGUAGE_SERVER.md index 1b94235..472d6d3 100644 --- a/docs/LANGUAGE_SERVER.md +++ b/docs/LANGUAGE_SERVER.md @@ -57,8 +57,8 @@ Document synchronization is **full** (`TextDocumentSyncKind.Full`). Any LSP client can launch the server. For a Neovim client you might register a server whose command is the built binary and whose `filetypes` include `lig`. -For VS Code, point a generic LSP extension's server command at the binary and -associate the `.lig` extension with a `lig` language id. +For VS Code, the extension in [`editors/vscode`](../editors/vscode/README.md) runs the +server and adds syntax highlighting. ## Tests diff --git a/docs/LEXER.md b/docs/LEXER.md index 7cbe279..a2ef047 100644 --- a/docs/LEXER.md +++ b/docs/LEXER.md @@ -24,7 +24,7 @@ A rule has the form: | regex as text => action ``` -An action is either `skip` or a Lean expression producing a token. A regex can use quoted strings, character classes, sequencing, alternation, grouping, `*`, and `+`. For example: +An action is either `skip` or a Lean expression producing a token. A regex can use quoted strings, character literals (`'c'`), character classes (`[…]`, `[^ …]`), `_` (any character), `ε` (the empty string), a `let`-bound name, sequencing, alternation `|`, grouping, and the postfix operators `*`, `+` and `?`. For example: ```text %tokentype Tok @@ -127,7 +127,7 @@ The generated module does not state constructor coverage or synthesize reachabil A lexer module also emits `noEofEmit` (no rule emits the `%eof` token) when that token carries no value, and, for one mode whose rules all stay: -- `tokenize_sound`: a successful `tokenize` is a maximal-munch `Lexer.Tokenization` of the input and the spec `Lexer.tokenize lexer` returns the same token values; +- `tokenize_sound`: if `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization (`Lexer.Tokenization`) and the spec `Lexer.tokenize lexer` returns the token values of `ts`; - `tokenize_complete`: if the input has a maximal-munch `Lexer.Lexing` with steps `steps` (each step a rule and a length, `Lexer/Lexing.lean`), `tokenize` succeeds and its token values are `Lexer.lexingTokens lexer lexer.start input.toList steps`. `Lexer.Lexing.unique` states that the steps are determined by the input; - `Lexes s ts`, the positioned tokenization of `s` (`Lexer.PosLexing`): each token's span `⟨p.offset, q.offset⟩` delimits its lexeme `s.extract p q`, the maximal-munch match at `p`; a rule whose action emits nothing (a skip) consumes the bytes between two tokens; the end-of-input token has the empty span at the end. `Lexer.PosLexing.spans_ordered` states that the spans lie in the input and that each ends at or before the next starts; - `tokenize_iff_lexes : tokenize s = .ok ts ↔ Lexes s ts`, `lexPos_iff_lexes` (the same for the byte lexer `lexPos`, through `posLexerAgrees`), and `lexes_unique`; diff --git a/docs/RUST_PARSER.md b/docs/RUST_PARSER.md index 32bd4f8..9e9b856 100644 --- a/docs/RUST_PARSER.md +++ b/docs/RUST_PARSER.md @@ -71,11 +71,11 @@ compile, the user changes it; the rustc error is in `generated.rs`, and each arm comment with the rule name and alternative number. How a user writes and calls them is in `docs/USING_RUST_GENERATOR.md`. -The motivation is that the parsing theorems are stated on parse trees, so the proof that -the Rust parser corresponds to the Lean one needs the two parsers to agree on the trace, -and does not need their semantic values to agree. The values are the user's: the Lean and -the Rust action of a production are separate pieces of code, and nothing checks that they -build the same thing. A user who wants that can compare them on their own inputs. +The motivation is that the parsing theorems relate the Lean value to the parse tree, so a +correspondence proof on the trace gives the tree for the Rust parser, and nothing relates +the Rust value to it. The values are the user's: the Lean and the Rust action of a +production are separate pieces of code, and nothing checks that they build the same thing. +A user who wants that can compare them on their own inputs. The driver, `parse_values`, keeps one `Vec` per distinct Rust type (`Stacks`) and an entry stack of states and spans. A reduction pops the values of its right-hand side, each from the @@ -283,7 +283,7 @@ on regexes). The inclusion test explores the derivatives of both regexes togethe `DFA.build?WithVecs`. Every other expression is reported as not checked. The check is not trusted, only informative. -On the public grammars all the `toNat!`/`toInt!` calls are proved. A grammar with +On the public grammars the domain check accepts every `toNat!`/`toInt!` call. A grammar with `0x` hex literals going through `toNat!` is reported `NOT SATISFIED` for that rule. ### Decisions @@ -299,7 +299,7 @@ classifier or report does it today. | D4 | An action is emitted only if it uses the rules above and `knownFns`. Lambdas are never emitted. | Applies to lexer actions and the classifier; for parser actions superseded by D17 | | D5 | A variable used more than once is a note ("copy needed"), not a blocker. | Reported by the classifier; with D17 it is the user's concern | | D6 | `List T` as a Rust cons-list rather than `Vec`, because `x :: rest` on a `Vec` is a front insert. | Superseded by D17: the user picks the type (a `VecDeque` with `push_front` does it in O(1)) | -| D7 | `Nat` becomes `u64` and `Int` becomes `i64`. A value out of range is an error in the Rust code (D15), so the correspondence theorem reads: if the Rust lexer succeeds, so does Lean's, with the same tokens. | Implemented for lexer token values | +| D7 | `Nat` becomes `u64` and `Int` becomes `i64`. A value out of range is an error in the Rust code (D15), so a correspondence theorem, if one is proved, would read: if the Rust lexer succeeds, so does Lean's, with the same tokens. | Implemented for lexer token values | | D8 | The Rust AST types are generated from the Lean environment. | Tried and dropped, see D17 | | D9 | Unemittable actions become methods of a generated trait the user implements. | Not done; D17 puts the Rust text in the `.lig` instead | | D10 | A partial known function carries its domain as a regex, and the generator checks lexer-rule languages against it. | Implemented for lexer actions | diff --git a/docs/USING_RUST_GENERATOR.md b/docs/USING_RUST_GENERATOR.md index 735a2f4..63f101b 100644 --- a/docs/USING_RUST_GENERATOR.md +++ b/docs/USING_RUST_GENERATOR.md @@ -231,10 +231,10 @@ return. One thing differs: the Rust actions of `parse_values_str` run on the tok before the first error, lex or parse, where `tokenize` followed by `parse_values` runs no action when the input has a lex error. Actions with side effects see that prefix. -On the 100 MB `asm` input, `parse_values_str` takes 76.7 ns/token against 83.4 for -`tokenize` followed by `parse_values`, with a peak RSS of 1347 MiB against 2182 MiB, -and `parse_str` with a counting sink peaks at 98 MiB (the source) against 2519 MiB for -`parse` with its token and node vectors; `test/asm/README.md` has the numbers. +On the 100 MB `asm` input, `parse_values_str` takes 73.3 ns/token against 81.9 for +`tokenize` followed by `parse_values`, with a peak RSS of 1364 MiB against 2199 MiB, +and `parse_str` with a counting sink peaks at 98 MiB (the source) against 1796 MiB for +`parse` with its token and node vectors over a slice (measured after #18); `test/asm/README.md` has the numbers. ### The lexer @@ -323,7 +323,8 @@ The generator pastes each Rust action into the reduction of its production, as t block that must evaluate to the rule's Rust type. It does not read the text, so any Rust works: statements before the final expression, calls into your own modules, closures. It is your job to keep the Rust action doing what the Lean one does; nothing checks it, -and the theorems about the parser are about the parse tree, which does not depend on either. +and the Lean theorems relate the Lean value to the Lean actions over the parse tree; +nothing relates the Rust value to either. What is in scope in the body: diff --git a/lakefile.lean b/lakefile.lean index 0d6a4f8..8799e83 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -83,7 +83,7 @@ structure GenTarget where output names and modules are inferred from the `.lig` stem and its `%option`s (`module_prefix`, `roundtrip_lexer`), so a normal target is just the input. -/ def genTargets : Array GenTarget := #[ - -- Our parser generator bootsraps itselfs by generating the parser for `.lig` files. + -- The parser generator bootstraps itself by generating the parser for `.lig` files. -- Regenerating this needs a working generator; the committed `LigParser`/`LigVerified` keep a -- clean checkout building without bootstrapping. Its outputs live in -- `Generated/` under a dotted module prefix, so it passes `--out-dir` and `--module-prefix`. @@ -203,6 +203,7 @@ lean_lib «VerifiedSmoke» where `asm.AsmAst, `asm.AsmLexer, `asm.AsmParser, `asm.AsmVerified, -- A grammar whose actions read spans (`w_span`). `spanuse.SpanUseLexer, `spanuse.SpanUseParser, `spanuse.SpanUseVerified, + `spanuse.SpanUseLexerRoundtripSupport, `spanuse.SpanUseLexerRoundtrip, ] needs := #[parsers] @@ -233,6 +234,9 @@ lean_lib «VerifiedMid» where `cedarentities.CedarEntitiesParser, `cedarentities.CedarEntitiesVerified, `cedarentities.CedarEntitiesLexerRoundtripSupport, `cedarentities.CedarEntitiesLexerRoundtrip, + -- Rust actions (the Lean side) + `rustactions.RustactionsAst, `rustactions.RustactionsLexer, + `rustactions.RustactionsParser, `rustactions.RustactionsVerified, ] needs := #[parsers] @@ -250,7 +254,7 @@ lean_lib «VerifiedHeavy» where @[default_target] lean_lib «RustActions» where srcDir := "test" - roots := #[`rustactions.RustActionsAst, `rustactions.RustactionsLexer, `rustactions.RustactionsParser] + roots := #[`rustactions.RustactionsAst, `rustactions.RustactionsLexer, `rustactions.RustactionsParser] needs := #[parsers] /-- The `asm` fixture (long unterminated lists, Lean and Rust backends): its Lean AST, the @@ -297,12 +301,14 @@ lean_exe «cli-test» where srcDir := "test" root := `cli.CliTest -/-- End-to-end functional parser tests (calc, imp). Light fixtures only; kept out - of the heavy path. Builds the `#guard`/`native_decide` checks. -/ +/-- End-to-end functional parser tests (calc, imp, cedar, spanuse) and the error-state + enumerator test. No verified modules; kept out of the heavy path. Builds the + `#guard`/`native_decide` checks. -/ lean_lib «ParserTests» where srcDir := "test" roots := #[`calc.CalcAst, `calc.CalcLexer, `calc.CalcParser, `calc.ParserTestCalc, - `calc.PositionTest, `calc.ErrorMessageTest, + `calc.PositionTest, `calc.ErrorMessageTest, `calc.ErrorListTest, + `cedar.CedarAst, `cedar.CedarLexer, `cedar.CedarParser, `cedar.ParserTestCedar, `spanuse.SpanUseLexer, `spanuse.SpanUseParser, `spanuse.SpanUseTest, `imp.ImpAst, `imp.ImpParser, `imp.ParserTestImp] needs := #[parsers] diff --git a/test/README.md b/test/README.md index 38d69c8..871ca65 100644 --- a/test/README.md +++ b/test/README.md @@ -12,15 +12,17 @@ CLI invocation. Generated modules are committed; do not edit them directly. | `cedarentities/CedarEntities.lig` | `cedarentities/CedarEntitiesVerified.lean` | `cedarentities/CedarEntitiesParser.lean` | `cedarentities/CedarEntitiesLexer.lean` | | `c99/c99.lig` | `c99/C99Verified.lean` | `c99/C99Parser.lean` | — (hand-written) | | `asm/asm.lig` | `asm/AsmVerified.lean` | `asm/AsmParser.lean` | `asm/AsmLexer.lean` | +| `spanuse/SpanUse.lig` | `spanuse/SpanUseVerified.lean` | `spanuse/SpanUseParser.lean` | `spanuse/SpanUseLexer.lean` | +| `rustactions/rustactions.lig` | `rustactions/RustactionsVerified.lean` | `rustactions/RustactionsParser.lean` | `rustactions/RustactionsLexer.lean` | ```sh lake build parsers # regenerate parser + lexer modules for stale non-heavy fixtures lake build heavyParsers # regenerate the heavy fixtures (c99) lake build Generated # compile executable artifacts -lake build VerifiedSmoke # compile verified smoke tests (calc, asm; default) +lake build VerifiedSmoke # compile verified smoke tests (calc, asm, spanuse; default) lake build VerifiedMid # compile + CACHE non-heavy verified + roundtrip proofs lake build VerifiedHeavy # compile + CACHE the heavy *Verified module (c99) -lake build ParserTests # calc/imp end-to-end + span/error-message/x_span tests +lake build ParserTests # calc/imp/cedar end-to-end, span/error-message/x_span, error-list tests lake build Asm # asm fixture: AST, generated lexer and parser, dump (default) lake build asm-bench # asm smoke test (--dump) and benchmark; see asm/README.md ``` @@ -61,18 +63,20 @@ Lake 5.0.0 has no `-j`; bound parallelism with `LAKE_NUM_JOBS` (e.g. The `parsers` target regenerates a fixture's modules when its grammar, the generator, or any output is newer/missing. Grammars with a `%lexer` block -(`calc`, `cedar`, `cedarschema`, `cedarentities`, `asm`) generate a lexer -module too, in the same invocation. +(`calc`, `cedar`, `cedarschema`, `cedarentities`, `asm`, `spanuse`, `rustactions`) +generate a lexer module too, in the same invocation. To proof-check the dependent specification (`*Verified`) modules, prefer the -caching `lean_lib`s over `lake env lean test//Verified.lean`. The six -non-heavy specs are rooted in `VerifiedMid` (`asm/AsmVerified.lean`, 7 s, is in -`VerifiedSmoke` instead), and the heavy one (c99) in -`VerifiedHeavy` (reached through the `heavyParsers` regeneration target); both -cache each `native_decide` certificate to `.olean`, so a rebuild after an unrelated -change is a Lake trace no-op (~0.9 s for Cedar) instead of the full re-check the -per-file `lake env lean` invocation pays every time (~230 s for Cedar). Neither is -a default target — plain `lake build` stays cheap. `VerifiedHeavy` is memory-heavy: +caching `lean_lib`s over `lake env lean test//Verified.lean`. The non-heavy +specs of calc, imp, cedar, cedarschema, cedarentities and rustactions are rooted in +`VerifiedMid`, asm (7 s) and spanuse are in `VerifiedSmoke`, calc is in both, and the +heavy one (c99) is in +`VerifiedHeavy` (reached through the `heavyParsers` regeneration target). The libraries +cache each checked module to `.olean`, so a rebuild after an unrelated change is a Lake +trace no-op (~0.9 s for Cedar) instead of the full re-check that a per-file +`lake env lean` invocation pays every time (about 17 s for Cedar on 16 cores). +`VerifiedMid` and `VerifiedHeavy` are not default targets, so plain `lake build` stays +cheap. `VerifiedHeavy` is memory-heavy: build it alone, one worker at a time (`LAKE_NUM_JOBS=1`). The `ParserTestFoo` and position/error-message tests are rooted in the `ParserTests` `lean_lib`, separate `#guard`-based behavior tests, not the proof modules. @@ -80,7 +84,7 @@ not the proof modules. ## Lexers A grammar is in one of two regimes. Grammars with a `%lexer { … }` block -(`calc`, `cedar`, `cedarschema`, `cedarentities`, `asm`) are in the +(`calc`, `cedar`, `cedarschema`, `cedarentities`, `asm`, `spanuse`, `rustactions`) are in the **generated** regime: the CLI emits the token type and the tokenizer into the lexer module (e.g. `calc/CalcLexer.lean`), with the DFA tables validated offline by `native_decide`. @@ -107,8 +111,8 @@ define `runStream`/`parseStr : String → …` with their theorems, and their corollaries (DESIGN §13), including completeness and unambiguity from the string (`parseStr_complete_lexing`, `parseStr_unambiguous`, `parseStr_*_lexes`, `parseStr_node_spans`). `PosLexerAgrees` is a theorem of every lexer module -(`posLexerAgrees`), and the dependent specification has spans, so these theorems take no -hypothesis. `spanuse`'s action reads `w_span`; `spanuse/SpanUseVerified.lean` is in +(`posLexerAgrees`), and the dependent specification has spans, so no theorem takes a +hypothesis about spans or the lexer. `spanuse`'s action reads `w_span`; `spanuse/SpanUseVerified.lean` is in `VerifiedSmoke`. `cedarschema` and `rustactions` do not opt in, and `imp` and `c99` have no `%lexer` block. @@ -137,7 +141,7 @@ args, and parent lists allow an optional trailing comma, matching the RFC's addition), so the `Annotated` wrapper always carries an empty list. Pager construction is conflict-free; `cedarentities/CedarEntitiesParser.lean` and `CedarEntitiesVerified.lean` both build, and the verified module proof-checks -(~7 s). +(about 4 s). `test/cedarentities/corpus/` holds a positive/negative corpus: `corpus/positive/*.cedarentities` must parse and `corpus/negative/*.cedarentities` @@ -184,7 +188,7 @@ Measured over 2000 iterations, per policy: |---|---|---|---|---| | Cedar `generated/` (22) | 185.3 µs | 143 µs | 66.8 µs/policy | ~2.2x vs `List Char` | -This is the honest ceiling for the scan-representation lever: a profiler +This is the limit of what changing the scan representation gives: a profiler decomposition attributes the remaining lex-only time to the flat scan (~72%), the `String.extract` lexeme (~11%), and per-token semantic actions (~18%, user code the generator cannot speed up). The flat table is `DFA.flatOfDFA` (untrusted); the diff --git a/test/asm/AsmLexer.lean b/test/asm/AsmLexer.lean index 93cc41d..d3d8e62 100644 --- a/test/asm/AsmLexer.lean +++ b/test/asm/AsmLexer.lean @@ -513,8 +513,9 @@ theorem AsmLexer.textIndep0 : ∀ r, AsmLexer.cflat.needsText 0 r = false → Lexer.FastActs.textIndep_of_forall₂ AsmLexer.fastActs (AsmLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun Lexer.Forall₂.nil)))))))))))))))))))))))))))))))))))))))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem AsmLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : AsmLexer.tokenize input = .ok ts) : Lexer.Tokenization AsmLexer.rules0 input.toList ∧ diff --git a/test/asm/AsmVerified.lean b/test/asm/AsmVerified.lean index dc2fcf9..07f81c4 100644 --- a/test/asm/AsmVerified.lean +++ b/test/asm/AsmVerified.lean @@ -3479,8 +3479,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Program) (accepted : AsmParser.parse input logNSteps = some semantic) : @@ -3505,6 +3506,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (AsmParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -3523,6 +3526,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : AsmParser.run input logNSteps ≠ .err message := by @@ -3531,6 +3535,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index @@ -3580,6 +3585,7 @@ abbrev PosLexerAgrees : Prop := Lexer.PosLexerAgrees AsmLexer.cbyte AsmLexer.tok theorem posLexerAgrees : PosLexerAgrees := AsmLexer.posLexerAgrees +/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.tokenize s = .ok ts) : Lexer.lexPos AsmLexer.cbyte s = .ok ts := by have hagree := posLexerAgrees s @@ -3589,16 +3595,21 @@ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) | error e => intro hc; simp [Except.toOption] at hc | ok v => intro hc; simp [Except.toOption] at hc; rw [hc] +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/ theorem parseStr_eq (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.tokenize s = .ok ts) : AsmParser.parseStr s k = AsmParser.parse ts k := by have hp : Lexer.lexPos AsmLexer.cbyte s = .ok ts := lexPos_eq_of_tokenize s ts h exact AsmParser.parseStr_eq_lexPos s k ts hp +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/ theorem parseStr_eq_dependent (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.tokenize s = .ok ts) : AsmParser.parseStr s k = parse ts k := by rw [parseStr_eq s k ts h, parse_eq_dependent] +/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s` + with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a + parse tree whose value is `p`. -/ theorem parseStr_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.tokenize s = .ok ts) (p : Program) (accepted : AsmParser.parseStr s k = some p) : @@ -3609,28 +3620,13 @@ theorem parseStr_sound (s : String) rw [parseStr_eq s k ts h] at accepted exact parser_sound ts k p accepted -/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr` - is `none` or `parse` of an extension of `ts`. -/ -theorem parseStr_of_tokenize_error (s : String) (k : Nat) - (e : Lexer.LexError) (h : AsmLexer.tokenize s = .error e) : - ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux AsmLexer.cbyte s.toUTF8)) - ⟨false, s.toUTF8.size + 1, 0, [AsmLexer.cbyte.flat.base.start]⟩ ts e' ∧ - ∀ tail, AsmParser.parseStr s k = none ∨ AsmParser.parseStr s k = AsmParser.parse (ts ++ tail) k := by - rcases AsmParser.parseStr_total s k with ⟨ts, hD, _⟩ | hF - · exfalso - have hp : Lexer.lexPos AsmLexer.cbyte s = .ok ts := - Lexer.lexPosAux_of_denotes AsmLexer.cbyte s.toUTF8 _ _ _ ts hD - have hagree := posLexerAgrees s - rw [hp, h] at hagree - simp [Except.toOption] at hagree - · exact hF - /-- Every production of the start symbol has the end marker `$` on its right-hand side. -/ theorem startProds_end : ∀ p : Production, prodLhs' p = startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState) → Symbol.T (⟨40, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by native_decide +/-- Only the `EOF` token has the terminal of the end marker `$`. -/ theorem tokenTerm_eq_end (t : Tok) (h : tokenTerm' t = (⟨40, of_decide_eq_true rfl⟩ : Terminal)) : t = .EOF := by cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl) @@ -3647,6 +3643,7 @@ theorem dependent_ne_parsed_of_no_eof (input : List (Runtime.Positioned Tok)) (k startProds_end input ⟨.EOF, Runtime.Span.dummy⟩ rfl (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest +/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat) (hin : ∀ t ∈ input, t.val ≠ .EOF) (hlen : 2 ^ k < input.length) : parse input k = none := by unfold parse @@ -3655,7 +3652,8 @@ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest) | _ => rfl -/-- A prefix of lexed tokens with no `EOF`, padded with copies of its first token. -/ +/-- A token list `t0 :: ts` with no `EOF`, padded with `2^k + 1` copies of `t0`, has no + `EOF` and is longer than `2^k`. -/ theorem no_eof_pad (t0 : Runtime.Positioned Tok) (ts : List (Runtime.Positioned Tok)) (hts : ∀ t ∈ t0 :: ts, t.val ≠ .EOF) (k : Nat) : (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .EOF) ∧ @@ -3741,7 +3739,8 @@ theorem runStream_ne_ok_of_tokenize_error (s : String) (k : Nat) (e : Lexer.LexE exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep /-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to - `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse + tree whose value is `p`. -/ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Program) (accepted : AsmParser.parseStr s k = some p) : ∃ ts, AsmLexer.tokenize s = .ok ts ∧ @@ -3757,8 +3756,8 @@ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Program) /-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`, then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer - returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse - tree whose value is `p`. -/ + returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Program) (accepted : AsmParser.parseStr s k = some p) : ∃ ts, AsmLexer.tokenize s = .ok ts ∧ Lexer.Tokenization AsmLexer.rules0 s.toList ∧ @@ -3773,7 +3772,8 @@ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Program) /-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token - values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of + a parse tree whose value is `p`. -/ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (p : Program) (h : AsmLexer.tokenize s = .ok ts) (accepted : AsmParser.parse ts k = some p) : Lexer.Tokenization AsmLexer.rules0 s.toList ∧ Lexer.tokenize AsmLexer.lexer s = .ok (ts.map (·.val)) ∧ @@ -3784,8 +3784,8 @@ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Position obtain ⟨htok, hspec⟩ := AsmLexer.tokenize_sound h exact ⟨htok, hspec, parser_sound ts k p accepted⟩ -/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol - spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ +/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word + exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ theorem parseStr_complete (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.tokenize s = .ok ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : @@ -3816,8 +3816,8 @@ theorem parseStr_unambiguous (s : String) {ts₁ ts₂ : List (Runtime.Positione exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩ /-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s` - (`AsmLexer.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel, - `parseStr` returns the tree's value. -/ + (`AsmLexer.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr` + returns the tree's value. -/ theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : AsmParser.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) := @@ -3839,17 +3839,17 @@ theorem parseStr_unambiguous_lexes (s : String) {ts₁ ts₂ : List (Runtime.Pos `s` (`AsmLexer.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions - `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start - of the lexeme of its first token or, when its word is empty or its leftmost children - derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/ + `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before + the node when the word is empty) and `a` is `pe` or the start of the first token of the + word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/ theorem parseStr_node_spans (s : String) (ts : List (Runtime.Positioned Tok)) (h : AsmLexer.Lexes s ts) (tree : ParserStartTree ts) : Lexer.AllNodeText (Lexer.modeAct AsmLexer.lexer AsmLexer.lexer.start) AsmLexer.lexer.eofToken s ⟨0⟩ tree := Lexer.PosLexing.allNodeText h tree /-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then - `s` has a positioned tokenization `ts` (`AsmLexer.Lexes`), and `ts` starts with the word of a - parse tree whose value is `p`. -/ + `s` has a positioned tokenization `ts` (`AsmLexer.Lexes`), and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_lexes (s : String) (k : Nat) (p : Program) (accepted : AsmParser.parseStr s k = some p) : ∃ ts, AsmLexer.Lexes s ts ∧ diff --git a/test/asm/README.md b/test/asm/README.md index 17fa988..67bc5c5 100644 --- a/test/asm/README.md +++ b/test/asm/README.md @@ -12,8 +12,8 @@ decimal/hex/binary/real literals with leading `-`, identifiers, tensor reference index expressions (`src[%g0, %g1 + 1]`), and register sets (`{%v0, %v1}`). In large files the `.code` section holds almost every token. -The grammar is 232 lines: 41 terminals (14 carry a `String` or `Nat`), 32 nonterminals -after macro expansion, 95 productions, 164 LR states, no conflict. Both backends are +The grammar is 233 lines: 41 terminals (14 carry a `String` or `Nat`), 41 nonterminals +after macro expansion, 104 productions, 172 LR states, no conflict. Both backends are generated from it: the Lean lexer, parser and `AsmVerified.lean`, and `rust/src/generated.rs`, whose `!!rust{…}` actions build the AST of `rust/src/ast.rs`. @@ -115,7 +115,8 @@ with `N` = 10 at 1 MB and 3 at 10 and 100 MB. Inputs from `gen_large.py --seed 1 | Rust | 100 MB | parse | 66.0 | 55.4 | 2.64 M | 2182 | | Rust | 100 MB | trace | 31.4 | 116.5 | 5.55 M | 2519 | -The maximum LR stack depth is 26 on all three inputs (both backends run the same tables). +The maximum LR stack depth was 26 on all three inputs when these rows were measured, before +the left-recursive list macros (#18); it is 16 now (both backends run the same tables). Per-token cost is not flat from 1 to 10 MB for any phase that parses (Lean +15% to +17%, Rust +29% to +40%); only the Rust lexer is flat. I think the 1 MB working set fits @@ -136,7 +137,7 @@ lex-only peak is 2867 MiB of the 2902 MiB lex+parse peak, and lexing takes 163 o ### Pull-based API Same host and inputs, `BENCH_ITERS=3`, all processes on core 30. "slice, HEAD" is the -driver and generated parser of commit 46d96d4, before the pull-based API; "slice, now" is +driver and generated parser before the pull-based API (a commit of #17, before it was squashed); "slice, now" is `tokenize`, `parse` and `parse_values` as they are now (wrappers over the pull-based functions); "stream" is `BENCH_STREAM=1`. Each row is the median of 5 processes, run interleaved (one process of each row in turn, 5 rounds). The spread is (max − min) / @@ -177,14 +178,15 @@ one, which parses tokens made before the timer (+3.7% at 10 MB, −2.4% at 100 M lexing on the fly costs about what reading the token vector costs; its peak RSS is the source. Streaming lex-only is faster than the slice version because it writes no vector. The maximum LR stack depth -is 26 in every row. +was 26 in every row (16 since #18). ### Lean: lexer action table and `parseStr` Same host and inputs, `BENCH_ITERS` = 10 at 1 MB and 3 at 10 and 100 MB, all processes on core 30, 5 rounds run interleaved as above; each row is the median of 5 processes and -the spread is (max − min) / median of ns/token. "list, HEAD" is `asm-bench` of commit -49afb69, before the generated lexer read its actions from `fastActs`; "list, now" is +the spread is (max − min) / median of ns/token. "list, HEAD" is `asm-bench` at a commit +of #17 (before it was squashed) from before the generated lexer read its actions from +`fastActs`; "list, now" is `tokenize` and `parse` as they are now; "stream" is `BENCH_STREAM=1` (`parseStr`). The Lean rows of the table above were measured before `fastActs` and agree with "list, HEAD" within 5%. @@ -336,7 +338,7 @@ also keeps the `VecDeque` and each entry's value on the value stack until the en `docs/DESIGN.md` (§13, "Abandoned") rejected a left-recursive rewrite of the list rules: about 3% slower on the Cedar corpus and about 2% faster on a synthetic 2000-element list, -and it says deep right recursion costs memory, not time. On this fixture's list of +and it said deep right recursion costs memory, not time. On this fixture's list of 4.76 M entries, right recursion costs both: 6–8% of the Lean time and 21–24% of the Rust time (lex+parse and parse only), on top of the memory. diff --git a/test/c99/C99Verified.lean b/test/c99/C99Verified.lean index 2d5d215..18530fe 100644 --- a/test/c99/C99Verified.lean +++ b/test/c99/C99Verified.lean @@ -5809,8 +5809,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : TranslationUnit) (accepted : C99Parser.parse input logNSteps = some semantic) : @@ -5835,6 +5836,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (C99Parser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -5853,6 +5856,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : C99Parser.run input logNSteps ≠ .err message := by @@ -5861,6 +5865,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index diff --git a/test/calc/CalcLexer.lean b/test/calc/CalcLexer.lean index 15fc6fa..6e23899 100644 --- a/test/calc/CalcLexer.lean +++ b/test/calc/CalcLexer.lean @@ -172,8 +172,9 @@ theorem CalcLexer.textIndep0 : ∀ r, CalcLexer.cflat.needsText 0 r = false → Lexer.FastActs.textIndep_of_forall₂ CalcLexer.fastActs (CalcLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) Lexer.Forall₂.nil))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem CalcLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : CalcLexer.tokenize input = .ok ts) : Lexer.Tokenization CalcLexer.rules0 input.toList ∧ diff --git a/test/calc/CalcVerified.lean b/test/calc/CalcVerified.lean index a77c72b..34d621f 100644 --- a/test/calc/CalcVerified.lean +++ b/test/calc/CalcVerified.lean @@ -983,8 +983,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Int) (accepted : CalcParser.parse input logNSteps = some semantic) : @@ -1009,6 +1010,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (CalcParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -1027,6 +1030,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : CalcParser.run input logNSteps ≠ .err message := by @@ -1035,6 +1039,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index @@ -1084,6 +1089,7 @@ abbrev PosLexerAgrees : Prop := Lexer.PosLexerAgrees CalcLexer.cbyte CalcLexer.t theorem posLexerAgrees : PosLexerAgrees := CalcLexer.posLexerAgrees +/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.tokenize s = .ok ts) : Lexer.lexPos CalcLexer.cbyte s = .ok ts := by have hagree := posLexerAgrees s @@ -1093,16 +1099,21 @@ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) | error e => intro hc; simp [Except.toOption] at hc | ok v => intro hc; simp [Except.toOption] at hc; rw [hc] +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/ theorem parseStr_eq (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.tokenize s = .ok ts) : CalcParser.parseStr s k = CalcParser.parse ts k := by have hp : Lexer.lexPos CalcLexer.cbyte s = .ok ts := lexPos_eq_of_tokenize s ts h exact CalcParser.parseStr_eq_lexPos s k ts hp +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/ theorem parseStr_eq_dependent (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.tokenize s = .ok ts) : CalcParser.parseStr s k = parse ts k := by rw [parseStr_eq s k ts h, parse_eq_dependent] +/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s` + with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a + parse tree whose value is `p`. -/ theorem parseStr_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.tokenize s = .ok ts) (p : Int) (accepted : CalcParser.parseStr s k = some p) : @@ -1113,28 +1124,13 @@ theorem parseStr_sound (s : String) rw [parseStr_eq s k ts h] at accepted exact parser_sound ts k p accepted -/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr` - is `none` or `parse` of an extension of `ts`. -/ -theorem parseStr_of_tokenize_error (s : String) (k : Nat) - (e : Lexer.LexError) (h : CalcLexer.tokenize s = .error e) : - ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux CalcLexer.cbyte s.toUTF8)) - ⟨false, s.toUTF8.size + 1, 0, [CalcLexer.cbyte.flat.base.start]⟩ ts e' ∧ - ∀ tail, CalcParser.parseStr s k = none ∨ CalcParser.parseStr s k = CalcParser.parse (ts ++ tail) k := by - rcases CalcParser.parseStr_total s k with ⟨ts, hD, _⟩ | hF - · exfalso - have hp : Lexer.lexPos CalcLexer.cbyte s = .ok ts := - Lexer.lexPosAux_of_denotes CalcLexer.cbyte s.toUTF8 _ _ _ ts hD - have hagree := posLexerAgrees s - rw [hp, h] at hagree - simp [Except.toOption] at hagree - · exact hF - /-- Every production of the start symbol has the end marker `$` on its right-hand side. -/ theorem startProds_end : ∀ p : Production, prodLhs' p = startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState) → Symbol.T (⟨7, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by native_decide +/-- Only the `EOF` token has the terminal of the end marker `$`. -/ theorem tokenTerm_eq_end (t : Tok) (h : tokenTerm' t = (⟨7, of_decide_eq_true rfl⟩ : Terminal)) : t = .EOF := by cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl) @@ -1151,6 +1147,7 @@ theorem dependent_ne_parsed_of_no_eof (input : List (Runtime.Positioned Tok)) (k startProds_end input ⟨.EOF, Runtime.Span.dummy⟩ rfl (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest +/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat) (hin : ∀ t ∈ input, t.val ≠ .EOF) (hlen : 2 ^ k < input.length) : parse input k = none := by unfold parse @@ -1159,7 +1156,8 @@ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest) | _ => rfl -/-- A prefix of lexed tokens with no `EOF`, padded with copies of its first token. -/ +/-- A token list `t0 :: ts` with no `EOF`, padded with `2^k + 1` copies of `t0`, has no + `EOF` and is longer than `2^k`. -/ theorem no_eof_pad (t0 : Runtime.Positioned Tok) (ts : List (Runtime.Positioned Tok)) (hts : ∀ t ∈ t0 :: ts, t.val ≠ .EOF) (k : Nat) : (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .EOF) ∧ @@ -1245,7 +1243,8 @@ theorem runStream_ne_ok_of_tokenize_error (s : String) (k : Nat) (e : Lexer.LexE exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep /-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to - `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse + tree whose value is `p`. -/ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Int) (accepted : CalcParser.parseStr s k = some p) : ∃ ts, CalcLexer.tokenize s = .ok ts ∧ @@ -1261,8 +1260,8 @@ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Int) /-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`, then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer - returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse - tree whose value is `p`. -/ + returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Int) (accepted : CalcParser.parseStr s k = some p) : ∃ ts, CalcLexer.tokenize s = .ok ts ∧ Lexer.Tokenization CalcLexer.rules0 s.toList ∧ @@ -1277,7 +1276,8 @@ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Int) /-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token - values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of + a parse tree whose value is `p`. -/ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (p : Int) (h : CalcLexer.tokenize s = .ok ts) (accepted : CalcParser.parse ts k = some p) : Lexer.Tokenization CalcLexer.rules0 s.toList ∧ Lexer.tokenize CalcLexer.lexer s = .ok (ts.map (·.val)) ∧ @@ -1288,8 +1288,8 @@ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Position obtain ⟨htok, hspec⟩ := CalcLexer.tokenize_sound h exact ⟨htok, hspec, parser_sound ts k p accepted⟩ -/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol - spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ +/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word + exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ theorem parseStr_complete (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.tokenize s = .ok ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : @@ -1320,8 +1320,8 @@ theorem parseStr_unambiguous (s : String) {ts₁ ts₂ : List (Runtime.Positione exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩ /-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s` - (`CalcLexer.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel, - `parseStr` returns the tree's value. -/ + (`CalcLexer.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr` + returns the tree's value. -/ theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : CalcParser.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) := @@ -1343,17 +1343,17 @@ theorem parseStr_unambiguous_lexes (s : String) {ts₁ ts₂ : List (Runtime.Pos `s` (`CalcLexer.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions - `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start - of the lexeme of its first token or, when its word is empty or its leftmost children - derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/ + `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before + the node when the word is empty) and `a` is `pe` or the start of the first token of the + word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/ theorem parseStr_node_spans (s : String) (ts : List (Runtime.Positioned Tok)) (h : CalcLexer.Lexes s ts) (tree : ParserStartTree ts) : Lexer.AllNodeText (Lexer.modeAct CalcLexer.lexer CalcLexer.lexer.start) CalcLexer.lexer.eofToken s ⟨0⟩ tree := Lexer.PosLexing.allNodeText h tree /-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then - `s` has a positioned tokenization `ts` (`CalcLexer.Lexes`), and `ts` starts with the word of a - parse tree whose value is `p`. -/ + `s` has a positioned tokenization `ts` (`CalcLexer.Lexes`), and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_lexes (s : String) (k : Nat) (p : Int) (accepted : CalcParser.parseStr s k = some p) : ∃ ts, CalcLexer.Lexes s ts ∧ diff --git a/test/calc/ErrorListTest.lean b/test/calc/ErrorListTest.lean index 47a1f05..b00b122 100644 --- a/test/calc/ErrorListTest.lean +++ b/test/calc/ErrorListTest.lean @@ -23,6 +23,10 @@ Run with: `lake env lean test/calc/ErrorListTest.lean` -/ public import LeanParserGenerator.Emit.ErrorList public import LeanParserGenerator.Frontend.File +-- `#guard` evaluates at the meta phase, so the frontend and the enumerator are also +-- `meta`-imported. +meta import LeanParserGenerator.Emit.ErrorList +meta import LeanParserGenerator.Frontend.File public section @@ -55,7 +59,7 @@ def tinyErrorStates : Array ErrorState := -- The initial state (0) expects `A` and nothing has an empty expected set here. #guard tinyErrorStates.any (fun es => es.state == 0 && es.expected.contains "A") --- Every listed error state genuinely rejects at least one terminal and accepts +-- Every listed error state rejects at least one terminal and accepts -- at least one (a well-formed `.messages` template entry). #guard tinyErrorStates.all (fun es => es.rejecting.size > 0 && es.expected.size > 0) diff --git a/test/cedar/CedarLexer.lean b/test/cedar/CedarLexer.lean index c16a3ba..f09e9d6 100644 --- a/test/cedar/CedarLexer.lean +++ b/test/cedar/CedarLexer.lean @@ -404,8 +404,9 @@ theorem CedarLexer.textIndep0 : ∀ r, CedarLexer.cflat.needsText 0 r = false Lexer.FastActs.textIndep_of_forall₂ CedarLexer.fastActs (CedarLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) Lexer.Forall₂.nil))))))))))))))))))))))))))))))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem CedarLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : CedarLexer.tokenize input = .ok ts) : Lexer.Tokenization CedarLexer.rules0 input.toList ∧ diff --git a/test/cedar/CedarVerified.lean b/test/cedar/CedarVerified.lean index aaefc32..c4b16e7 100644 --- a/test/cedar/CedarVerified.lean +++ b/test/cedar/CedarVerified.lean @@ -7834,8 +7834,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Policies) (accepted : CedarParser.parse input logNSteps = some semantic) : @@ -7860,6 +7861,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (CedarParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -7878,6 +7881,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : CedarParser.run input logNSteps ≠ .err message := by @@ -7886,6 +7890,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index @@ -7935,6 +7940,7 @@ abbrev PosLexerAgrees : Prop := Lexer.PosLexerAgrees CedarLexer.cbyte CedarLexer theorem posLexerAgrees : PosLexerAgrees := CedarLexer.posLexerAgrees +/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.tokenize s = .ok ts) : Lexer.lexPos CedarLexer.cbyte s = .ok ts := by have hagree := posLexerAgrees s @@ -7944,16 +7950,21 @@ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) | error e => intro hc; simp [Except.toOption] at hc | ok v => intro hc; simp [Except.toOption] at hc; rw [hc] +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/ theorem parseStr_eq (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.tokenize s = .ok ts) : CedarParser.parseStr s k = CedarParser.parse ts k := by have hp : Lexer.lexPos CedarLexer.cbyte s = .ok ts := lexPos_eq_of_tokenize s ts h exact CedarParser.parseStr_eq_lexPos s k ts hp +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/ theorem parseStr_eq_dependent (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.tokenize s = .ok ts) : CedarParser.parseStr s k = parse ts k := by rw [parseStr_eq s k ts h, parse_eq_dependent] +/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s` + with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a + parse tree whose value is `p`. -/ theorem parseStr_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.tokenize s = .ok ts) (p : Policies) (accepted : CedarParser.parseStr s k = some p) : @@ -7964,28 +7975,13 @@ theorem parseStr_sound (s : String) rw [parseStr_eq s k ts h] at accepted exact parser_sound ts k p accepted -/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr` - is `none` or `parse` of an extension of `ts`. -/ -theorem parseStr_of_tokenize_error (s : String) (k : Nat) - (e : Lexer.LexError) (h : CedarLexer.tokenize s = .error e) : - ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux CedarLexer.cbyte s.toUTF8)) - ⟨false, s.toUTF8.size + 1, 0, [CedarLexer.cbyte.flat.base.start]⟩ ts e' ∧ - ∀ tail, CedarParser.parseStr s k = none ∨ CedarParser.parseStr s k = CedarParser.parse (ts ++ tail) k := by - rcases CedarParser.parseStr_total s k with ⟨ts, hD, _⟩ | hF - · exfalso - have hp : Lexer.lexPos CedarLexer.cbyte s = .ok ts := - Lexer.lexPosAux_of_denotes CedarLexer.cbyte s.toUTF8 _ _ _ ts hD - have hagree := posLexerAgrees s - rw [hp, h] at hagree - simp [Except.toOption] at hagree - · exact hF - /-- Every production of the start symbol has the end marker `$` on its right-hand side. -/ theorem startProds_end : ∀ p : Production, prodLhs' p = startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState) → Symbol.T (⟨51, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by native_decide +/-- Only the `EOF` token has the terminal of the end marker `$`. -/ theorem tokenTerm_eq_end (t : Tok) (h : tokenTerm' t = (⟨51, of_decide_eq_true rfl⟩ : Terminal)) : t = .EOF := by cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl) @@ -8002,6 +7998,7 @@ theorem dependent_ne_parsed_of_no_eof (input : List (Runtime.Positioned Tok)) (k startProds_end input ⟨.EOF, Runtime.Span.dummy⟩ rfl (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest +/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat) (hin : ∀ t ∈ input, t.val ≠ .EOF) (hlen : 2 ^ k < input.length) : parse input k = none := by unfold parse @@ -8010,7 +8007,8 @@ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest) | _ => rfl -/-- A prefix of lexed tokens with no `EOF`, padded with copies of its first token. -/ +/-- A token list `t0 :: ts` with no `EOF`, padded with `2^k + 1` copies of `t0`, has no + `EOF` and is longer than `2^k`. -/ theorem no_eof_pad (t0 : Runtime.Positioned Tok) (ts : List (Runtime.Positioned Tok)) (hts : ∀ t ∈ t0 :: ts, t.val ≠ .EOF) (k : Nat) : (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .EOF) ∧ @@ -8096,7 +8094,8 @@ theorem runStream_ne_ok_of_tokenize_error (s : String) (k : Nat) (e : Lexer.LexE exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep /-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to - `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse + tree whose value is `p`. -/ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Policies) (accepted : CedarParser.parseStr s k = some p) : ∃ ts, CedarLexer.tokenize s = .ok ts ∧ @@ -8112,8 +8111,8 @@ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Policies) /-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`, then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer - returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse - tree whose value is `p`. -/ + returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Policies) (accepted : CedarParser.parseStr s k = some p) : ∃ ts, CedarLexer.tokenize s = .ok ts ∧ Lexer.Tokenization CedarLexer.rules0 s.toList ∧ @@ -8128,7 +8127,8 @@ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Policies) /-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token - values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of + a parse tree whose value is `p`. -/ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (p : Policies) (h : CedarLexer.tokenize s = .ok ts) (accepted : CedarParser.parse ts k = some p) : Lexer.Tokenization CedarLexer.rules0 s.toList ∧ Lexer.tokenize CedarLexer.lexer s = .ok (ts.map (·.val)) ∧ @@ -8139,8 +8139,8 @@ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Position obtain ⟨htok, hspec⟩ := CedarLexer.tokenize_sound h exact ⟨htok, hspec, parser_sound ts k p accepted⟩ -/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol - spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ +/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word + exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ theorem parseStr_complete (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.tokenize s = .ok ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : @@ -8171,8 +8171,8 @@ theorem parseStr_unambiguous (s : String) {ts₁ ts₂ : List (Runtime.Positione exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩ /-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s` - (`CedarLexer.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel, - `parseStr` returns the tree's value. -/ + (`CedarLexer.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr` + returns the tree's value. -/ theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : CedarParser.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) := @@ -8194,17 +8194,17 @@ theorem parseStr_unambiguous_lexes (s : String) {ts₁ ts₂ : List (Runtime.Pos `s` (`CedarLexer.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions - `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start - of the lexeme of its first token or, when its word is empty or its leftmost children - derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/ + `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before + the node when the word is empty) and `a` is `pe` or the start of the first token of the + word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/ theorem parseStr_node_spans (s : String) (ts : List (Runtime.Positioned Tok)) (h : CedarLexer.Lexes s ts) (tree : ParserStartTree ts) : Lexer.AllNodeText (Lexer.modeAct CedarLexer.lexer CedarLexer.lexer.start) CedarLexer.lexer.eofToken s ⟨0⟩ tree := Lexer.PosLexing.allNodeText h tree /-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then - `s` has a positioned tokenization `ts` (`CedarLexer.Lexes`), and `ts` starts with the word of a - parse tree whose value is `p`. -/ + `s` has a positioned tokenization `ts` (`CedarLexer.Lexes`), and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_lexes (s : String) (k : Nat) (p : Policies) (accepted : CedarParser.parseStr s k = some p) : ∃ ts, CedarLexer.Lexes s ts ∧ diff --git a/test/cedar/ParserTestCedar.lean b/test/cedar/ParserTestCedar.lean index ba7e6c2..e08e844 100644 --- a/test/cedar/ParserTestCedar.lean +++ b/test/cedar/ParserTestCedar.lean @@ -72,9 +72,9 @@ private def rootPrimary (expression : Expr) : Option Primary := do private def tokenizerParity : Bool := match CedarLexer.tokenize "permit ?principal ?resource ?other foo 123 \"a\\\"b\" == != <= >= :: =" with - | .ok tokens => tokens == + | .ok tokens => tokens.map (·.val) == [.PERMIT, .PRINCIPAL_SLOT, .RESOURCE_SLOT, .OTHER_SLOT "?other", - .IDENTIFIER "foo", .NUMBER 123, .STRINGLIT "a\\\"b", .EQ, .NEQ, .LEQ, + .IDENTIFIER ⟨"foo", by decide⟩, .NUMBER 123, .STRINGLIT "a\\\"b", .EQ, .NEQ, .LEQ, .GEQ, .COLONCOLON, .SINGLE_EQ, .EOF] | .error _ => false @@ -82,14 +82,14 @@ example : tokenizerParity = true := by native_decide private def commentParity : Bool := match CedarLexer.tokenize "// comment\r\ntrue" with - | .ok tokens => tokens == [.TRUE, .EOF] + | .ok tokens => tokens.map (·.val) == [.TRUE, .EOF] | .error _ => false example : commentParity = true := by native_decide private def multilineStringParity : Bool := match CedarLexer.tokenize "\"line one\nline two\"" with - | .ok tokens => tokens == [.STRINGLIT "line one\nline two", .EOF] + | .ok tokens => tokens.map (·.val) == [.STRINGLIT "line one\nline two", .EOF] | .error _ => false example : multilineStringParity = true := by native_decide diff --git a/test/cedarentities/CedarEntitiesLexer.lean b/test/cedarentities/CedarEntitiesLexer.lean index 51338ae..1de3745 100644 --- a/test/cedarentities/CedarEntitiesLexer.lean +++ b/test/cedarentities/CedarEntitiesLexer.lean @@ -259,8 +259,9 @@ theorem CedarEntitiesLexer.textIndep0 : ∀ r, CedarEntitiesLexer.cflat.needsTex Lexer.FastActs.textIndep_of_forall₂ CedarEntitiesLexer.fastActs (CedarEntitiesLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) Lexer.Forall₂.nil))))))))))))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem CedarEntitiesLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : CedarEntitiesLexer.tokenize input = .ok ts) : Lexer.Tokenization CedarEntitiesLexer.rules0 input.toList ∧ diff --git a/test/cedarentities/CedarEntitiesVerified.lean b/test/cedarentities/CedarEntitiesVerified.lean index 6e34971..adbd83c 100644 --- a/test/cedarentities/CedarEntitiesVerified.lean +++ b/test/cedarentities/CedarEntitiesVerified.lean @@ -2063,8 +2063,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Entities) (accepted : CedarEntitiesParser.parse input logNSteps = some semantic) : @@ -2089,6 +2090,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (CedarEntitiesParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -2107,6 +2110,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : CedarEntitiesParser.run input logNSteps ≠ .err message := by @@ -2115,6 +2119,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index @@ -2164,6 +2169,7 @@ abbrev PosLexerAgrees : Prop := Lexer.PosLexerAgrees CedarEntitiesLexer.cbyte Ce theorem posLexerAgrees : PosLexerAgrees := CedarEntitiesLexer.posLexerAgrees +/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.tokenize s = .ok ts) : Lexer.lexPos CedarEntitiesLexer.cbyte s = .ok ts := by have hagree := posLexerAgrees s @@ -2173,16 +2179,21 @@ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) | error e => intro hc; simp [Except.toOption] at hc | ok v => intro hc; simp [Except.toOption] at hc; rw [hc] +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/ theorem parseStr_eq (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.tokenize s = .ok ts) : CedarEntitiesParser.parseStr s k = CedarEntitiesParser.parse ts k := by have hp : Lexer.lexPos CedarEntitiesLexer.cbyte s = .ok ts := lexPos_eq_of_tokenize s ts h exact CedarEntitiesParser.parseStr_eq_lexPos s k ts hp +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/ theorem parseStr_eq_dependent (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.tokenize s = .ok ts) : CedarEntitiesParser.parseStr s k = parse ts k := by rw [parseStr_eq s k ts h, parse_eq_dependent] +/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s` + with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a + parse tree whose value is `p`. -/ theorem parseStr_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.tokenize s = .ok ts) (p : Entities) (accepted : CedarEntitiesParser.parseStr s k = some p) : @@ -2193,28 +2204,13 @@ theorem parseStr_sound (s : String) rw [parseStr_eq s k ts h] at accepted exact parser_sound ts k p accepted -/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr` - is `none` or `parse` of an extension of `ts`. -/ -theorem parseStr_of_tokenize_error (s : String) (k : Nat) - (e : Lexer.LexError) (h : CedarEntitiesLexer.tokenize s = .error e) : - ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux CedarEntitiesLexer.cbyte s.toUTF8)) - ⟨false, s.toUTF8.size + 1, 0, [CedarEntitiesLexer.cbyte.flat.base.start]⟩ ts e' ∧ - ∀ tail, CedarEntitiesParser.parseStr s k = none ∨ CedarEntitiesParser.parseStr s k = CedarEntitiesParser.parse (ts ++ tail) k := by - rcases CedarEntitiesParser.parseStr_total s k with ⟨ts, hD, _⟩ | hF - · exfalso - have hp : Lexer.lexPos CedarEntitiesLexer.cbyte s = .ok ts := - Lexer.lexPosAux_of_denotes CedarEntitiesLexer.cbyte s.toUTF8 _ _ _ ts hD - have hagree := posLexerAgrees s - rw [hp, h] at hagree - simp [Except.toOption] at hagree - · exact hF - /-- Every production of the start symbol has the end marker `$` on its right-hand side. -/ theorem startProds_end : ∀ p : Production, prodLhs' p = startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState) → Symbol.T (⟨22, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by native_decide +/-- Only the `EOF` token has the terminal of the end marker `$`. -/ theorem tokenTerm_eq_end (t : Tok) (h : tokenTerm' t = (⟨22, of_decide_eq_true rfl⟩ : Terminal)) : t = .EOF := by cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl) @@ -2231,6 +2227,7 @@ theorem dependent_ne_parsed_of_no_eof (input : List (Runtime.Positioned Tok)) (k startProds_end input ⟨.EOF, Runtime.Span.dummy⟩ rfl (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest +/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat) (hin : ∀ t ∈ input, t.val ≠ .EOF) (hlen : 2 ^ k < input.length) : parse input k = none := by unfold parse @@ -2239,7 +2236,8 @@ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest) | _ => rfl -/-- A prefix of lexed tokens with no `EOF`, padded with copies of its first token. -/ +/-- A token list `t0 :: ts` with no `EOF`, padded with `2^k + 1` copies of `t0`, has no + `EOF` and is longer than `2^k`. -/ theorem no_eof_pad (t0 : Runtime.Positioned Tok) (ts : List (Runtime.Positioned Tok)) (hts : ∀ t ∈ t0 :: ts, t.val ≠ .EOF) (k : Nat) : (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .EOF) ∧ @@ -2325,7 +2323,8 @@ theorem runStream_ne_ok_of_tokenize_error (s : String) (k : Nat) (e : Lexer.LexE exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep /-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to - `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse + tree whose value is `p`. -/ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Entities) (accepted : CedarEntitiesParser.parseStr s k = some p) : ∃ ts, CedarEntitiesLexer.tokenize s = .ok ts ∧ @@ -2341,8 +2340,8 @@ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Entities) /-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`, then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer - returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse - tree whose value is `p`. -/ + returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Entities) (accepted : CedarEntitiesParser.parseStr s k = some p) : ∃ ts, CedarEntitiesLexer.tokenize s = .ok ts ∧ Lexer.Tokenization CedarEntitiesLexer.rules0 s.toList ∧ @@ -2357,7 +2356,8 @@ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Entities) /-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token - values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of + a parse tree whose value is `p`. -/ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (p : Entities) (h : CedarEntitiesLexer.tokenize s = .ok ts) (accepted : CedarEntitiesParser.parse ts k = some p) : Lexer.Tokenization CedarEntitiesLexer.rules0 s.toList ∧ Lexer.tokenize CedarEntitiesLexer.lexer s = .ok (ts.map (·.val)) ∧ @@ -2368,8 +2368,8 @@ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Position obtain ⟨htok, hspec⟩ := CedarEntitiesLexer.tokenize_sound h exact ⟨htok, hspec, parser_sound ts k p accepted⟩ -/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol - spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ +/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word + exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ theorem parseStr_complete (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.tokenize s = .ok ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : @@ -2400,8 +2400,8 @@ theorem parseStr_unambiguous (s : String) {ts₁ ts₂ : List (Runtime.Positione exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩ /-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s` - (`CedarEntitiesLexer.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel, - `parseStr` returns the tree's value. -/ + (`CedarEntitiesLexer.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr` + returns the tree's value. -/ theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : CedarEntitiesParser.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) := @@ -2423,17 +2423,17 @@ theorem parseStr_unambiguous_lexes (s : String) {ts₁ ts₂ : List (Runtime.Pos `s` (`CedarEntitiesLexer.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions - `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start - of the lexeme of its first token or, when its word is empty or its leftmost children - derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/ + `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before + the node when the word is empty) and `a` is `pe` or the start of the first token of the + word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/ theorem parseStr_node_spans (s : String) (ts : List (Runtime.Positioned Tok)) (h : CedarEntitiesLexer.Lexes s ts) (tree : ParserStartTree ts) : Lexer.AllNodeText (Lexer.modeAct CedarEntitiesLexer.lexer CedarEntitiesLexer.lexer.start) CedarEntitiesLexer.lexer.eofToken s ⟨0⟩ tree := Lexer.PosLexing.allNodeText h tree /-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then - `s` has a positioned tokenization `ts` (`CedarEntitiesLexer.Lexes`), and `ts` starts with the word of a - parse tree whose value is `p`. -/ + `s` has a positioned tokenization `ts` (`CedarEntitiesLexer.Lexes`), and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_lexes (s : String) (k : Nat) (p : Entities) (accepted : CedarEntitiesParser.parseStr s k = some p) : ∃ ts, CedarEntitiesLexer.Lexes s ts ∧ diff --git a/test/cedarschema/CedarSchemaAst.lean b/test/cedarschema/CedarSchemaAst.lean index 71ff78d..a40615f 100644 --- a/test/cedarschema/CedarSchemaAst.lean +++ b/test/cedarschema/CedarSchemaAst.lean @@ -16,7 +16,7 @@ module /- -`test/cedar-schema/CedarSchemaAst.lean` — the Cedar schema concrete syntax tree +`test/cedarschema/CedarSchemaAst.lean` — the Cedar schema concrete syntax tree and token type. This mirrors `cedar-policy-core/src/validator/cedar_schema/ast.rs` and the diff --git a/test/cedarschema/CedarSchemaLexer.lean b/test/cedarschema/CedarSchemaLexer.lean index 4e76cab..b14f0c6 100644 --- a/test/cedarschema/CedarSchemaLexer.lean +++ b/test/cedarschema/CedarSchemaLexer.lean @@ -287,8 +287,9 @@ theorem CedarSchemaLexer.textIndep0 : ∀ r, CedarSchemaLexer.cflat.needsText 0 Lexer.FastActs.textIndep_of_forall₂ CedarSchemaLexer.fastActs (CedarSchemaLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) Lexer.Forall₂.nil)))))))))))))))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem CedarSchemaLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : CedarSchemaLexer.tokenize input = .ok ts) : Lexer.Tokenization CedarSchemaLexer.rules0 input.toList ∧ diff --git a/test/cedarschema/CedarSchemaVerified.lean b/test/cedarschema/CedarSchemaVerified.lean index 45d2920..cb6d383 100644 --- a/test/cedarschema/CedarSchemaVerified.lean +++ b/test/cedarschema/CedarSchemaVerified.lean @@ -5793,8 +5793,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Schema) (accepted : CedarSchemaParser.parse input logNSteps = some semantic) : @@ -5819,6 +5820,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (CedarSchemaParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -5837,6 +5840,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : CedarSchemaParser.run input logNSteps ≠ .err message := by @@ -5845,6 +5849,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index diff --git a/test/cli/CliTest.lean b/test/cli/CliTest.lean index 24939b5..6e03744 100644 --- a/test/cli/CliTest.lean +++ b/test/cli/CliTest.lean @@ -161,6 +161,7 @@ def main : IO UInt32 := do usageErr "a flag without its value" ["a.lig", "--out-dir"] "`--out-dir` needs a value" usageErr "-v without --rust-report" ["-v", "a.lig"] "`-v` is only meaningful with `--rust-report`" usageErr "--print-grammar with --rust-report" ["--print-grammar", "bnf", "--rust-report", "a.lig"] "`--print-grammar` and `--rust-report` cannot be combined" + usageErr "--list-errors with --print-grammar" ["--list-errors", "--print-grammar", "bnf", "a.lig"] "only one of `--print-grammar`, `--list-errors` and `--rust-report` can be given" -- Input errors: exit 1 and no uncaught exception. let d ← fresh [("sub/x", "")] @@ -223,6 +224,12 @@ def main : IO UInt32 := do let r ← run d ["sub/expr.lig"] check "%option gen_rust is relative to the .lig" (r.code == 0 && (← has d "sub/rust/gen.rs") && (← has d "sub/ExprParser.lean")) r.err + -- The `wrote` lines name the module with its prefix. + let d ← fresh [("expr.lig", "%option module_prefix MyProject\n" ++ lexerGrammar)] + let r ← run d ["expr.lig"] + check "wrote lines give the dotted module name" + (r.code == 0 && contains r.out "(module MyProject.ExprParser)" && contains r.out "(module MyProject.ExprLexer)") r.out + -- Grammar inspection writes no files. let d ← fresh [("expr.lig", lexerGrammar)] let r ← run d ["--print-grammar", "bnf", "expr.lig"] @@ -230,6 +237,10 @@ def main : IO UInt32 := do (r.code == 0 && contains r.out "expr" && contains r.out "PLUS" && !(← has d "ExprParser.lean")) r.err let r ← run d ["--print-grammar", "markdown", "expr.lig"] check "--print-grammar markdown" (r.code == 0 && r.out.length > 0 && !(← has d "ExprParser.lean")) r.err + let r ← run d ["--list-errors", "expr.lig"] + check "--list-errors prints the error states and writes nothing" + (r.code == 0 && contains r.out "## State " && contains r.out "## expected one of:" && + contains r.out "" && !(← has d "ExprParser.lean")) r.err -- A `.lig` file name has to give valid module names. for bad in ["my-grammar.lig", "two words.lig", "1calc.lig", "calc.v2.lig", ".lig", "ünï.lig"] do diff --git a/test/imp/ImpVerified.lean b/test/imp/ImpVerified.lean index b9ac872..499cb0e 100644 --- a/test/imp/ImpVerified.lean +++ b/test/imp/ImpVerified.lean @@ -2042,8 +2042,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Com) (accepted : ImpParser.parse input logNSteps = some semantic) : @@ -2068,6 +2069,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (ImpParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -2086,6 +2089,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : ImpParser.run input logNSteps ≠ .err message := by @@ -2094,6 +2098,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index diff --git a/test/lig/BootstrapAgreementTest.lean b/test/lig/BootstrapAgreementTest.lean index f5d9cce..92d789f 100644 --- a/test/lig/BootstrapAgreementTest.lean +++ b/test/lig/BootstrapAgreementTest.lean @@ -19,7 +19,7 @@ public import LeanParserGenerator.Frontend.File public import LeanParserGenerator.Frontend.LigParse /- `test/lig/BootstrapAgreementTest.lean` — checks that the bootstrapped `.lig` -frontend agrees with the hand-written one (DESIGN §15.4). +frontend agrees with the hand-written one (DESIGN §15). For every `.lig` file in the repository (the fixtures plus the `.lig` grammar's own `lig.lig`), the hand-written `Frontend.parseLig` and the generated @@ -62,8 +62,9 @@ private def norm : Except String Surface → String def ligFiles : List String := [ "test/calc/calc.lig", "test/imp/imp.lig", "test/cedar/cedar.lig", - "test/cedarschema/CedarSchema.lig", "test/c99/c99.lig", - "test/rustactions/rustactions.lig", "test/asm/asm.lig", + "test/cedarschema/CedarSchema.lig", "test/cedarentities/CedarEntities.lig", + "test/c99/c99.lig", "test/rustactions/rustactions.lig", "test/asm/asm.lig", + "test/spanuse/SpanUse.lig", "LeanParserGenerator/Frontend/lig.lig" ] /-- A grammar around one rule, for the shapes of `!!rust{…}` that the fixtures do not cover. -/ diff --git a/test/rustactions/RustActionsAst.lean b/test/rustactions/RustactionsAst.lean similarity index 100% rename from test/rustactions/RustActionsAst.lean rename to test/rustactions/RustactionsAst.lean diff --git a/test/rustactions/RustactionsLexer.lean b/test/rustactions/RustactionsLexer.lean index 2666539..78213ad 100644 --- a/test/rustactions/RustactionsLexer.lean +++ b/test/rustactions/RustactionsLexer.lean @@ -22,7 +22,7 @@ meta import LeanParserGenerator.Lexer.FlatTokenize meta import LeanParserGenerator.Lexer.ByteAgree -public import rustactions.RustActionsAst +public import rustactions.RustactionsAst open RustActions @@ -259,8 +259,9 @@ theorem RustactionsLexer.textIndep0 : ∀ r, RustactionsLexer.cflat.needsText 0 Lexer.FastActs.textIndep_of_forall₂ RustactionsLexer.fastActs (RustactionsLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons nofun Lexer.Forall₂.nil))))))))))))))))))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem RustactionsLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : RustactionsLexer.tokenize input = .ok ts) : Lexer.Tokenization RustactionsLexer.rules0 input.toList ∧ diff --git a/test/rustactions/RustactionsParser.lean b/test/rustactions/RustactionsParser.lean index 5c7b2b4..44541c5 100644 --- a/test/rustactions/RustactionsParser.lean +++ b/test/rustactions/RustactionsParser.lean @@ -15,7 +15,7 @@ public import LeanParserGenerator.Runtime.Diagnostic public import rustactions.RustactionsLexer -public import rustactions.RustActionsAst +public import rustactions.RustactionsAst open RustActions diff --git a/test/rustactions/RustactionsVerified.lean b/test/rustactions/RustactionsVerified.lean index 5290160..b884f3f 100644 --- a/test/rustactions/RustactionsVerified.lean +++ b/test/rustactions/RustactionsVerified.lean @@ -33,7 +33,7 @@ meta import rustactions.RustactionsParser public import rustactions.RustactionsLexer -public import rustactions.RustActionsAst +public import rustactions.RustactionsAst open RustActions @@ -1347,8 +1347,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Program) (accepted : RustactionsParser.parse input logNSteps = some semantic) : @@ -1373,6 +1374,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (RustactionsParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -1391,6 +1394,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : RustactionsParser.run input logNSteps ≠ .err message := by @@ -1399,6 +1403,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index diff --git a/test/rustactions/rustactions.lig b/test/rustactions/rustactions.lig index f3a2f4f..b518d53 100644 --- a/test/rustactions/rustactions.lig +++ b/test/rustactions/rustactions.lig @@ -3,7 +3,7 @@ -- `separated_list_trailing(…)` is a macro (a call accepts a trailing comma): its Rust -- counterpart is a `Vec` (docs/RUST_PARSER.md, D21). %header { -import rustactions.RustActionsAst +import rustactions.RustactionsAst open RustActions } %option module_prefix rustactions diff --git a/test/spanuse/SpanUseLexer.lean b/test/spanuse/SpanUseLexer.lean index 7ec3eb2..1dcd175 100644 --- a/test/spanuse/SpanUseLexer.lean +++ b/test/spanuse/SpanUseLexer.lean @@ -150,8 +150,9 @@ theorem SpanUseLexer.textIndep0 : ∀ r, SpanUseLexer.cflat.needsText 0 r = fals Lexer.FastActs.textIndep_of_forall₂ SpanUseLexer.fastActs (SpanUseLexer.cflat.textDep.getD 0 #[]) 0 (Lexer.Forall₂.cons nofun (Lexer.Forall₂.cons (fun _ _ => rfl) (Lexer.Forall₂.cons (fun _ _ => rfl) Lexer.Forall₂.nil))) -/-- A successful `tokenize` is a maximal-munch tokenization of the input, and the spec - tokenizer `Lexer.tokenize` returns the same token values. -/ +/-- If `tokenize` succeeds with `ts`, the input has a maximal-munch tokenization + (`Lexer.Tokenization`), and the spec tokenizer `Lexer.tokenize` returns the token values + of `ts`. -/ theorem SpanUseLexer.tokenize_sound {input : String} {ts : List (Runtime.Positioned Tok)} (h : SpanUseLexer.tokenize input = .ok ts) : Lexer.Tokenization SpanUseLexer.rules0 input.toList ∧ diff --git a/test/spanuse/SpanUseVerified.lean b/test/spanuse/SpanUseVerified.lean index 70e3fbf..bd4de70 100644 --- a/test/spanuse/SpanUseVerified.lean +++ b/test/spanuse/SpanUseVerified.lean @@ -566,8 +566,9 @@ abbrev ParserStartTree (word : List grammarInst.Token) := Grammar.ParseTree (G := grammarInst) (.NT (startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState))) word -/-- **Soundness.** An accepted token list starts with the word of a parse tree whose value, - at the start of the input, is the result. -/ +/-- **Soundness.** If `parse` accepts `input`, the EOF-padded stream of `input` + (`toStream input`) starts with the word of a parse tree whose value, at the start of the + input, is the result. -/ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) (semantic : Nat) (accepted : SpanUseParser.parse input logNSteps = some semantic) : @@ -592,6 +593,8 @@ theorem parser_sound (input : List grammarInst.Token) (logNSteps : Nat) refine ⟨word, tree, rest, inputEq, ?_⟩ rw [← valueEq, semanticEq] +/-- **Error freedom.** The executable parser's `run` never returns `.err` (the result of + inconsistent tables), on every token list and fuel. -/ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : Runtime.Exec.ResultErrFree (SpanUseParser.run input logNSteps) := by have related := parserRunRefines input logNSteps @@ -610,6 +613,7 @@ theorem parser_err_free (input : List grammarInst.Token) (logNSteps : Nat) : | timeout => trivial | error message => exact dependentFree +/-- `parser_err_free` as an inequality: `run` is not `.err message` for any `message`. -/ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) (message : String) : SpanUseParser.run input logNSteps ≠ .err message := by @@ -618,6 +622,7 @@ theorem parser_ne_err (input : List grammarInst.Token) (logNSteps : Nat) rw [isError] at errorFree exact errorFree +/-- The EOF-padded stream of `input` is `input` followed by the stream of `[]`. -/ theorem toStream_eq_appList (input : List grammarInst.Token) : toStream input = Runtime.AppStream.appList input (toStream []) := by funext index @@ -667,6 +672,7 @@ abbrev PosLexerAgrees : Prop := Lexer.PosLexerAgrees SpanUseLexer.cbyte SpanUseL theorem posLexerAgrees : PosLexerAgrees := SpanUseLexer.posLexerAgrees +/-- When `tokenize` lexes `s` to `ts`, the positioned byte lexer `lexPos` returns `ts` too. -/ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.tokenize s = .ok ts) : Lexer.lexPos SpanUseLexer.cbyte s = .ok ts := by have hagree := posLexerAgrees s @@ -676,16 +682,21 @@ theorem lexPos_eq_of_tokenize (s : String) (ts : List (Runtime.Positioned Tok)) | error e => intro hc; simp [Except.toOption] at hc | ok v => intro hc; simp [Except.toOption] at hc; rw [hc] +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is `parse` on `ts`. -/ theorem parseStr_eq (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.tokenize s = .ok ts) : SpanUseParser.parseStr s k = SpanUseParser.parse ts k := by have hp : Lexer.lexPos SpanUseLexer.cbyte s = .ok ts := lexPos_eq_of_tokenize s ts h exact SpanUseParser.parseStr_eq_lexPos s k ts hp +/-- When `tokenize` lexes `s` to `ts`, `parseStr` on `s` is the dependent `parse` on `ts`. -/ theorem parseStr_eq_dependent (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.tokenize s = .ok ts) : SpanUseParser.parseStr s k = parse ts k := by rw [parseStr_eq s k ts h, parse_eq_dependent] +/-- **Soundness of `parseStr`.** When `tokenize` lexes `s` to `ts` and `parseStr` accepts `s` + with value `p`, the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a + parse tree whose value is `p`. -/ theorem parseStr_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.tokenize s = .ok ts) (p : Nat) (accepted : SpanUseParser.parseStr s k = some p) : @@ -696,28 +707,13 @@ theorem parseStr_sound (s : String) rw [parseStr_eq s k ts h] at accepted exact parser_sound ts k p accepted -/-- When `tokenize` fails, the byte lexer delivers a prefix `ts` and fails, and `parseStr` - is `none` or `parse` of an extension of `ts`. -/ -theorem parseStr_of_tokenize_error (s : String) (k : Nat) - (e : Lexer.LexError) (h : SpanUseLexer.tokenize s = .error e) : - ∃ ts e', Runtime.Exec.Fails (Lexer.pullSource (Lexer.pullAux SpanUseLexer.cbyte s.toUTF8)) - ⟨false, s.toUTF8.size + 1, 0, [SpanUseLexer.cbyte.flat.base.start]⟩ ts e' ∧ - ∀ tail, SpanUseParser.parseStr s k = none ∨ SpanUseParser.parseStr s k = SpanUseParser.parse (ts ++ tail) k := by - rcases SpanUseParser.parseStr_total s k with ⟨ts, hD, _⟩ | hF - · exfalso - have hp : Lexer.lexPos SpanUseLexer.cbyte s = .ok ts := - Lexer.lexPosAux_of_denotes SpanUseLexer.cbyte s.toUTF8 _ _ _ ts hD - have hagree := posLexerAgrees s - rw [hp, h] at hagree - simp [Except.toOption] at hagree - · exact hF - /-- Every production of the start symbol has the end marker `$` on its right-hand side. -/ theorem startProds_end : ∀ p : Production, prodLhs' p = startNt' (⟨0, of_decide_eq_true rfl⟩ : InitState) → Symbol.T (⟨3, of_decide_eq_true rfl⟩ : Terminal) ∈ prodRhsRev' p := by native_decide +/-- Only the `EOF` token has the terminal of the end marker `$`. -/ theorem tokenTerm_eq_end (t : Tok) (h : tokenTerm' t = (⟨3, of_decide_eq_true rfl⟩ : Terminal)) : t = .EOF := by cases t <;> first | rfl | exact absurd (congrArg Fin.val h) (Nat.ne_of_beq_eq_false rfl) @@ -734,6 +730,7 @@ theorem dependent_ne_parsed_of_no_eof (input : List (Runtime.Positioned Tok)) (k startProds_end input ⟨.EOF, Runtime.Span.dummy⟩ rfl (fun t ht he => hin t ht (tokenTerm_eq_end t.val he)) k hlen r rest +/-- `dependent_ne_parsed_of_no_eof` for the dependent `parse`: it returns `none`. -/ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat) (hin : ∀ t ∈ input, t.val ≠ .EOF) (hlen : 2 ^ k < input.length) : parse input k = none := by unfold parse @@ -742,7 +739,8 @@ theorem parse_eq_none_of_no_eof (input : List (Runtime.Positioned Tok)) (k : Nat | Parsed r rest => exact absurd hp (dependent_ne_parsed_of_no_eof input k hin hlen r rest) | _ => rfl -/-- A prefix of lexed tokens with no `EOF`, padded with copies of its first token. -/ +/-- A token list `t0 :: ts` with no `EOF`, padded with `2^k + 1` copies of `t0`, has no + `EOF` and is longer than `2^k`. -/ theorem no_eof_pad (t0 : Runtime.Positioned Tok) (ts : List (Runtime.Positioned Tok)) (hts : ∀ t ∈ t0 :: ts, t.val ≠ .EOF) (k : Nat) : (∀ t ∈ t0 :: ts ++ List.replicate (2 ^ k + 1) t0, t.val ≠ .EOF) ∧ @@ -828,7 +826,8 @@ theorem runStream_ne_ok_of_tokenize_error (s : String) (k : Nat) (e : Lexer.LexE exact dependent_ne_parsed_of_no_eof _ k hin hlen value stream hdep /-- **End to end.** If `parseStr` accepts `s` with value `p`, then `tokenize` lexes `s` to - `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of a parse + tree whose value is `p`. -/ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Nat) (accepted : SpanUseParser.parseStr s k = some p) : ∃ ts, SpanUseLexer.tokenize s = .ok ts ∧ @@ -844,8 +843,8 @@ theorem parseStr_sound_tokenize (s : String) (k : Nat) (p : Nat) /-- **End to end, with the lexer specification.** If `parseStr` accepts `s` with value `p`, then `s` has a maximal-munch tokenization (`Lexer.Tokenization`), the spec tokenizer - returns the token values of `ts = tokenize s`, and `ts` starts with the word of a parse - tree whose value is `p`. -/ + returns the token values of `ts = tokenize s`, and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Nat) (accepted : SpanUseParser.parseStr s k = some p) : ∃ ts, SpanUseLexer.tokenize s = .ok ts ∧ Lexer.Tokenization SpanUseLexer.rules0 s.toList ∧ @@ -860,7 +859,8 @@ theorem parseStr_sound_tokenization (s : String) (k : Nat) (p : Nat) /-- **`tokenize` then `parse`.** If `tokenize` lexes `s` to `ts` and `parse` accepts `ts` with value `p`, then `s` has a maximal-munch tokenization, the spec tokenizer returns the token - values of `ts`, and `ts` starts with the word of a parse tree whose value is `p`. -/ + values of `ts`, and the EOF-padded stream of `ts` (`toStream ts`) starts with the word of + a parse tree whose value is `p`. -/ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (p : Nat) (h : SpanUseLexer.tokenize s = .ok ts) (accepted : SpanUseParser.parse ts k = some p) : Lexer.Tokenization SpanUseLexer.rules0 s.toList ∧ Lexer.tokenize SpanUseLexer.lexer s = .ok (ts.map (·.val)) ∧ @@ -871,8 +871,8 @@ theorem tokenize_parse_sound (s : String) (k : Nat) (ts : List (Runtime.Position obtain ⟨htok, hspec⟩ := SpanUseLexer.tokenize_sound h exact ⟨htok, hspec, parser_sound ts k p accepted⟩ -/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a parse tree of the start symbol - spans exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ +/-- **Completeness.** If `tokenize` lexes `s` to `ts` and a start parse tree has word + exactly `ts`, within the fuel, `parseStr` returns the tree's value. -/ theorem parseStr_complete (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.tokenize s = .ok ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : @@ -903,8 +903,8 @@ theorem parseStr_unambiguous (s : String) {ts₁ ts₂ : List (Runtime.Positione exact ⟨rfl, (parser_unambiguous tree₁ tree₂).2⟩ /-- **Completeness over positioned tokens.** If `ts` is the positioned tokenization of `s` - (`SpanUseLexer.Lexes`) and a parse tree of the start symbol spans exactly `ts`, within the fuel, - `parseStr` returns the tree's value. -/ + (`SpanUseLexer.Lexes`) and a start parse tree has word exactly `ts`, within the fuel, `parseStr` + returns the tree's value. -/ theorem parseStr_complete_lexes (s : String) (k : Nat) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.Lexes s ts) (tree : ParserStartTree ts) (fuel : Grammar.ptSize tree ≤ 2 ^ k) : SpanUseParser.parseStr s k = some (SpanGrammar.ptSem ⟨0⟩ tree) := @@ -926,17 +926,17 @@ theorem parseStr_unambiguous_lexes (s : String) {ts₁ ts₂ : List (Runtime.Pos `s` (`SpanUseLexer.Lexes`), every leaf's span is `[a, b)` for positions `a ≤ b` of `s`, and a rule's action emits the leaf's token from the lexeme `s.extract a b` (or the leaf is the end-of-input token at the end of `s`). Every inner node's span is `[a, b)` for positions - `a ≤ b` of `s`; `b` is the end of the lexeme of the node's last token, and `a` is the start - of the lexeme of its first token or, when its word is empty or its leftmost children - derive the empty word, the end of the token before it (`Lexer.AllNodeText`). -/ + `a ≤ b` of `s`, where `b` is the end of the node's word (the end `pe` of the token before + the node when the word is empty) and `a` is `pe` or the start of the first token of the + word (`Lexer.AllNodeText`). The theorem does not state which of the two `a` is. -/ theorem parseStr_node_spans (s : String) (ts : List (Runtime.Positioned Tok)) (h : SpanUseLexer.Lexes s ts) (tree : ParserStartTree ts) : Lexer.AllNodeText (Lexer.modeAct SpanUseLexer.lexer SpanUseLexer.lexer.start) SpanUseLexer.lexer.eofToken s ⟨0⟩ tree := Lexer.PosLexing.allNodeText h tree /-- **End to end over positioned tokens.** If `parseStr` accepts `s` with value `p`, then - `s` has a positioned tokenization `ts` (`SpanUseLexer.Lexes`), and `ts` starts with the word of a - parse tree whose value is `p`. -/ + `s` has a positioned tokenization `ts` (`SpanUseLexer.Lexes`), and the EOF-padded stream of `ts` + (`toStream ts`) starts with the word of a parse tree whose value is `p`. -/ theorem parseStr_sound_lexes (s : String) (k : Nat) (p : Nat) (accepted : SpanUseParser.parseStr s k = some p) : ∃ ts, SpanUseLexer.Lexes s ts ∧