How-to › Parse, validate and transform data

How to choose between PEG, LALR, and a hand-written parser#

Prototype peggy, Lark, chevrotain, and a hand-written parser on twenty lines of your format, and compare their size, error messages, and change cost.

Audience
API producer
Level
beginner
Topic
Write a grammar and parser
Languages
TypeScript and Python
Verified

Your service writes its own log format, and the parser for it is a pile of split(' ') calls that breaks on a quoted value with a space in it. You want a real parser. Four kinds of tool could run the grammar, each one changes how you write it, and the choice is hard to undo once other code depends on its tree.

What you get

You will end up with one log format written down in ABNF and four working parsers for it. Each parser gets three numbers: lines of code, the message for each invalid line, and the lines changed to add one rule. This is for you if you are about to pick a parser tool for a format you own.

Short answer

Write the format down in ABNF, then prototype two or more parsers on the same twenty sample lines. Record each one’s lines of code, its message for each invalid line, and the lines it changes to add one rule. peggy and Lark keep a grammar file as the source of truth, chevrotain and a hand-written parser keep code, and PEG ordered choice can reject lines the ABNF accepts.

You will need

Node 22 or later, Python 3.8 or later for Lark, and twenty sample lines in your format, three of them invalid. Verified 2026-11-29 against Node 22.23.5, Python 3.13.18 and 3.12.3, peggy 5.1.1, chevrotain 13.2.0, and Lark 1.3.1. peggy 5.1.1 and chevrotain 13.2.0 both declare node >= 22 in their engines field. npm ci in the sample directory installs Lark from PyPI into pydeps/, pinned by hash.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
chevrotainAn editor must keep parsing past an error, in JavaScript or TypeScriptLexer modes and keyword tokens for a context-sensitive format, and token names in its messagesThe grammar must be readable by people who do not write JavaScript
hand-written recursive descentUsers read the errors, and the format is small and stableThree times the lines of a grammar, and no grammar to show anyoneSeveral people change the format, or a second language needs it
LarkThe parser runs in Python, and the grammar should stay declarativeA Python runtime, and messages that name terminals such as $ENDThe parser must run in Node or the browser with no Python
peggyA JavaScript parser from a grammar file, with the fewest linesOrdered choice, so an alternative order copied from ABNF can reject valid inputAn editor needs recovery after the first error

peggy and Lark are the shortest prototypes here, at 30 lines each, and both keep the format in a file that reads as a grammar. peggy costs you ordered choice, which the last sections are about. Lark costs you a Python process. chevrotain and the hand-written parser are code, which costs lines and buys control: recovery for an editor from chevrotain, and the hand-written parser’s messages for a person.

Answer four questions before you prototype

The format here is one log line: a UTC timestamp, a level, key=value fields, and optional free text after -. Each question below removes options before you write any code.

Operator precedence. A log line has no operators, so this one rules nothing out. A filter language does, and then the prototype to build compares a table of binding powers in a hand-written parser with layered rules in a grammar.

Error recovery inside an editor. chevrotain ships recovery heuristics, off by default and enabled with the recoveryEnabled parser option, as its fault tolerance tutorial says. Lark’s parse() takes an on_error callback, for LALR only. The peggy documentation has no section on recovery, and a search of it for “recover” finds nothing. A hand-written parser recovers however you write it.

One grammar in more than one language. peggy generates JavaScript, and a chevrotain grammar is JavaScript code. Lark’s grammar is Python’s, and its JavaScript port, Lark.js, says in its README that it needs Lark 1.1.5 or earlier. A hand-written parser is one parser per language.

The maintainer in two years. A grammar file changes in a diff a reviewer can read as grammar. A parser written as code changes as code, so its reviewer needs to know the parsing technique too.

Write the format down before choosing a tool

The ABNF is the specification, and every parser below is checked against it rather than against the others.1 %s marks a string as case-sensitive, which plain ABNF strings are not.

; One log line: a UTC timestamp, a level, key=value fields, and
; optional free text after " - ". RFC 5234 ABNF with RFC 7405 %s.
line      = timestamp SP level *(SP item)
item      = field / "-" SP text
timestamp = date "T" time "Z"
date      = 4DIGIT "-" 2DIGIT "-" 2DIGIT
time      = 2DIGIT ":" 2DIGIT ":" 2DIGIT ["." 1*3DIGIT]
level     = %s"DEBUG" / %s"INFO" / %s"WARN" / %s"WARNING" / %s"ERROR"
field     = key "=" value
key       = ALPHA *(ALPHA / DIGIT / "_")
value     = quoted / 1*vchar
vchar     = %x21 / %x23-3C / %x3E-7E
quoted    = DQUOTE *(%x20-21 / %x23-7E) DQUOTE
text      = *(%x20-7E)

inputs.mjs holds the twenty lines: 17 valid ones that cover each rule, and three invalid ones, an unknown level, an empty value, and an unterminated quote.

Prototype them on the same twenty lines

compare.mjs runs all four parsers over the twenty lines. Then it repeats the run with the copies in with-component/, which add one rule, an optional [auth] tag after the level.

node compare.mjs
lines of code, blank and comment-only lines excluded
  chevrotain     72  chevrotain-log.mjs
  hand-written   95  hand-log.mjs
  Lark (LALR)    30  log.lark + lark_log.py
  peggy (PEG)    30  log.peggy + peggy-log.mjs

17 valid lines: 4 of 4 parsers build the same records
3 invalid lines: 4 of 4 parsers reject all three

2026-11-29T10:15:02Z NOTICE user=alice
  chevrotain    column 22: MismatchedTokenException: Expecting token of type --> Level <-- but found --> 'NOTICE' <--
  hand-written  column 22: expected a level (DEBUG, INFO, WARN, WARNING or ERROR), found "N"
  Lark (LALR)   Unexpected token Token('KEY', 'NOTICE') at line 1, column 22.
  peggy (PEG)   Expected level but "N" found.

