Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,27 @@ All notable changes to this project are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Until 1.0, minor
versions may change the CLI, the `.lig` syntax, and the generated module API.

## [Unreleased]

### Changed

- Breaking: node spans are exact, in Lean and in Rust. A node whose word is nonempty spans
from the start of its first token to the end of its last token, also when its leftmost
children derive the empty word (a left-recursive `list(X)`, or a rule that begins with
one). Before, such a node started at the end of the previous token. A node whose word is
empty keeps the span `(pe, pe)` at the end `pe` of the previous token.
`Runtime.SpanGrammar.SpanFacts`, `allSpanFacts` and `parseStr_node_spans` state the exact
span, with no disjunction.
- Breaking (runtime API): `Runtime.NodeSpan := Span × Bool` carries a flag that is `true`
iff the word is empty. `Span.fold` takes a `List NodeSpan` and returns a `NodeSpan`;
`VP := Runtime.NodeSpan × V`; `SpanGrammar.semR s := Pos → NodeSpan × semT s`; the
values of `SpanGrammar.parseCorrect`/`parseComplete` are
`((ptSpan pe t, word.isEmpty), ptSem pe t)`; each generated `Stk` cell has a `Bool`
field, except the cells of tokens and of nonterminals whose productions all start with
a token or such a nonterminal, which use the flagless constructors `cUnitN`/`c<i>N`;
`ptSpan_startPos` states `startPos = wordStart pe word`, `ptSpan_eq` is new, and
`ptlSpans_head` is removed. The Rust `Entry` and `ValueEntry` have a new field `empty`.

## [0.1.0-alpha.2] - 2026-12-01

Changes since `0.1.0-alpha.1`.
Expand Down
36 changes: 34 additions & 2 deletions LeanParserGenerator/Construct/Analysis.lean
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ module
/-
Construct the nullable and FIRST sets by a fixpoint over the grammar.
* `nullable` : which nonterminals derive the empty string;
* `leadNonempty` : which nonterminals start every production with a terminal or
another such nonterminal;
* `firstSets` : the FIRST set (set of terminal indices) of each nonterminal.

Both iterate a monotone fixpoint. They feed Pager closure and the generated
`nullableNt`/`firstNt` certificate annotations.
Each iterates a monotone fixpoint. `nullable` and `firstSets` feed Pager closure and the
generated `nullableNt`/`firstNt` certificate annotations; `leadNonempty` selects the
generated Lean stack cells that carry no emptiness flag.
-/
public import LeanParserGenerator.IR.Grammar

Expand Down Expand Up @@ -69,6 +72,35 @@ partial def nullable (g : Grammar) : Array Bool :=
if next == cur then cur else loop next fuel
loop (Array.replicate g.numNonterminals false) (g.numNonterminals + 1)

/-! ### Lead-nonempty -/

/-- One step of the lead-nonempty fixpoint: a nonterminal stays in the set if each of its
productions has a nonempty right-hand side whose first symbol is a terminal or a
nonterminal in `cur`. -/
def leadStep (g : Grammar) (cur : Array Bool) : Array Bool :=
(Array.range g.numNonterminals).map (fun nt =>
(g.prodsFor nt).all (fun (_, p) =>
match p.rhs with
| [] => false
| .term _ :: _ => true
| .nonterm j :: _ => cur.getD j false))

/-- The lead-nonempty nonterminals: the greatest set such that every production of a
member starts with a terminal or a member. Every member is non-nullable, since the
first symbol of each of its productions derives no empty word. The generated Lean
parser stores no emptiness flag in the cells of these nonterminals and of tokens.
The generated `fuseOK<p>` proofs check the flags by `rfl`, so this analysis is not
trusted: a wrong set makes a proof fail, not a theorem false. Iterates `leadStep`
from the full set; each step removes at least one nonterminal or stops. -/
partial def leadNonempty (g : Grammar) : Array Bool :=
let rec loop (cur : Array Bool) (fuel : Nat) : Array Bool :=
match fuel with
| 0 => cur
| fuel + 1 =>
let next := leadStep g cur
if next == cur then cur else loop next fuel
loop (Array.replicate g.numNonterminals true) (g.numNonterminals + 1)

/-! ### FIRST -/

/-- FIRST of a symbol under the current first-set assignment. -/
Expand Down
232 changes: 172 additions & 60 deletions LeanParserGenerator/Emit/Codegen.lean

Large diffs are not rendered by default.

