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
93 changes: 93 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,66 @@ versions may change the CLI, the `.lig` syntax, and the generated module API.

## [Unreleased]

### Added

- `diagnoseStr : String → Except Lexer.LexError (Runtime.Exec.Diagnostic T)` in the
parser module of every grammar with a `%lexer` block. It runs the generated `tokenize`
and then `diagnose`, so a lex error and a syntax error can be reported from a string.
It does not need `%option parseStr`.
- `Lexer.LexError.lineCol source` and `Lexer.LexError.format source`, which give the
1-based line and column of a lex error and a message of the form
`1:3: lex error: unexpected character '?'`.

### Changed

- Breaking: the `expected` list of a `ParseError`, and so of `errorMessage`, `diagnose`
and `diagnoseSpanned`, keeps only terminals that can be shifted from the actual stack
after the reductions they trigger. Before, it was every terminal with a non-error
action in the state, which listed `RPAR` for `1 2` at the top level. `--list-errors`
still prints the full per-state set and says so in its header.
- Breaking: `LexError.pos` is a byte offset in every generated lexer. Before, `tokenize`
and `tokenizeBare` reported a character offset, while `tokenizeByte`, `lexPos` and
`parseStr` reported bytes, so the same error had different positions. The two differ
only when a non-ASCII character comes before the error. The list-based specification
`Lexer.tokenize` still counts characters.
- The generator warns when the path of a written Lean module does not end in the module
name as a path (`--out-dir . --module-prefix J` writes `./ExprParser.lean` for
`J.ExprParser`), because Lake will not find it. One warning per run; the exit code is
unchanged.
- A grammar without a `%lexer` block gets no "token is never used" warning, because the
hand-written lexer may emit it. The warning stays for grammars with `%lexer`, and an
undeclared symbol is still an error.
- Breaking: the generated `diagnose` and `diagnoseSpanned` return
`Runtime.Exec.Diagnostic <start type>` instead of `Runtime.Exec.Diagnostic VP`, so
`.ok v` carries the same value as `parse`. `Runtime.Exec.Diagnostic.mapOk` is new.
- Breaking (`.lig`): a token declared twice, a nonterminal given two result types, and a
second `%header`, `%lexerheader`, `%tokentype`, `%eof`, `%start` or `%lexer` are errors.
Before, the first two were warnings and gave a module that did not compile or a parser
that rejected valid input, and a repeated directive replaced the earlier one. A second
`%option` of the same name is an error too; before, the later value won.
- Generated modules set `autoImplicit false` after the copied `%header`, so an unknown type
name is reported as an unknown identifier. Code in `%lexerheader` is elaborated with this
setting too.
- `errorMessage` without a source string gives the token index (`token 2: …`) for every
error. Before, an error at a token with a span gave `1:1`.
- Each LR(1) conflict is a warning at the `.lig` position of the production the tables do
not use, with terminal and production names and the items, instead of state and
terminal numbers.
- Every frontend error has a `.lig` position, except a missing `%%`, `%start` or `%eof`.
Unknown directives and options suggest the closest name. Macro errors name the wrong
argument count, an unknown macro, an undeclared argument, or a macro call used as an
argument. A missing `%%`, `%eof` or `%start` says what to add, and a rule before `%%`
says that rules start after `%%`.
- New warnings: two alternatives of a rule with the same symbols; a token or nonterminal that no production uses; `%option parseStr` or
`roundtrip_lexer` without a `%lexer` block; a lexer rule that matches only the empty
string (one warning instead of two). The warning for a lexer rule that can never win
gives the line of the rule that shadows it.
- The generated modules name the `.lig` in their first comment, and each action is
preceded by a comment with its `.lig` line.
- `--list-errors` no longer lists the `%eof` token next to "end of input".
- The README lists `diagnoseSpanned` and `terminalName` as stable. The other generated
names (`run`, `decode`, `sem`, the tables, `tokenizeBare`, `tokenizeByte`) can be named
by an importer but are not stable.
- 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
Expand All @@ -25,6 +83,41 @@ versions may change the CLI, the `.lig` syntax, and the generated module API.
`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`.

