A programmer building a C-expression parser revisits Pratt parsing to understand and remember how it works, relating it to the shunting-yard algorithm. Shunting yard uses an explicit operator stack and binding powers: tighter-binding operators stay on the stack, while operators of equal or lower precedence are emitted first. This simple approach handles basic arithmetic, but adding parentheses, unary operators, right-associative operators, or variable-argument functions requires special cases that can become awkward.
Pratt parsing makes the operator stack implicit in recursive calls. The parser first handles a token that can begin an expression, such as a number or a prefix operator; Pratt called these handlers “nud” functions. It then processes following infix or postfix operators, called “led” functions, according to binding power. Each operator triggers a recursive parse of its subexpression, and parsing returns when the next operator binds less tightly - functionally like unwinding the shunting-yard stack. The author demonstrates this with a small parser that emits postfix output, then adds parentheses by parsing their contents as a nested expression and checking for the closing delimiter. The key benefit is extensibility: operators can have their own parsing behavior while the central parser remains compact. A table combining binding power with prefix and infix/postfix handlers provides a practical structure for a more realistic parser, including unary and postfix operators.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.