33 changes: 28 additions & 5 deletions LeanParserGenerator/Emit/CodegenRust.lean
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
(tables.defaultReduce.getD st none).getD noGoto
let lhs := g.prods.map (·.lhs)
let len := g.prods.map (·.rhs.length)
-- The index of the first right-hand-side symbol that is not nullable (the length when
-- every symbol is nullable). A reduce tests the emptiness flag of the children before it.
let nul := Construct.nullable g
let firstNN := g.prods.map fun p =>
(p.rhs.findIdx? (fun s => !Construct.symNullable nul s)).getD p.rhs.length
let actMax := act.foldl max 0
let nonterms := g.nontermNames
let termNames := g.termNames
Expand All @@ -87,6 +92,9 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
staticArr "DEFAULT_REDUCE" "u16" (defRed.map toString),
staticArr "LHS" (uintTy numN) (lhs.map toString),
staticArr "RHS_LEN" "u8" (len.map toString),
"/// The index of the first right-hand-side symbol of production `p` that is not\n" ++
"/// nullable, or `RHS_LEN[p]` when every symbol is nullable.\n" ++
staticArr "FIRST_NONNULLABLE" "u8" (firstNN.map toString),
String.intercalate "\n" [
"/// A node of the postorder trace: a shifted token or a reduction.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
Expand All @@ -111,10 +119,13 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
" }",
"}",
"",
"/// A parse stack entry: the state, the start of the symbol's span, and whether the",
"/// symbol's word (its tokens) is empty.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
"pub struct Entry {",
" pub state: u16,",
" pub start: u32,",
" pub empty: bool,",
"}",
"",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
Expand All @@ -139,11 +150,13 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
" nodes: &mut N,",
") -> Result<(), StreamError<S::Error>> {",
" stack.clear();",
" stack.push(Entry { state: 0, start: 0 });",
" stack.push(Entry { state: 0, start: 0, empty: true });",
" let mut ti = 0usize;",
" let mut prev_end = 0u32;",
" // The state of the top entry, kept in a local so a step does not read it back",
" // from the stack.",
" let mut state = 0usize;",
" loop {",
" let state = stack[stack.len() - 1].state as usize;",
" let dr = DEFAULT_REDUCE[state] as usize;",
" let prod = if dr != NONE {",
" dr",
Expand All @@ -157,7 +170,8 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
" return Err(StreamError::Parse(ParseError { token: ti, state, term }));",
" }",
" if a & 1 == 1 {",
" stack.push(Entry { state: (a >> 1) as u16, start: tstart });",
" stack.push(Entry { state: (a >> 1) as u16, start: tstart, empty: false });",
" state = a >> 1;",
" nodes.push(Node { kind: term, start: tstart, end: tend });",
" prev_end = tend;",
" source.bump();",
Expand All @@ -171,7 +185,15 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
" return Err(StreamError::Parse(ParseError { token: ti, state, term: u16::MAX }));",
" }",
" let base = stack.len() - n;",
" let start = if n > 0 { stack[base].start } else { prev_end };",
" // The node starts at its first child with a nonempty word; an empty word starts",
" // (and ends) at `prev_end`. Only the children before `FIRST_NONNULLABLE[prod]`",
" // are tested: they are nullable, and that child's word is never empty.",
" let k = FIRST_NONNULLABLE[prod] as usize;",
" let (start, empty) = match stack[base..base + k].iter().find(|e| !e.empty) {",
" Some(e) => (e.start, false),",
" None if k < n => (stack[base + k].start, false),",
" None => (prev_end, true),",
" };",
" stack.truncate(base);",
" let top = stack[base - 1].state as usize;",
" let g = GOTO[top * NUM_NONTERMINALS + LHS[prod] as usize] as usize;",
Expand All @@ -183,7 +205,8 @@ def renderParser (prepared : PreparedGrammar) : String := Id.run do
" Err(StreamError::Parse(ParseError { token: ti, state, term: u16::MAX }))",
" };",
" }",
" stack.push(Entry { state: g as u16, start });",
" stack.push(Entry { state: g as u16, start, empty });",
" state = g;",
" }",
"}",
"",
Expand Down
12 changes: 7 additions & 5 deletions LeanParserGenerator/Emit/CodegenVerified.lean
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ def emitRefinement (s : Surface) (g' : IR.Grammar) (execModule : String) : Strin
s!"theorem refinementDecodeAgrees (token : Runtime.Positioned {s.tokenType}) :",
s!" {execModule}.decode token =",
" (refinementTerminalIndex (tokenTerm' token.val),",
" (token.span, refinementEncodeValue (.T (tokenTerm' token.val)) (tokenSem' token.val))) := by",
" ((token.span, false), refinementEncodeValue (.T (tokenTerm' token.val)) (tokenSem' token.val))) := by",
" obtain ⟨token, span⟩ := token",
" cases token <;> rfl",
"",
Expand Down Expand Up @@ -1278,9 +1278,10 @@ 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`, 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. -/",
" `a ≤ b` of `s` (`Lexer.AllNodeText`). For a node with a nonempty word, `a` is the start of",
" the lexeme of its first token and `b` the end of the lexeme of its last token. For a node",
" with an empty word, `a = b = pe`, the end of the token before the node (byte 0 at the",
" start of `s`). -/",
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 :=",
Expand Down Expand Up @@ -1407,7 +1408,8 @@ def generateVerifiedFrom (s : Surface) (prepared : PreparedGrammar)
"theorem completeness : Complete := complete_of_completeValidator completenessValidation" ]
let startTy := (s.rules.find? (·.lhs == s.start)).map (·.ty) |>.getD "Unit"
-- `parse` returns the value of the start symbol at the start of the input (byte 0):
-- the derived value `r` maps a position to a span and a value.
-- the derived value `r` maps a position to a node span (a span and an emptiness flag)
-- and a value.
let parseEntry := lines [
s!"def toStream (input : List (Runtime.Positioned {s.tokenType})) : Runtime.NatStream (Runtime.Positioned {s.tokenType}) :=",
s!" fun n => input.getD n ⟨.{s.eof}, Runtime.Span.dummy⟩",
Expand Down
27 changes: 21 additions & 6 deletions LeanParserGenerator/Emit/Rust/Values.lean
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,14 @@ def renderValueParser (s : Surface) (plan : ValuePlan) (tokName tokLt : String)
" pub end: u32,",
"}",
"",
"/// A parse stack entry. The value of its symbol is on the stack of its type in `Stacks`.",
"/// A parse stack entry: the state, the span of its symbol, and whether the symbol's word",
"/// (its tokens) is empty. The value of its symbol is on the stack of its type in `Stacks`.",
"#[derive(Clone, Copy, Debug)]",
"pub struct ValueEntry {",
" pub state: u16,",
" pub start: u32,",
" pub end: u32,",
" pub empty: bool,",
"}",
"",
"/// The buffers of `parse_values`: the entry stack and one value stack per type.",
Expand Down Expand Up @@ -218,11 +220,13 @@ def renderValueParser (s : Surface) (plan : ValuePlan) (tokName tokLt : String)
s!" stacks: &mut Stacks{lt},",
s!") -> Result<{plan.startTy}, StreamError<S::Error>> \{",
" stacks.clear();",
" stacks.entries.push(ValueEntry { state: 0, start: 0, end: 0 });",
" stacks.entries.push(ValueEntry { state: 0, start: 0, end: 0, empty: true });",
" let mut ti = 0usize;",
" let mut prev_end = 0u32;",
" // The state of the top entry, kept in a local so a step does not read it back",
" // from the stack.",
" let mut state = 0usize;",
" loop {",
" let state = stacks.entries[stacks.entries.len() - 1].state as usize;",
" let dr = DEFAULT_REDUCE[state] as usize;",
" let prod = if dr != NONE {",
" dr",
Expand All @@ -240,7 +244,8 @@ def renderValueParser (s : Surface) (plan : ValuePlan) (tokName tokLt : String)
" if let Some(t) = tok {",
" push_payload(stacks, &t.tok);",
" }",
" stacks.entries.push(ValueEntry { state: (a >> 1) as u16, start: tstart, end: tend });",
" stacks.entries.push(ValueEntry { state: (a >> 1) as u16, start: tstart, end: tend, empty: false });",
" state = a >> 1;",
" prev_end = tend;",
" source.bump();",
" ti += 1;",
Expand All @@ -253,7 +258,16 @@ def renderValueParser (s : Surface) (plan : ValuePlan) (tokName tokLt : String)
" return Err(StreamError::Parse(ParseError { token: ti, state, term: u16::MAX }));",
" }",
" let __base = stacks.entries.len() - __n;",
" let __start = if __n > 0 { stacks.entries[__base].start } else { prev_end };",
" // The node starts at its first child with a nonempty word; an empty word starts",
" // (and ends) at `prev_end`. Only the children before `FIRST_NONNULLABLE[prod]`",
" // are tested: they are nullable, and that child's word is never empty.",
" let __k = FIRST_NONNULLABLE[prod] as usize;",
" let (__start, __empty) =",
" match stacks.entries[__base..__base + __k].iter().find(|__e| !__e.empty) {",
" Some(__e) => (__e.start, false),",
" None if __k < __n => (stacks.entries[__base + __k].start, false),",
" None => (prev_end, true),",
" };",
s!" let Stacks \{ entries: __stack, {destructure} } = &mut *stacks;",
" match prod {",
" AUG_PROD => {",
Expand All @@ -268,7 +282,8 @@ def renderValueParser (s : Surface) (plan : ValuePlan) (tokName tokLt : String)
" if __g == NONE {",
" return Err(StreamError::Parse(ParseError { token: ti, state, term: u16::MAX }));",
" }",
" __stack.push(ValueEntry { state: __g as u16, start: __start, end: prev_end });",
" __stack.push(ValueEntry { state: __g as u16, start: __start, end: prev_end, empty: __empty });",
" state = __g;",
" }",
"}",
"",
Expand Down
Loading