15. Precedence Climbing
An alternative to Pratt parsing
The expression problem (again)
Parsing expressions with operator precedence keeps coming up because it's genuinely tricky. You need * to bind tighter than +, you need parentheses to override everything, and you want left-to-right associativity for most operators but right-to-left for things like exponentiation and assignment.
We've seen several solutions: encoding precedence into the grammar with separate rules for each level, Pratt parsing with binding power functions, parser combinators that mirror the grammar. Precedence climbing is yet another approach — and it might be the most concise of all.
The core idea
Precedence climbing uses a single recursive function that takes a minimum precedence parameter. The function parses a "left-hand side" atom, then enters a loop: as long as the next token is a binary operator whose precedence is at least the minimum, it consumes the operator, recursively parses the right-hand side (with an adjusted minimum precedence), and builds a binary node.
That's it. One function, one loop, one recursive call.
The operator table
First, we define our operators with their precedence levels and associativity:
const operators = {
'+': { prec: 1, assoc: 'left' },
'-': { prec: 1, assoc: 'left' },
'*': { prec: 2, assoc: 'left' },
'/': { prec: 2, assoc: 'left' },
'^': { prec: 3, assoc: 'right' },
};
Higher numbers mean tighter binding. * at precedence 2 binds tighter than + at precedence 1. Exponentiation ^ at 3 is tightest.
The algorithm
function parseExpr(tokens, pos, minPrec) {
// Parse the left-hand side (an atom)
let { value: left, pos: nextPos } = parseAtom(tokens, pos);
pos = nextPos;
// Loop: consume operators at or above minPrec
while (pos < tokens.length) {
const tok = tokens[pos];
const op = operators[tok.value];
// Stop if it's not an operator or its precedence is too low
if (!op || op.prec < minPrec) break;
pos++; // consume the operator
// Compute the minimum precedence for the right-hand side
const nextMinPrec = op.assoc === 'left'
? op.prec + 1 // left-associative: right side needs HIGHER precedence
: op.prec; // right-associative: right side needs SAME precedence
// Recursively parse the right-hand side
let right;
({ value: right, pos } = parseExpr(tokens, pos, nextMinPrec));
// Build the AST node
left = { type: 'binop', op: tok.value, left, right };
}
return { value: left, pos };
}
function parseAtom(tokens, pos) {
const tok = tokens[pos];
if (tok.type === 'NUMBER') {
return { value: { type: 'number', value: Number(tok.value) }, pos: pos + 1 };
}
if (tok.value === '(') {
const result = parseExpr(tokens, pos + 1, 1); // reset to minimum precedence
// expect ')'
return { value: result.value, pos: result.pos + 1 };
}
throw new Error(`Unexpected token: ${tok.value}`);
}
That's about 30 lines of real logic. Let's trace through it.
Walking through 1 + 2 * 3 - 4
Tokens: 1, +, 2, *, 3, -, 4
Call: parseExpr(tokens, 0, minPrec=1)
parseAtomreads1— left =1- Loop: next token is
+(prec 1, left-assoc). Is ? Yes. - Consume
+. Right side needsminPrec = 2(left-assoc: prec + 1).
Recursive call: parseExpr(tokens, 2, minPrec=2)
parseAtomreads2— left =2- Loop: next token is
*(prec 2, left-assoc). Is ? Yes. - Consume
*. Right side needsminPrec = 3.
Recursive call: parseExpr(tokens, 4, minPrec=3)
parseAtomreads3— left =3- Loop: next token is
-(prec 1). Is ? No. Exit loop. - Return
3.
Back in the minPrec=2 call:
- Build node:
2 * 3 - Loop: next token is
-(prec 1). Is ? No. Exit loop. - Return
2 * 3.
Back in the minPrec=1 call:
- Build node:
1 + (2 * 3) - Loop: next token is
-(prec 1, left-assoc). Is ? Yes. - Consume
-. Right side needsminPrec = 2.
Recursive call: parseExpr(tokens, 6, minPrec=2)
parseAtomreads4— left =4- No more tokens. Return
4.
Back in the minPrec=1 call:
- Build node:
(1 + (2 * 3)) - 4 - No more tokens. Return.
Final AST:
-
/ \
+ 4
/ \
1 *
/ \
2 3
Precedence and left-associativity both come out correct.
How associativity works
The key trick is the nextMinPrec computation:
Left-associative (
+,-,*,/): the recursive call usesprec + 1. This means an operator at the same precedence level won't be consumed by the recursive call — it'll be consumed by the outer loop instead, giving left-to-right grouping.Right-associative (
^,=): the recursive call usesprec(same level). An operator at the same level will be consumed recursively, giving right-to-left grouping.
For example, 2 ^ 3 ^ 4:
With right-associativity, the recursive call for ^ uses minPrec = 3. The next ^ has prec = 3, and is true, so it's consumed recursively. Result: 2 ^ (3 ^ 4).
With left-associativity, the recursive call would use minPrec = 4. The next ^ has prec = 3, and is false, so the loop exits and the outer call picks it up. Result: (2 ^ 3) ^ 4.
Comparison with Pratt parsing
If you've read about Pratt parsing, precedence climbing will feel familiar. They're essentially the same algorithm viewed from different angles:
| Aspect | Pratt parsing | Precedence climbing |
|---|---|---|
| Dispatch | Table of "nud" and "led" functions | Single recursive function |
| Binding power | Left and right binding power per operator | Precedence + associativity flag |
| Extension | Add a new entry to the table | Add to the operator map |
| Prefix operators | "nud" function | Handled in parseAtom |
| Style | Object-oriented / table-driven | Procedural / loop-based |
The mapping is direct: Pratt's "right binding power" is what precedence climbing calls nextMinPrec. Pratt's "led" function is the body of the while loop. The algorithms produce identical parse trees for identical inputs.
Some people find Pratt parsing easier to extend (you just add functions to the table), while others prefer precedence climbing's simplicity (no table machinery, just a function and a map).
Extending the algorithm
Prefix operators
Unary minus, logical NOT, and similar prefix operators are handled in parseAtom:
function parseAtom(tokens, pos) {
const tok = tokens[pos];
// Prefix operators
if (tok.value === '-' || tok.value === '!') {
const operand = parseExpr(tokens, pos + 1, prefixPrec(tok.value));
return {
value: { type: 'unary', op: tok.value, operand: operand.value },
pos: operand.pos
};
}
// ... number and parenthesized expressions ...
}
function prefixPrec(op) {
if (op === '-') return 4; // higher than any binary operator
if (op === '!') return 4;
}
The prefix precedence should be higher than any binary operator so that -2 ^ 3 parses as (-2) ^ 3 or -(2 ^ 3) depending on your language's rules. (Most languages parse it as -(2^3), so you'd want prefix - at a lower precedence than ^ — adjust to taste.)
Postfix operators
Postfix operators like ! (factorial) or ++ can be added to the main loop, before or after binary operators:
// Inside the while loop, check for postfix operators first
if (isPostfix(tok.value) && postfixPrec(tok.value) >= minPrec) {
pos++;
left = { type: 'postfix', op: tok.value, operand: left };
continue;
}
Ternary operator
The ternary a ? b : c can be handled as a special case in the loop:
if (tok.value === '?') {
pos++; // consume '?'
const middle = parseExpr(tokens, pos, 1); // parse b with reset precedence
pos = middle.pos;
pos++; // consume ':'
const right = parseExpr(tokens, pos, ternaryPrec);
left = { type: 'ternary', cond: left, then: middle.value, else: right.value };
pos = right.pos;
continue;
}
Why it works
Precedence climbing works because of a simple invariant: each recursive call only consumes operators at or above a given precedence level. Lower-precedence operators are left for the calling frame to handle. This naturally produces the correct tree structure:
- High-precedence operators get consumed deep in the recursion and end up as leaf-adjacent nodes in the AST.
- Low-precedence operators are consumed in outer frames and become root-adjacent nodes.
The associativity trick (prec + 1 vs. prec) controls whether same-level operators group left or right by deciding whether the recursive call or the loop iteration gets to consume them.
Summary
Precedence climbing is a compact, elegant algorithm for parsing expressions with operator precedence and associativity. It's essentially Pratt parsing without the dispatch table — a single recursive function, a while loop, and an operator map. For many compilers and interpreters, it's all you need for expression parsing, and it fits in about 30 lines of code.
Try It Yourself — Precedence Climbing
Enter an arithmetic expression below. The visualizer steps through the precedence climbing algorithm, showing the call stack, the current minimum precedence, and how the AST is assembled.