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
10 changes: 6 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ versions may change the CLI, the `.lig` syntax, and the generated module API.
### 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.
and `diagnoseSpanned`, is computed from the stack right after the last consumed token.
It keeps the terminals that can be shifted from that stack after the reductions they
trigger. Before, it was every terminal with a non-error action in the state where the
parser rejects, which listed `RPAR` for `1 2` at the top level and, after default
reductions, left out `TIMES` for `1 )`. `--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
Expand Down
62 changes: 50 additions & 12 deletions LeanParserGenerator/Runtime/Diagnostic.lean
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ variable {V : Type}
/-- The terminals with a non-`error` action in `state`: what the parser would
have accepted there. This is the analog of the `[ … ]` expected-token set
that `menhir --list-errors` records for each error state. It is the static
superset; `diagnose` keeps only the terminals `canShiftAfter` accepts for the
actual stack. -/
superset of the terminals that can follow in that state; `diagnose` does not use it
except as a fallback (`rejectExpected`). -/
def expectedAt (tbl : ExecTable V) (numTerminals state : Nat) : List Nat :=
(List.range numTerminals).filter (fun t => tbl.action state t != Act.error)

Expand Down Expand Up @@ -97,9 +97,10 @@ structure ParseError where
/-- The number of input tokens consumed before the error (0-based index of the
offending token; equal to the input length when the error is at EOF). -/
position : Nat
/-- The terminals that can follow: those with a non-`error` action in `state` that
lead to a shift or accept from the actual stack after the reductions they
trigger (`canShiftAfter`). A subset of `expectedAt tbl numTerminals state`. -/
/-- The terminals that can follow the last consumed token: those that lead to a shift
or accept from the stack right after that token's shift, after the reductions they
trigger (`canShiftAfter`). It can hold terminals with no action in `state`, because
default reductions may have run between that shift and the rejection. -/
expected : List Nat
deriving Repr, Inhabited, DecidableEq

Expand Down Expand Up @@ -157,13 +158,48 @@ def runD (tbl : ExecTable V) (input : List (Nat × V)) (logNSteps : Nat := 20) :
| .inl (r, rem, stk) => (r, rem, stk)
| .inr (stk, rem) => (.timeout, rem, stk)

/-- The expected terminals at a rejection in state `s`: `expectedAt` filtered by
`canShiftAfter` from the stack `stk` that was handed to the rejecting step. -/
def expectedFrom (tbl : ExecTable V) (numTerminals : Nat) (stk : Stack V) (s : Nat) :
List Nat :=
/-- The stack right after the shift that consumed the `position`-th token, found by
running `step` again from the stack `stk` and remaining input `input`. `origLen` is
the length of the whole input. It is `[]` for `position = 0`. `none` when the run
stops first or runs out of `fuel`; the caller then falls back to the stack of the
rejecting step. A shift is a step that removes a token from `input`, so a shift of
the end marker (which `input` does not hold) is not seen. -/
def stackAfterShifts (tbl : ExecTable V) (origLen position : Nat) :
Stack V → List (Nat × V) → Nat → Option (Stack V)
| _, _, 0 => none
| stk, input, fuel + 1 =>
match step tbl stk input with
| .inl _ => none
| .inr (stk', input') =>
if input'.length < input.length && origLen - input'.length == position then some stk'
else stackAfterShifts tbl origLen position stk' input' fuel

/-- The terminals the parser accepts from the stack `stk`, whatever the stack's top state
holds in its action row: those `t` for which `canShiftAfter` reaches a shift or an
accept. -/
def expectedFrom (tbl : ExecTable V) (numTerminals : Nat) (stk : Stack V) : List Nat :=
let states := stk.map (·.1)
let fuel := 4 * (states.length + tbl.numStates + 1)
(expectedAt tbl numTerminals s).filter (canShiftAfter tbl states · fuel)
(List.range numTerminals).filter (canShiftAfter tbl states · fuel)

/-- The expected terminals at a rejection in state `s` after `position` tokens, when the
rejecting step was handed the stack `stk`. The default reductions that ran after the
last shift may have moved the parser to a state that accepts fewer terminals than the
one right after that shift (a state that shifts `TIMES` but reduces by default on
everything else reduces `term` to `expr` before it sees a `)`, and `expr` accepts no
`TIMES`). So the set is computed from the stack right after the last shift, over all
terminals. When that stack cannot be recovered, it is `expectedAt` for `s` filtered by
`canShiftAfter` from `stk`. -/
def rejectExpected (tbl : ExecTable V) (numTerminals : Nat) (input : List (Nat × V))
(logNSteps position : Nat) (stk : Stack V) (s : Nat) : List Nat :=
if position == 0 then expectedFrom tbl numTerminals []
else
match stackAfterShifts tbl input.length position [] input (2 ^ (logNSteps + 1)) with
| some stk0 => expectedFrom tbl numTerminals stk0
| none =>
let states := stk.map (·.1)
let fuel := 4 * (states.length + tbl.numStates + 1)
(expectedAt tbl numTerminals s).filter (canShiftAfter tbl states · fuel)

/-- Diagnose a parse: on rejection, compute the offending position and the set of
expected terminals. `numTerminals` is the width of the action table (the
Expand All @@ -175,7 +211,8 @@ def diagnose (tbl : ExecTable V) (numTerminals : Nat) (input : List (Nat × V))
| (.ok v, _) => .ok v
| (.reject s t, rem, stk) =>
.error { state := s, lookahead := t, position := origLen - rem.length,
expected := expectedFrom tbl numTerminals stk s }
expected := rejectExpected tbl numTerminals input logNSteps
(origLen - rem.length) stk s }
| (.timeout, _) => .timeout
| (.err e, _) => .internal e

Expand Down Expand Up @@ -205,7 +242,8 @@ def diagnoseSpanned (tbl : ExecTable V) (numTerminals : Nat) (spanOf : V → Opt
| (.ok v, _) => (.ok v, none)
| (.reject s t, rem, stk) =>
(.error { state := s, lookahead := t, position := origLen - rem.length,
expected := expectedFrom tbl numTerminals stk s },
expected := rejectExpected tbl numTerminals input logNSteps
(origLen - rem.length) stk s },
offendingSpan spanOf rem)
| (.timeout, _) => (.timeout, none)
| (.err e, _) => (.internal e, none)
Expand Down
27 changes: 17 additions & 10 deletions docs/ERROR_MESSAGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,18 @@ lookahead. The layer built on top lives in
tables, so no semantic action runs.
- `ParseError { state, lookahead, position, expected }` — the structured error.
- `diagnose` — runs the parser and, on rejection, fills in the position and the
expected set. `expected` keeps the terminals of `expectedAt` for which `canShiftAfter`
holds on the actual stack, so `errorMessage`, `diagnose` and `diagnoseSpanned` give the
same list. The list can omit a terminal that is valid at the error. When the parser
reduces on the offending lookahead before it rejects, `expectedAt` reads the row of the
state reached after the reduction. In the grammar `expr: expr PLUS term | term`,
`term: term TIMES atom | atom`, `atom: NUM | LPAR expr RPAR`, the tokens `NUM RPAR`
give `PLUS` and end of input but not `TIMES`. Every listed terminal is valid.
expected set. `expected` lists the terminals that could follow the last consumed token:
it takes the stack right after that token's shift and keeps every terminal for which
`canShiftAfter` holds. `errorMessage`, `diagnose` and `diagnoseSpanned` give the same
list. The set is not read from the state where the parser rejects, because default
reductions may have run since the last shift. In the grammar `expr: expr PLUS term | term`,
`term: term TIMES atom | atom`, `atom: NUM | LPAR expr RPAR`, the tokens `NUM RPAR` make
the parser reduce `NUM` to `atom`, `term` and `expr` before it rejects the `RPAR`, and the
state that rejects it has no action on `TIMES`. The list still has `PLUS`, `TIMES` and
end of input, as they could follow the `NUM`. The list can hold terminals that have no
action in the rejecting state, and can omit terminals that do. If the stack after the last
shift cannot be found, `diagnose` falls back to the terminals of `expectedAt` for the
rejecting state that pass `canShiftAfter` from the stack of the rejecting step.
- `diagnoseSpanned spanOf` — like `diagnose`, but also recovers the offending
token's source `Span` (via a `spanOf : V → Option Span` projection), so the
error can be rendered as `line:col`.
Expand Down Expand Up @@ -160,9 +165,11 @@ For `leanparsergenerator --list-errors test/calc/calc.lig` this prints:
<YOUR SYNTAX ERROR MESSAGE HERE>
```