- Breaking (`.lig`): a second `eof` rule in a `%lexer` block, and text after the `eof`
rule, are errors. Before, they were ignored. A name that is both a `%token` and a rule
head is an error; before, every reference resolved to the token. A `%token` line ends at
the end of its line, and a string literal in a `%lexer` pattern must close on its line.
- Text after a directive's argument (`%token A, B`, `%start expr atom`,
`%option compress_tables yes`, `%tokentype Lang.Tok`) is reported against the directive.
An empty rule type or `%token <>`, an unclosed `<` in `%token`, and an `enter` of an
undefined mode are errors at their position.
- `lexes_eof_last`, `word_eq_of_lexes` and `parseStr_sound_exact` are emitted only when
the `eof` rule of the `%lexer` block emits the `%eof` token.

- Breaking (`.lig`): a `let` name defined twice in a `%lexer` block is an error. The
closing `}` of an action is found with strings, character literals and comments skipped,
so `{ x ++ "}" }` works; an action with an unbalanced brace inside a string parses
differently. A UTF-8 byte order mark at the start of a `.lig` is skipped.
- New warning: a token a production uses and no lexer action mentions. An unknown symbol
in a rule suggests the closest name, and the unused-token and unused-nonterminal warnings
are left out when the grammar has an error. A `%token` continued on the next line and a
directive after `%%` have their own messages.

### Fixed

- A constant action with binders (`a=NUM PLUS b=NUM { 2 }`) did not compile in
`<Base>Verified`.
- A `%lexer` block without an `eof` rule, with a valueless `%eof` token, gave a lexer
module that did not compile.
- A nonterminal of function type (`Nat → Nat`) gave a `V` constructor with two arguments,
which did not compile; such types are now in parentheses, also in the token type.
- A binder named `stk` or `gotoData` was captured by the fused reducers, and a binder that
is a Lean keyword (`fun`, `from`, `at`) was written unescaped in patterns. Such binders
are written `«name»`; the action refers to them as `«fun»`.
- A start type written with a space (`List Nat`, `Nat × Nat`) gave `Option List Nat` in
`parse`, `parseStr` and `<Base>Verified.parse`, which did not compile.
- A `--` comment after the type of a rule became part of the type.

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

Changes since `0.1.0-alpha.1`.
Expand Down
36 changes: 28 additions & 8 deletions LeanParserGenerator/Construct/Tables.lean
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,29 @@ inductive Act where
| error : Act
deriving Repr, DecidableEq, Inhabited

/-- An LR(1) conflict found while filling the action table. The written table keeps
the first entry: the shift for a shift/reduce conflict, and `kept` for a
reduce/reduce conflict. -/
inductive ConflictKind where
/-- The completed production `prod` could also be reduced where the table shifts. -/
| shiftReduce (prod : Nat)
/-- Production `kept` is in the table, and `dropped` could also be reduced. -/
| reduceReduce (kept dropped : Nat)
deriving Repr, DecidableEq, Inhabited

/-- A conflict in state `state` on lookahead terminal `term`. -/
structure Conflict where
state : Nat
term : Nat
kind : ConflictKind
deriving Repr, DecidableEq, Inhabited

instance : ToString Conflict where
toString c := match c.kind with
| .shiftReduce _ => s!"shift/reduce conflict in Pager state {c.state} on terminal {c.term}"
| .reduceReduce kept dropped =>
s!"reduce/reduce conflict in Pager state {c.state} on terminal {c.term} (productions {kept} vs {dropped})"

/-- Parse tables for an augmented grammar and numbered LR state graph. -/
structure Tables where
/-- Number of states. -/
Expand All @@ -94,8 +117,8 @@ structure Tables where
goto : Array (Array (Option Nat))
/-- States that reduce a fixed production regardless of lookahead. -/
defaultReduce : Array (Option Nat)
/-- Human-readable conflict reports (empty ⇒ the constructed automaton is conflict-free). -/
conflicts : List String
/-- The conflicts (empty ⇒ the constructed automaton is conflict-free). -/
conflicts : List Conflict
deriving Repr, Inhabited

