Notes on Pratt parsing: replacing the operator stack with the call stack
The author set out to write a parser for C expressions that may later grow into a compiler, choosing Pratt parsing[1] after previously building a calculator with the shunting yard[2] algorithm. The post notes that Pratt parsing is absent from the conventional computer science path: the dragon book does not mention it, and programming language courses teach either LR or recursive descent, so the technique lives mostly in compiler development and PLT circles. The most mainstream mention the author knows is Crafting Interpreters, which was used to get oriented alongside Pratt's original paper, read for practice with formal texts. The approach clicked once the author related it back to shunting yard, and the observations are written down so they are not forgotten.
In shunting yard, an output stream and an operator stack do the work, and operators are defined with binding powers[3]: higher binding power means an operator binds tighter to its arguments, as * does compared with + in arithmetic. Standalone tokens go straight to the output, an operator of higher binding power than the stack top is pushed, and otherwise operators of higher or equal binding power are popped first, which assumes all operators are left-associative. The problem is extensibility: the algorithm has no concept of subexpressions, parentheses require attaching special behavior to the ) token, and unary operators, right-associative expressions and functions with variable arguments would get messy.
The shift to Pratt replaces the explicit operator stack with the call stack: the parser nests into subexpressions only when entering them, rather than descending through every precedence level for every expression as in recursive descent. The C version shown produces the same postfix notation[4] output as the shunting yard parser. Two gains follow: prefix operators get first-class handling, and arbitrary code can be assigned to any operator as soon as it is seen, as in recursive descent — adding parentheses, for instance, takes only an entry in the binding power table and a small paren() subroutine.
Read the original unix.dogDiscussion on GeekNews
Sources
-
KRGeekNews KO
Pratt 파싱을 기억하려고 정리해 보기
-
unix.dog
writing about pratt parsing so I remember it


