13. PEG Grammars

Ordered choice and unlimited lookahead

The ambiguity problem

Context-free grammars (CFGs) have a dirty secret: they can be ambiguous. A single input string might have two completely different parse trees. The classic example is the dangling else:

if a then if b then s1 else s2

Does the else belong to the inner if or the outer one? A CFG can't tell you — both parses are valid according to the grammar. You need extra disambiguation rules bolted on from outside.

In 2004, Bryan Ford proposed an alternative called Parsing Expression Grammars (PEGs). The key innovation: alternatives are ordered. The parser tries the first option, and only if it fails does it try the second. No ambiguity, ever, by construction.

PEG vs. CFG

A PEG looks a lot like a CFG, but the meaning of / (choice) is fundamentally different.

In a CFG, A | B means "the input can match A or B" — both are valid, and if both work, the grammar is ambiguous.

In a PEG, A / B means "try A first; if A succeeds, use it and don't try B; only try B if A fails." This is called ordered choice.

That single change eliminates ambiguity entirely. It also means a PEG is not a generative grammar (it doesn't describe a set of strings) — it's a recognition formalism. It tells you how to parse, not what to parse.

PEG operators

Here are the core PEG operators, using standard notation:

Operator Syntax Meaning
Literal "text" Match exact string
Character class [a-z] Match one character in range
Any character . Match any single character
Sequence e1 e2 Match e1 then e2
Ordered choice e1 / e2 Try e1; if it fails, try e2
Zero or more e* Match e repeatedly (greedy)
One or more e+ Like e* but at least one
Optional e? Match e or nothing
And-predicate &e Succeed if e matches, but consume nothing
Not-predicate !e Succeed if e does not match, consume nothing

The predicates are PEG's secret weapon. They give you unlimited lookahead without consuming input. You can peek ahead to decide which branch to take, then actually parse it.

And-predicate example

Want to match a letter, but only if it's followed by a digit?

&[0-9] [a-z]    // Wrong: checks digit first, then tries letter
[a-z] &[0-9]    // Right: match letter, then peek at digit

Actually, let's be precise: &[0-9] checks that the next character is a digit without consuming it. So if you want "a letter followed by a digit," you'd write:

[a-z] &[0-9]

The letter is consumed, the digit is verified but left for the next rule to consume.

Not-predicate example

Match anything that's not a string delimiter:

!'"' .

"If the next character is not a quote, match any character." Repeat this with * and you can parse string contents: '"' (!'"' .)* '"'.

A PEG for arithmetic

Let's write a PEG that parses expressions like 3 + 5 * (2 - 1):

Expr    ← Term (('+' / '-') Term)*
Term    ← Factor (('*' / '/') Factor)*
Factor  ← Number / '(' Expr ')'
Number  ← [0-9]+

This looks almost identical to the CFG version, and that's typical. For most practical grammars, PEGs and CFGs produce the same results. The differences show up in edge cases — and in the guarantee that the PEG version is never ambiguous.

Handling whitespace

PEGs don't have a separate lexer, so you handle whitespace explicitly:

Expr    ← Spacing Term (('+' / '-') Spacing Term)*
Term    ← Spacing Factor (('*' / '/') Spacing Factor)*
Factor  ← Number / '(' Expr ')' Spacing
Number  ← [0-9]+ Spacing
Spacing ← [ \t\n]*

This is called scannerless parsing — the grammar handles both lexical and syntactic structure.

The greedy trap

PEG's * and + are greedy: they match as much as possible. Unlike CFG, there's no backtracking into a repetition once it's done. This can cause surprises.

Consider this PEG rule for matching C-style comments:

Comment ← '/*' .* '*/'     // WRONG!

The .* is greedy — it eats everything, including the */. The rule never succeeds. The fix uses the not-predicate:

Comment ← '/*' (!'*/' .)* '*/'

"Match any character, as long as it's not the start of */." This is a pattern you'll use constantly in PEGs.

Packrat parsing

There's a catch with PEGs. Because of ordered choice and backtracking, the same rule might be tried at the same position multiple times. In the worst case, this leads to exponential parsing time.

Packrat parsing fixes this with memoization. The idea: cache the result of every rule at every input position. If Expr was already tried at position 7, just return the cached result.

function packratParse(rules, input) {
  // memo[ruleName][position] = result
  const memo = {};

  function apply(ruleName, pos) {
    if (!memo[ruleName]) memo[ruleName] = {};
    if (memo[ruleName][pos] !== undefined) {
      return memo[ruleName][pos]; // Cache hit!
    }

    const result = rules[ruleName](input, pos, apply);
    memo[ruleName][pos] = result; // Cache it
    return result;
  }

  return apply('start', 0);
}

With memoization, every rule is tried at most once per position. If you have RR rules and NN characters, that's at most R×NR \times N calls — linear time in the input size.

The memory tradeoff

The price is memory. You're storing a result for every rule at every position. For a grammar with 50 rules and a 10,000-character input, that's 500,000 cache entries. For a large source file with a complex grammar, memory usage can be significant.

In practice, most packrat parsers use lazy memoization — only caching rules that are actually reached, which is usually a small fraction of the theoretical maximum. Some implementations use bounded caches, evicting entries that are unlikely to be needed again (the parser generally moves forward through the input).

PEG vs. Regex vs. CFG

Feature Regex PEG CFG
Recursion No Yes Yes
Ambiguity N/A Never Possible
Lookahead Limited Unlimited Depends on parser type
Greedy quantifiers Yes (default) Always N/A
Left recursion N/A Problematic Fine (LR parsers)
Time complexity O(N)O(N) O(N)O(N) with packrat O(N)O(N) for LR/LL
Space for packrat — O(R×N)O(R \times N) —
Composability Weak Strong Moderate

PEGs sit in a sweet spot: more powerful than regex (they handle recursion and nesting), simpler than full CFGs (no ambiguity to resolve), and with guaranteed linear-time parsing.

What PEGs can't do

PEGs aren't strictly a superset or subset of CFGs. There are context-free languages that no PEG can recognize, and PEGs can match some patterns that aren't context-free (using predicates).

The most practical limitation is left recursion. This PEG rule loops forever:

Expr ← Expr '+' Term / Term     // Infinite loop!

Expr tries to match Expr at the same position, which tries to match Expr, and so on. The fix is the same as with recursive descent and parser combinators: rewrite as right recursion or iteration.

Some modern PEG tools handle left recursion with special extensions, but it's not part of the original formalism.

Real-world PEG tools

  • PEG.js / Peggy (JavaScript) — write a PEG grammar, get a parser. Peggy is the actively maintained fork.
  • pest (Rust) — a PEG parser generator with excellent error messages
  • tree-sitter — uses a PEG-inspired approach with GLR fallback, powers syntax highlighting in many editors
  • LPEG (Lua) — a library for PEGs with a unique VM-based implementation
  • Parboiled (Java/Scala) — PEG parsing on the JVM

Summary

PEGs take the "try alternatives" idea from parser combinators and bake it into a formal grammar notation. Ordered choice eliminates ambiguity. Predicates give unlimited lookahead. Packrat parsing guarantees linear time. The tradeoffs — greedy-only quantifiers, no left recursion, and higher memory usage — are manageable in practice.

If you're building a parser for a new language and you want something between "hand-rolled recursive descent" and "full parser generator," a PEG tool is an excellent choice.

Try It Yourself — PEG Parsing

Enter an arithmetic expression below. The PEG parser will parse it using packrat memoization, showing which rules are tried at each position and where cache hits save work.

Parsed AST

Parse Trace & Memoization

Memo Table