You Don't Need to Understand Pratt Parsing to Use It
Pratt parsing is a black box
Pratt parsing fits in nine lines of code, and that snippet is the least important thing to learn. What matters is the mindset: register semantic actions on terminals rather than production rules, splitting tokens into nuds (expect nothing to the left) and leds (expect something). The author, who built a Pratt-based compiler without studying the algorithm, argues this shift eliminates left-recursion headaches, backtracking, and repeated actions, and turns table gaps into extension points for macros and custom operators.
Pratt takes parsing, which is a really complicated thing, and reduces it to one simple question: what do we expect to see to the left of a token?
- vinipsmaker
Author here.
I was using Pratt parsing for almost a year in a macro-heavy language that I've been developing before finally sitting down on my chair to write my thoughts on Pratt parsing. Code is closed right now because I don't want LLMs training on my code before 0.1, but I'll open source it again later.
Happy to answer questions.
- ghusbands
I've written a few Pratt parsers in my time. You don't need a lexer and you can have more parser states than are implied by 'nud' and 'led'. They can be incredibly extensible. For example, if you can parse the expression "{a:1, b:2}" then you might naturally have an Expr state (nud), a Between state (led) and a DictKey state; that might initially accept just an identifier and a colon before recursing into Expr state, but you could later add dynamic expressions, perhaps via a macro, to support [expr] as a key.
- e12e
I'd like to see a bit more about how compares to peg or something like ohm/ometa - am I correct assuming you pretty much give up the benefits of a readable grammar as documentation?
Maybe I just need to see something super simple like a calculator with expressions side by side to grasp the trade-off?