How-to › Parse, validate and transform data

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.

Audience
Library maintainer
Level
intermediate
Topic
Write a grammar and parser
Languages
TypeScript
Verified

Read first: Write a log format in ABNF and compile it to a rule table

A log line that your own service wrote fails to parse. The message names a column and an unexpected character, and the character at that column is an opening quote that the grammar plainly allows. You read the rule for quoted values three times, and it still looks right to you.

What you get

You will end up with the first character your grammar refuses in a valid line, found by bisecting it. A trace and the compiled grammar then name the rule that refuses it. This is for you if a parser rejects input you know is valid.

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

ApproachWhen it fitsWhat it costs youWhen to pick something else
@tabnas/debugThe grammar runs on the tabnas engine, and you need the rule table it compiledHundreds of trace lines per input line, and compiled names such as T4 to decodeThe grammar runs on any other engine
peggy —traceA peggy grammar, and you want every rule entered and left, with positionsRule events only, so a failing character class inside a rule never appearsThe rule that fails is long, and you need the character
tree-sitter parse —debugA tree-sitter grammar, where the lexer and the parse stack are the questionsA generated C parser to compile before any trace, plus a grammar of its ownYour 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:

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.

npx peggy --trace -t '2026-11-29T08:02:45Z INFO user=alice msg="reset, then sent" retries=1' log.peggy
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.

node tabnas-debug.mjs
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.

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.

node bisect.mjs
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, and tests every printable ASCII character inside quotes, not only the comma.

node --test debug.test.mjs
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 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.

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.

Footnotes

  1. The tree-sitter documentation 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. ↩︎ Back to text

  2. The peggy documentation 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.