PARSING: PRECEDENCE & RECURSIVE DESCENT
Why 1 + 2 * 3 is not 9
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.
// 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;
}// precedence climbing: loop at your level; each right operand needs a higher minimum
const PREC = { '+': 1, '-': 1, '*': 2, '/': 2 };
function expr(min) {
let left = primary();
while (PREC[peek()] >= min) {
const op = next();
const right = expr(PREC[op] + 1); // +1: the right operand absorbs only tighter ops
left = { op, left, right };
}
return left;
}
// call expr(1) 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.
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
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.
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).
“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.