2026-11-29T10:15:02Z INFO user=
  chevrotain    end of line: NoViableAltException: Expecting: one of these possible Token sequences: 1. [Quoted] 2. [Value] but found: ''
  hand-written  column 32: expected a value after "=", found the end of the line
  Lark (LALR)   Unexpected token Token('$END', '') at line 1, column 31.
  peggy (PEG)   Expected value but end of input found.

2026-11-29T10:15:02Z INFO msg="unterminated
  chevrotain    column 31: unexpected character: ->"<- at offset: 30, skipped 1 characters.
  hand-written  column 44: expected a closing quote, found the end of the line
  Lark (LALR)   Unexpected token Token('TEXT', '"unterminated') at line 1, column 31.
  peggy (PEG)   Expected value but "\"" found.

adding one rule, an optional [component] after the level: lines changed
  chevrotain    +9 -3
  hand-written  +15 -1
  Lark (LALR)   +5 -3
  peggy (PEG)   +2 -2
  same records from all 4 on "2026-11-29T10:15:02Z INFO [auth] user=alice" and the 17 valid lines: true

Read the unterminated quote first. Only the hand-written parser names the missing closing quote. peggy blames the whole value because value is a named rule, and its documentation says it prefers to match named rules completely or not at all. Lark’s contextual lexer finds no value token, and the error names the TEXT terminal, which the parser was not expecting there.

The empty value shows a second difference. The end-of-input token in chevrotain carries offset -1, so its message has no column unless you compute one. Lark gives column 31, the = before the gap.

Lines of code favor the grammar files, at 30 lines each against 72 for chevrotain and 95 by hand. The change cost points the same way: four lines for peggy against sixteen for the hand-written parser. Minutes spent adding a rule depend on who adds it, so the sample counts changed lines instead.

Check it worked

choose.test.mjs asserts the claims in that output with the Node test runner. Four parsers must build identical records for the 17 valid lines and reject the three invalid ones. They must also agree on 13 neighbors, lines such as a=b=c or a tab in the text, where a looser parser would show.

node --test choose.test.mjs
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0

A test that only compares the four parsers with each other passes when all four share one bug. The second test also pins one record field by field, so agreement alone is not enough.

When it goes wrong

A PEG grammar translated rule for rule from the ABNF rejects a line the ABNF accepts. The / in ABNF lists alternatives in no order, while the / in PEG tries them in order and keeps the first that matches.2 With the levels in the ABNF’s order, WARN matches the start of WARNING, the choice is settled, and the next rule meets I where it wanted a space.

node pitfall.mjs
peggy, level = "DEBUG" / "INFO" / "WARN" / "WARNING" / "ERROR"  (copied from the ABNF)
  accepts 16 of 17 valid lines
  rejects 2026-11-29T10:15:02Z WARNING disk=91% mount=/var
          column 26: Expected " " but "I" found.
peggy, level = "DEBUG" / "INFO" / "WARNING" / "WARN" / "ERROR"  (longest first)
  accepts 17 of 17 valid lines
Lark LALR, LEVEL: "DEBUG" | "INFO" | "WARN" | "WARNING" | "ERROR"
  accepts 17 of 17 valid lines

The failure is silent for any sample without a WARNING line, because the other 16 lines pass. Put the longer alternative first wherever one alternative is a prefix of another:

level "level"
  = "DEBUG" / "INFO" / "WARNING" / "WARN" / "ERROR"

Lark accepts either order because it compiles a terminal’s string alternatives into one regular expression and sorts them longest first. The hand-written parser has the same trap in its LEVELS array, which lists WARNING before WARN for the same reason.

Two more failures show up in a chevrotain prototype. A keyword token such as INFO needs longer_alt, as its tutorial shows for keywords and identifiers, so that a key such as INFOx stays one token. A format where - starts free text in one place and a value in another needs lexer modes, as chevrotain-log.mjs uses after each =.

When not to do this

Do not prototype four parsers for a format with one consumer and a short life. Pick the tool the team already runs, write the twenty lines as its tests, and move on.

Do not choose peggy for an editor that must keep parsing after a mistake, because its parser throws at the first error. chevrotain is the better choice in that case.

Do not take Lark into a Node service to get a declarative grammar. A Python process beside the service, or a port that trails the Python release, costs more than peggy’s ordered choice does.

Do not hand-write the parser while the format is still changing. The [component] rule took one more function and an edit to its caller, where peggy changed two lines. The specification also lives only in the ABNF file you keep beside it. The hand-written parser pays back once the format is stable and people read its errors.

Last verified

Verified 2026-11-29 against Node 22.23.5, Python 3.13.18 and 3.12.3, peggy 5.1.1, chevrotain 13.2.0, and Lark 1.3.1. Every output block is what the command preceding it printed. Lark.js was not run, and what the page says of it is read from its README. The recovery features of chevrotain and Lark are read from their documentation and were not exercised.

Footnotes

  1. ABNF’s case rule is the one most often misremembered. RFC 5234 says ABNF strings are case insensitive, so a plain "INFO" also matches info. Case-sensitive strings needed a second document, RFC 7405, which added %s for them in December 2014, almost seven years after the January 2008 grammar it amends. ↩︎ Back to text

  2. The slash is the same character with opposite meanings. RFC 5234 defines / as plain alternatives, and Bryan Ford’s 2004 paper that introduced parsing expression grammars uses / for prioritized choice, in place of the unordered | of EBNF. The paper gives its own example: the rules a b / a and a / a b differ, because the second alternative of the latter never succeeds. ↩︎ 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.