12. Parser Combinators
Building parsers from small composable functions
The idea
Imagine you have a tiny function that can parse a single digit. And another tiny function that parses a + sign. Now imagine you could glue them together — "parse a digit, then a plus, then another digit" — and get back a new function that parses 3+5.
That's parser combinators in a nutshell: small parsing functions combined into bigger parsing functions using a handful of generic glue operations. No grammar files, no code generation — just functions calling functions.
What is a parser?
Before we build combinators, we need to agree on what a "parser" is as a data type. A parser is a function that takes an input string (and a position) and returns either a success (the parsed value plus how far we got) or a failure.
// A parser result
// Success: { success: true, value: ..., rest: ... }
// Failure: { success: false, expected: ... }
function parse(parser, input) {
return parser(input, 0);
}
We'll represent input position as an index into the string. A parser takes (input, pos) and returns a result object.
The basic combinators
literal — match an exact string
The simplest parser. It checks whether the input at the current position matches a fixed string.
function literal(str) {
return (input, pos) => {
if (input.startsWith(str, pos)) {
return { success: true, value: str, rest: pos + str.length };
}
return { success: false, expected: `"${str}"`, pos };
};
}
Usage: literal("hello") returns a parser that matches the text hello.
regex — match a pattern
Like literal, but uses a regular expression.
function regex(pattern, name) {
// Ensure the regex is sticky (matches at exact position)
const re = new RegExp(pattern.source, 'y');
return (input, pos) => {
re.lastIndex = pos;
const match = re.exec(input);
if (match) {
return { success: true, value: match[0], rest: pos + match[0].length };
}
return { success: false, expected: name || pattern.toString(), pos };
};
}
Usage: regex(/[0-9]+/, "number") matches one or more digits.
seq — match one thing after another
This is where combination starts. seq takes multiple parsers and runs them in sequence. All must succeed.
function seq(...parsers) {
return (input, pos) => {
const values = [];
let current = pos;
for (const p of parsers) {
const result = p(input, current);
if (!result.success) return result;
values.push(result.value);
current = result.rest;
}
return { success: true, value: values, rest: current };
};
}
Usage: seq(literal("("), regex(/[0-9]+/), literal(")")) matches (123).
alt — try alternatives
alt tries each parser in order and returns the first success.
function alt(...parsers) {
return (input, pos) => {
let furthest = null;
for (const p of parsers) {
const result = p(input, pos);
if (result.success) return result;
// Track the furthest failure for better error messages
if (!furthest || result.pos >= furthest.pos) {
furthest = result;
}
}
return furthest;
};
}
Usage: alt(literal("true"), literal("false")) matches either boolean keyword.
many — zero or more repetitions
many applies a parser repeatedly until it fails, collecting all the results. It always succeeds (zero matches is fine).
function many(parser) {
return (input, pos) => {
const values = [];
let current = pos;
while (true) {
const result = parser(input, current);
if (!result.success) break;
values.push(result.value);
current = result.rest;
}
return { success: true, value: values, rest: current };
};
}
There's also many1 (one or more), which is just many with a check that at least one match occurred.
map — transform the result
Parsing is useless if you can't do something with the matched text. map applies a function to a successful parse result.
function map(parser, fn) {
return (input, pos) => {
const result = parser(input, pos);
if (!result.success) return result;
return { ...result, value: fn(result.value) };
};
}
Usage: map(regex(/[0-9]+/), s => parseInt(s, 10)) parses a number and converts it to an integer.
Building an expression parser
Now let's combine these to parse arithmetic like 3 + 5 * 2. We need:
- Numbers
- The operators
+,-,*,/ - Operator precedence (
*binds tighter than+) - Parentheses
// Whitespace skipper
const ws = regex(/\s*/, "whitespace");
function token(parser) {
return map(seq(parser, ws), ([value]) => value);
}
// Atoms
const number = token(map(regex(/[0-9]+/, "number"), Number));
const lparen = token(literal("("));
const rparen = token(literal(")"));
// Operators by precedence
const mulOp = token(alt(literal("*"), literal("/")));
const addOp = token(alt(literal("+"), literal("-")));
For the grammar rules, we need recursion: an expression can contain parenthesized sub-expressions. This is where we hit a snag.
Lazy evaluation for recursion
If expr refers to atom, and atom refers to expr (for parenthesized groups), we have a circular dependency. Both can't be defined before the other.
The fix: wrap recursive references in a lazy thunk.
function lazy(fn) {
return (input, pos) => fn()(input, pos);
}
Now we can build the recursive grammar:
// atom = number | "(" expr ")"
const atom = alt(
number,
map(seq(lparen, lazy(() => expr), rparen), ([, e]) => e)
);
// term = atom (("*" | "/") atom)*
const term = map(
seq(atom, many(seq(mulOp, atom))),
([first, rest]) =>
rest.reduce((left, [op, right]) =>
({ type: 'binop', op, left, right }), first)
);
// expr = term (("+" | "-") term)*
const expr = map(
seq(term, many(seq(addOp, term))),
([first, rest]) =>
rest.reduce((left, [op, right]) =>
({ type: 'binop', op, left, right }), first)
);
Let's trace 3 + 5 * 2:
exprcallsterm, which callsatom— matches3termtriesmulOp atom— fails (next token is+), sotermreturns3exprtriesaddOp term— matches+- The inner
termmatches5, then* 2, building{ op: "*", left: 5, right: 2 } exprbuilds{ op: "+", left: 3, right: { op: "*", left: 5, right: 2 } }
Precedence falls out naturally from the grammar structure, just like in recursive descent.
Combinators vs. recursive descent
Parser combinators and hand-written recursive descent are the same thing wearing different clothes:
| Aspect | Recursive descent | Combinators |
|---|---|---|
| Grammar rule | A function you write | A combinator expression |
| Sequence | Sequential statements | seq(a, b, c) |
| Choice | if/else or switch |
alt(a, b, c) |
| Repetition | while loop |
many(p) |
| Transformation | Code after the match | map(p, fn) |
| Recursion | Function calls itself | lazy(() => p) |
The power is identical — both parse exactly the class of LL grammars. Combinators trade the explicitness of hand-written code for composability. You can reuse combinators across projects, store parsers in data structures, and build grammars dynamically.
The left recursion problem
Just like recursive descent, basic combinators can't handle left recursion:
expr → expr "+" term // left-recursive!
If expr calls itself as the first thing it does, you get infinite recursion. The standard fix is the same: rewrite as iteration with many:
expr → term ("+" term)*
Some advanced combinator libraries handle left recursion automatically using techniques like memoization with growing seeds, but that's beyond our scope.
Error handling in combinators
One weakness of basic combinators is error messages. When alt tries three alternatives and all fail, which failure should it report? The usual answer: the one that got furthest into the input, since it was probably the closest match.
More sophisticated libraries track a "committed" state — once a parser has consumed input, failure becomes an error rather than backtracking. This is similar to how PEG grammars work, which we'll explore in the next article.
Real-world libraries
Parser combinators are popular in functional programming communities:
- Parsec (Haskell) — the library that popularized combinators
- FParsec (F#) — a Parsec port with excellent error messages
- nom (Rust) — zero-copy combinators, great for binary formats
- Arcsecond (JavaScript) — a small, readable combinator library
- Combine (Swift) — though the name now collides with Apple's framework
These libraries add features we skipped: labeled errors, backtracking control, context-sensitive parsing, and streaming input. But the core idea — tiny parsers composed into big ones — is exactly what we built here.
Summary
Parser combinators let you express grammars as compositions of functions. The building blocks are simple:
literalandregexfor matching textseqfor sequencing,altfor choicemanyfor repetition,mapfor transformationlazyfor recursive grammars
They produce the same parsers as hand-written recursive descent, but in a style that's more declarative, more reusable, and — if you like functional programming — more fun.
Try It Yourself — Parser Combinators
Enter an arithmetic expression below. The combinator-based parser will parse it step by step, showing which combinators fire and how the AST is built from the bottom up.