PARSING: PRECEDENCE & RECURSIVE DESCENT

Why 1 + 2 * 3 is not 9

L215 MINCOMPILERS
PREDICT

A parser uses expr := term ('-' expr)?: an expression is a term, optionally followed by '-' and another whole expression, so it recurses on the right. What does it return for 10 - 4 - 3?

A parser turns a flat list of tokens into a tree. The tree decides the meaning: whatever sits lower in the tree is computed first. Two rules fix the shape. Precedence: * and / sit below + and -. Associativity: equal operators group left to right, so 10 - 4 - 3 is (10 - 4) - 3.

Recursive descent writes one function per precedence level. The trap is recursing on the right operand: it gets precedence right and associativity wrong. Precedence climbing loops at each level instead, and parses each right operand with a minimum precedence one higher, so the recursion only absorbs strictly tighter operators.

▶ SIMULATION
LEXER
tokens 0
—
AST · PRECEDENCE CLIMBING
—
nodes built, in order: —
RESULT
tree value —
reference —
select a parser
source10 - 4 - 3 * 2
reference RPN (shunting-yard)—
✓ tree respects precedence and left associativity✓ evaluates like the reference
SCHEDULE
01[PARSER]use the left-to-right parser (no precedence)
02[LEXER]lex: characters → tokens
03[PARSER]parse: tokens → AST
04[EVAL]evaluate the AST
05[REF]compare with the shunting-yard reference
Start of left-to-right scenario. 5 steps.
// expr := term (('+'|'-') expr)?      <- recurses on the RIGHT
function expr() {
  const left = term();
  if (peek() === '+' || peek() === '-') {
    const op = next();
    return { op, left, right: expr() };  // 10 - 4 - 3 => 10 - (4 - 3)
  }
  return left;
}

The invariant strip checks the tree shape and the final value. LEFT-TO-RIGHT breaks both on the default expression; RIGHT-RECURSIVE breaks the shape on every chain, and the value only on - and /; PRECEDENCE CLIMBING holds on every expression. Try EXPRESSION # 7: right value, wrong tree.

BREAK IT NOT YET

The right-recursive grammar gets precedence right: 1 + 2 * 3 comes out 7. Slide EXPRESSION # until it disagrees with the reference on an expression that the plain left-to-right parser gets right. That isolates the second bug.

GOAL: right-recursive is wrong while left-to-right is right

FIX IT NOT YET

Rewrite parseExpr so * and / bind tighter than + and -, and operators of equal precedence group left to right. The grader checks the shape of your tree and its value against a reference on 14 expressions.

Mental model:

the tree is the meaning. A parser’s job is to put tighter operators lower and to group equal operators to the left. Precedence climbing does both with one number: parse the right operand with a minimum precedence one above the current operator, and loop for the rest.

IN PRODUCTION

Expression parsers in calculators, spreadsheet formulas, template languages, query filters, config DSLs, and every hand-written compiler front end (Clang, V8, rustc and Go all hand-write recursive descent with precedence climbing or Pratt parsing for expressions).

IN INTERVIEWS

“Write a parser for arithmetic expressions” or “Evaluate this string without eval.” Tokenize first, then use precedence climbing or shunting-yard; say why the naive right-recursive grammar is right associative, and test with a chain of subtractions.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: CLOSURES & ESCAPE ANALYSIS →