# How to debug a grammar that rejects valid input

> Find why a grammar refuses a valid line with peggy --trace, @tabnas/debug, and a bisection of the input, before you change a single rule.

Source: https://voxgig.com/howto/debug-a-grammar-that-rejects-valid-input

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Reproduce the rejection with one line, then bisect that line to the first character the parser refuses, because the reported error position is often where backtracking gave up. Read the path with `peggy --trace` or the `@tabnas/debug` trace, and read the compiled rule with `tn.debug.model().abnf`. Fix the rule, and keep the line as a test.

---
## You will need

Node 22 or later, a grammar, and one input it wrongly rejects. Verified 2026-11-30 against Node
22.23.5, peggy 5.1.1, `@tabnas/debug` 0.3.13, `@tabnas/parser` 0.12.21, and `@tabnas/abnf` 0.5.1.
The four `@tabnas` packages declare `node >= 24` in their `engines` field and ran here under Node
22 after an `EBADENGINE` warning at install.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [`@tabnas/debug`](https://github.com/tabnas/debug) | The grammar runs on the tabnas engine, and you need the rule table it compiled | Hundreds of trace lines per input line, and compiled names such as `T4` to decode | The grammar runs on any other engine |
| [peggy --trace](https://peggyjs.org/documentation.html#generating-a-parser-command-line) | A peggy grammar, and you want every rule entered and left, with positions | Rule events only, so a failing character class inside a rule never appears | The rule that fails is long, and you need the character |
| [tree-sitter parse --debug](https://tree-sitter.github.io/tree-sitter/cli/parse.html#-d--debug) | A tree-sitter grammar, where the lexer and the parse stack are the questions | A generated C parser to compile before any trace, plus a grammar of its own | Your grammar is not a tree-sitter grammar |

Voxgig maintains tabnas. It is one of three options here, not the recommendation.

The two traces answer the question of which path the parser took, and both are long. The rendered
grammar from `@tabnas/debug` answers a different question, what the engine is running, in a few
lines with no path at all. tree-sitter's log shows its lexer beside the parse stack, at the price of
a C build step.[^1] peggy's trace stops at the start of the value, so the bisection below finds the
character from the input side, whichever parser runs.

## Reproduce the rejection with one line

`lines.txt` holds five valid lines. Both `log.peggy` and `log.abnf` accept four of them and refuse
the fourth:

```text title="lines.txt"
2026-11-29T08:00:00Z INFO service=billing version=4.2.1 - starting
2026-11-29T08:02:44Z ERROR host=db1 retries=3 - connection refused
2026-11-29T08:02:45Z INFO user=alice msg="password reset sent"
2026-11-29T08:02:45Z INFO user=alice msg="reset, then sent" retries=1
2026-11-29T08:03:00Z INFO note=""
```

One failing line and one passing neighbor are worth more than a log file. The third line has a
quoted value too, so quoting as such is not the problem.

## Trace the path with peggy

`--trace` makes the generated parser log each rule it enters, matches, and fails, with a range of
positions. `-t` parses one string and exits with code 2 when it fails.

```bash
npx peggy --trace -t '2026-11-29T08:02:45Z INFO user=alice msg="reset, then sent" retries=1' log.peggy
```

```text output
1:38-1:38 rule.enter   item
1:38-1:38 rule.enter     field
1:38-1:38 rule.enter       key
1:38-1:41 rule.match       key
1:42-1:42 rule.enter       value
1:42-1:42 rule.fail        value
1:38-1:38 rule.fail      field
1:38-1:38 rule.fail    item
1:1-1:1 rule.fail  line
Error running test
Error: Expected value but "\"" found.
 --> command line:1:42
  |
1 | 2026-11-29T08:02:45Z INFO user=alice msg="reset, then sent" retries=1
  |                                          ^
```

The trace narrows the failure to `value` at column 42. It cannot go further, because the
character classes inside `value` are not rules and emit no events. The error points at the
opening quote for the same reason: `value` is a named rule, and peggy reports a named rule's
failure at the place the rule started.[^2]

## Ask tabnas what it compiled

`@tabnas/debug` installs as a plugin. Its `trace` option logs every step of the engine, and
`tn.debug.model().abnf` renders the live rule table back as ABNF. `tabnas-debug.mjs` collects the
trace for the same line and prints the end of it, then the rendered rules on that path.

```bash
node tabnas-debug.mjs
```

```text output
trace for one 69-character line: 288 rule and lex lines, 1221 with every kind on
last token read: "," as #RXA___U0023__U002F
last rule steps:
  _gen35_star__gen34_group~142:CLOSE
  value$alt0~115:CLOSE
  value$alt0$step1~143:OPEN
  DQUOTE~144:OPEN

live grammar from tn.debug.model().abnf, rules on that path:
  value-alt0 = T4 *( ALPHA / DIGIT / SP ) value-alt0-step1
  value = value-alt0 / value-alt1
  quoted = T4 *( ALPHA / DIGIT / SP ) DQUOTE
plugins: abnf, Debug
```

The last token read is the comma, and the engine was waiting for `DQUOTE` when it arrived. The
rendered `quoted` rule says why in one line: inside the quotes it allows letters, digits, and
spaces. That is what the engine runs, whatever the source file claims, which is the point of
reading it from the live instance after every plugin has run. The `plugins` line lists them.

## Bisect the line before you change the grammar

The error position is where the parser gave up, which is not always where the mismatch began.
peggy says column 42 and tabnas says column 48 for the same line. `bisect.mjs` finds the
character from the input side, so it does not depend on the parser's report.

```ts title="bisect.mjs"
export function bisect(parse, line) {
  if (parse(line).ok) throw new Error('the parser accepts this line, so there is nothing to bisect')
  const { head, items: all } = items(line)
  if (!parse(head).ok) return { item: null, column: null, note: 'the timestamp and level alone fail' }
  const failing = all.filter((it) => !parse(`${head} ${it.text}`).ok)
  if (failing.length === 0) return { item: null, column: null, note: 'no item fails alone' }
```

It parses each field alone after the timestamp and level. Then it binary-searches the failing
value's prefixes, closing the quote each time, until it finds the shortest prefix the parser
refuses.

```bash
node bisect.mjs
```

```text output
2026-11-29T08:02:45Z INFO user=alice msg="reset, then sent" retries=1
peggy
  error reported at column 42: Expected value but "\"" found.
  failing item: msg="reset, then sent"
  first refused character: "," at column 48
@tabnas/abnf
  error reported at column 48: [tabnas/unexpected]: unexpected character(s): ,
  failing item: msg="reset, then sent"
  first refused character: "," at column 48
```

Both grammars refuse the comma. tabnas reported the comma itself, the character that matched no
active alternative, and peggy reported the start of the value it abandoned.

## Check it worked

`log-fixed.peggy` and `log-fixed.abnf` widen the quoted value to every printable character except
the double quote, as the format says. `debug.test.mjs` holds both versions to that, with the
[Node test runner](https://nodejs.org/api/test.html), and tests every printable ASCII character
inside quotes, not only the comma.

```bash
node --test debug.test.mjs
```

```text output
1..11
# tests 11
# suites 0
# pass 11
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

The tests also pin the two error columns, 42 and 48, and check that no peggy trace event reaches
column 48. If a later release changes either report, the test says so.

## When it goes wrong

The bisection throws `nothing to bisect`. The parser in the script accepts the line, so the
rejection you saw came from another grammar file, another start rule, or other options. Load the
grammar exactly as the failing program does, then bisect.

The rendered grammar is hard to read. Generated names such as `T4` and `RXA---U0023--U002F` stand
for tokens, and the token table at the end of `tn.debug.model().abnf` maps each one to its
characters: `T4 = %x22` is the double quote.

The fixed grammar accepts a tab inside a quoted value under tabnas. By default the engine's lexer
skips spaces and tabs between tokens, as the
[`space` options](https://github.com/tabnas/parser/blob/main/ts/doc/options.md) show, so the tab
never reaches the rule. `parsers.mjs` sets `space.lex` to `false`, and the tests show the tab accepted by default and
refused with that setting.

## When not to do this

Do not start with a full trace on a long input. 1221 lines for one 69-character line is the
measure here, and a trace of a file buries the one step that matters. Cut the input to one line
first.

Do not install `@tabnas/debug` for a grammar that runs on another engine. It reads the tabnas rule
table and nothing else, so peggy's trace or tree-sitter's log is the tool there. For a
tree-sitter grammar whose lexer splits the input wrongly, `tree-sitter parse --debug` is the
better choice, because it logs the lexer beside the parser.

Do not edit the grammar on the strength of the reported column. Here it pointed at a quote that
was correct, and the defect sat six characters later.

## Related how-tos

- [Recover from syntax errors and report several in one parse](/howto/report-multiple-syntax-errors-in-one-parse)

- [Remove left recursion from a PEG grammar](/howto/remove-left-recursion-from-a-peg-grammar)

- [Attach parse actions to grammar rules by name](/howto/attach-parse-actions-by-rule-name)

- [Write a log format in ABNF and compile it to a rule table](/howto/abnf-grammar-for-a-log-format)

- [Choose between PEG, LALR, and a hand-written parser](/howto/choose-a-parsing-approach-for-your-format)

## Last verified

Verified 2026-11-30 against Node 22.23.5, peggy 5.1.1, `@tabnas/debug` 0.3.13, `@tabnas/parser`
0.12.21, and `@tabnas/abnf` 0.5.1. Every output block is what the command preceding it printed.
tree-sitter was not run, so what the page says of `tree-sitter parse --debug` is read from its
documentation.

[^1]: The [tree-sitter documentation](https://tree-sitter.github.io/tree-sitter/cli/parse.html#-d--debug)
describes two levels of the same habit. `--debug` writes logs from the parser and the lexer to stderr,
and `--debug-graph` adds graphs of the stack and parse trees, drawn with the Graphviz `dot` tool and
written to `log.html`.

[^2]: The [peggy documentation](https://peggyjs.org/documentation.html#error-messages) says that
peggy prefers to match named rules completely or not at all, and that unnamed rules can produce an
error in the middle of their own parts. A rule given a human-readable name is therefore
blamed in that name, at its first character, for whatever went wrong inside it. The name buys a
readable message at the cost of a precise column.