Hacker News new | ask | show | jobs
by amelius 4039 days ago
Why not hard-code the operator precedence into the BNF? Like the K&R book does it.
1 comments

If you're using something that generates a parser for you—like bison or yacc—then sure, you can express your grammar like that, and there are advantages to doing so. On the other hand, if you don't have something like that available—say, you're working in a language where nobody has written a yacc clone yet, so there's no way for you to generate a parser from a BNF description—then implementing a Pratt parser is a lot easier than implementing a parser generator.

Even if you have alternatives, there are still situations in which you might want to use a Pratt parser. It's much easier to understand the internals of this kind of parser than understand the shift/reduce rules of an LL(k) grammar, and Pratt parsers have the nice property that you can easily modify them at runtime, making it easy to switch to alternate grammars in particular contexts—e.g., directly parsing SQL within particular delimiters is a pretty trivial task that is somewhat more difficult with a BNF-style grammar.

EDIT: Actually, a better final example would be user-defined operators with arbitrary precedence and branching. There is no way of expressing this directly in a BNF-style grammar, but it is trivial with a Pratt parser.