Hacker News Viewer

Intuiting Pratt Parsing

by signa11 on 3/30/2026, 12:31:52 PM

https://louis.co.nz/2026/03/26/pratt-parsing.html

Comments

by: logdahl

Love Pratt parsing! Not a compiler guy, but I&#x27;ve spent way too many hours reflecting on parsing. I remember trying to get though the dragon book so many times and reading all about formal grammar etc. Until I landed on; recursive descent parsing + Pratt for expressions. Super simple technique, and for me is sufficient. I&#x27;m sure it doesn&#x27;t cover all cases, but just for toy languages it feels like we can usually do everything with 2-token lookahead.<p>Not to step on anyone&#x27;s toes, I just don&#x27;t feel that formal grammar theory is that important in practice. :^)

4/1/2026, 10:58:26 AM


by: svat

&gt; <i>I’ve read many articles on the same topic but never found it presented this way - hopefully N + 1 is of help to someone.</i><p>Can confirm; yes it was helpful! I&#x27;ve never thought seriously about parsing and I&#x27;ve read occasionally (casually) about Pratt parsing, but this is the first time it seemed like an intuitive idea I&#x27;ll remember.<p>(Then I confused myself by following some references and remembering the term &quot;precedence climbing&quot; and reading e.g. <a href="https:&#x2F;&#x2F;www.engr.mun.ca&#x2F;~theo&#x2F;Misc&#x2F;pratt_parsing.htm" rel="nofollow">https:&#x2F;&#x2F;www.engr.mun.ca&#x2F;~theo&#x2F;Misc&#x2F;pratt_parsing.htm</a> by the person who coined that term, but nevermind — the original post here has still given me an idea I think I&#x27;ll remember.)

4/1/2026, 12:17:52 PM


by: randomNumber7

I can recommend anyone reading pratts original paper. Its written in a very cool and badass style.<p><a href="https:&#x2F;&#x2F;dl.acm.org&#x2F;doi&#x2F;epdf&#x2F;10.1145&#x2F;512927.512931" rel="nofollow">https:&#x2F;&#x2F;dl.acm.org&#x2F;doi&#x2F;epdf&#x2F;10.1145&#x2F;512927.512931</a>

4/1/2026, 11:43:35 AM


by: hyperhello

You can either use the stack in an intuitive way, or you can change the tree directly in a somewhat less intuitive way without recursion. Essentially either DF or BF. I don’t see how it matters much anymore with stacks that grow automatically, but it’s good to understand.

4/1/2026, 12:05:30 PM


by: priceishere

An even simpler way imo, is explicit functions instead of a precedence table, then the code pretty much has the same structure as EBNF.<p>Need to parse * before +? Begin at add, have it call parse_mul for its left and right sides, and so on.<p><pre><code> parse_mul() { left = parse_literal() while(is_mul_token()) { &#x2F;&#x2F; left associative right = parse_literal() make_mul_node(left, right) } } parse_add() { left = parse_mul() while(is_add_token()) { &#x2F;&#x2F; left associative right = parse_mul() make_add_node(left, right) } } </code></pre> Then just add more functions as you climb up the precedence levels.

4/1/2026, 11:24:38 AM