Hacker News
points by throw-qqqqq 3 days ago | 0 comments
For me, the win is that a Pratt parser is more data-driven.

It’s easy to look at a table or map of operators and their precedence and convince myself that it’s correct. A recursive descent parser needs to be very clearly structured to have similar clarity, IMO.

You can easily combine Pratt parsing with recursive descent, using the Pratt part only for expressions. FWIW, this is my favorite approach for parsing C.

[–] dunham 2 days ago
The table-driven aspect is nice when you have user defined operators. I've used it inside a combinator based parser for a language with mixfix operators (e.g. _≡⟨_⟩_ ).

Lean4 takes this to an extreme and has "syntax categories" (e.g. expression), each of which has something like a pratt parser. Ambiguity is broken by taking the option that makes the most progress, and it is made efficient by memoization. You can add syntax at compile time, down to the lexing level. There is an example that adds HTML-like syntax and uses it later in the same file.

https://github.com/leanprover/lean4/blob/0f2eaa6e776255083f9...

(I'm not saying changing the language on the fly is a good idea, but it's interesting that they pulled it off.)

[–] bonzini 3 days ago
Pratt parsing, in its simplest form, is essentially an optimized recursive descent that uses lookahead to skip levels. Which as you say ends up being clearer too.
[–] marssaxman 1 day ago
That is my favorite approach for parsing any language which has operator precedence. It is easy to write, easy to maintain, performs well, and doesn't require you to include extra tools in your build process.

I know some people love their parser generator tools, but I just don't find them to be worth the hassle; parsing is not a hard problem.

[–] throw-qqqqq 1 day ago
> I know some people love their parser generator tools, but I just don't find them to be worth the hassle

Totally agree!

[–] arnsholt 3 days ago
Yeah, for “normal” syntax I’d generally go for recursive descent, but for expression parsing with operator precedence I’d implement Pratt parsing if I had any say in the matter.
[–] throw-qqqqq 3 days ago
I think of it as expressions vs statements, but I think we agree.

Lexing for tokenization -> recursive descent for statements -> Pratt parsing for expressions.

S-Expressions and prefix-notation are so easy to work with (compared to in-fix IMO), because the precedence is explicit.