/-- Is the item's dot at the end of its production's right-hand side? -/
Expand All @@ -113,7 +136,7 @@ def buildTables (g : Grammar) (col : Collection) : Tables := Id.run do
let numStates := col.states.size
let mut action := Array.replicate numStates (Array.replicate numT Act.error)
let mut goto := Array.replicate numStates (Array.replicate numN (none : Option Nat))
let mut conflicts : List String := []
let mut conflicts : List Conflict := []
for i in [0:numStates] do
for edge in col.trans.getD i [] do
let (symbol, target) := edge
Expand All @@ -126,13 +149,10 @@ def buildTables (g : Grammar) (col : Collection) : Tables := Id.run do
match (action[i]!)[term]! with
| .error => action := action.set! i ((action[i]!).set! term (.reduce item.prod))
| .shift _ =>
conflicts := conflicts ++
[s!"shift/reduce conflict in Pager state {i} on terminal {term}"]
conflicts := conflicts ++ [⟨i, term, .shiftReduce item.prod⟩]
| .reduce otherProd =>
if otherProd != item.prod then
conflicts := conflicts ++
[s!"reduce/reduce conflict in Pager state {i} on terminal {term} " ++
s!"(productions {otherProd} vs {item.prod})"]
conflicts := conflicts ++ [⟨i, term, .reduceReduce otherProd item.prod⟩]
let mut defaultReduce := Array.replicate numStates (none : Option Nat)
for i in [0:numStates] do
let row := action[i]!
Expand Down
31 changes: 31 additions & 0 deletions LeanParserGenerator/Emit/Builder.lean
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,35 @@ def headerDefs (header : String) : List String :=
| [] => []
go ws

/-- A type as a function argument: a type written with spaces or symbols, such as
`List String` or `Nat × Nat`, in parentheses, and a name as it is. -/
def parenTy (ty : String) : String :=
let ty := ty.trimAscii.toString
if ty.all (fun c => c.isAlphanum || c == '_' || c == '.' || c == '\'') then ty else s!"({ty})"

/-- Identifier-like tokens of Lean and its `Lean` package, taken from
`Lean.Parser.getTokenTable` under `import Lean` (the long `builtin_*`, `declare_*` and
`register_*` command names are left out). A binder with one of these names must be
written `«name»` in generated code. -/
def leanKeywords : List String := [
"Prop", "Sort", "StateRefT", "Type", "abbrev", "add_decl_doc", "assert_not_exists",
"assert_not_imported", "at", "attribute", "aux_def", "axiom", "bif", "binder_predicate",
"break", "by", "by_elab", "calc", "catch", "class", "coinductive", "continue", "dbg_trace",
"decreasing_by", "def", "deriving", "do", "dsimproc", "elab", "elab_rules", "else", "end",
"example", "exists", "export", "extends", "finally", "for", "forall", "from", "fun",
"generalizing", "have", "haveI", "hiding", "idbg", "if", "import", "in", "include",
"inductive", "infix", "infixl", "infixr", "initialize", "instance", "leading_parser", "let",
"letI", "let_fun", "local", "macro", "macro_rules", "match", "matches", "meta", "mut",
"mutual", "namespace", "nofun", "nomatch", "noncomputable", "nonrec", "notation", "omit",
"opaque", "open", "partial", "postfix", "prefix", "private", "protected", "public",
"renaming", "repeat", "return", "scoped", "section", "set_option", "show", "simproc",
"structure", "suffices", "syntax", "termination_by", "then", "theorem",
"trailing_parser", "try", "universe", "unless", "unsafe", "until", "using", "variable",
"where", "while", "with"]

/-- A `.lig` binder name as a Lean identifier: `«name»` when the name is a Lean keyword,
else the name. -/
def binderName (nm : String) : String :=
if leanKeywords.contains nm then s!"«{nm}»" else nm

end Emit.Builder
Loading