Writing about pratt parsing so I remember it
Posted by dverlaeckt80 2 days ago
Comments
Comment by mjbq 1 day ago
Nom may seem quite verbose. I have written another language (which compiles to nom) which I call Syntagma. The syntax of syntagma is much closer to EBNF but also has powerful additions, such as a "lookahead" syntax, a negated lookahead syntax (eg: "parse this as an expression if it is not followed by a multiply operator"). Also, Syntagma has a "condition" syntax, meaning that a parse rule will only reduce if the attributes of the parse tokens match certain conditions.
An example of an expression parser written in Syntagma is at http://www.nomlang.org/syntagma/eg/expr.sta This is much more succinct than the equivalent nom script. The script /syntagma/eg/expr.toforth.sta converts symbolic expressions (and assignments) into Forth.
Parsing is an interesting topic, but I feel that it is quite difficult or non-intuitive with some of the traditional tools and methods (at least for me).
Comment by jstanley 1 day ago
A recursive descent parser makes much more sense to me.
Comment by throw-qqqqq 1 day ago
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.
Comment by dunham 1 day ago
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.)
Comment by marssaxman 13 hours ago
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.
Comment by throw-qqqqq 10 hours ago
Totally agree!
Comment by bonzini 1 day ago
Comment by arnsholt 1 day ago
Comment by throw-qqqqq 1 day ago
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.