`## expected one of:` is the static set for the state. The list in a run-time message can
be shorter, because `diagnose` drops the terminals that cannot be shifted from the actual
stack. `--list-errors` has no stack, so it cannot filter.
`## expected one of:` is the static set for the state. The list in a run-time message is
computed from the stack after the last consumed token, so it can differ from the static
set of the rejecting state: it drops terminals that cannot be shifted from that stack and
adds terminals that default reductions hid. `--list-errors` has no stack, so it prints the
static set.

The state numbers match the generated parser, so you supply them directly:

Expand Down
23 changes: 23 additions & 0 deletions test/calc/ErrorMessageTest.lean
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,29 @@ private def expectedNames {V : Type} : Runtime.Exec.Diagnostic V → List String
#guard expectedNames (diagnose (dummy [.LPAR, .NUM 1, .NUM 2]))
== ["PLUS", "TIMES", "RPAR", "DIV"]

/-! ### The expected list is taken after the last shift

After `1`, a `)` at the top level makes the parser reduce to `factor`, `term` and `expr`
before it rejects the `)`. The state that rejects it accepts `PLUS` and the end of input but
not `TIMES` or `DIV`, which could still follow the `1`. The expected list is computed from the
stack right after the `1`, so it has all four. -/

#guard expectedNames (diagnose (dummy [.NUM 1, .RPAR]))
== ["PLUS", "TIMES", "DIV", "end of input"]
#guard expectedNames (diagnoseSpanned (dummy [.NUM 1, .RPAR])).1
== ["PLUS", "TIMES", "DIV", "end of input"]
#guard match errorMessage (dummy [.NUM 1, .RPAR]) with
| some msg => containsStr msg "unexpected RPAR"
&& containsStr msg "expected one of: PLUS, TIMES, DIV, end of input"
| none => false

-- Inside parentheses the same position also accepts `)`.
#guard expectedNames (diagnose (dummy [.LPAR, .NUM 1, .PLUS, .PLUS]))
== ["LPAR", "NUM"]

-- Nothing consumed: the start state.
#guard expectedNames (diagnose (dummy [.PLUS])) == ["LPAR", "NUM"]

-- `diagnose`, `diagnoseSpanned` and `errorMessage` agree.
#guard (match diagnoseSpanned (dummy [.NUM 1, .NUM 2]) with
| (d, _) => expectedNames d) == expectedNames (diagnose (dummy [.NUM 1, .NUM 2]))
Expand Down