The Personal Website of Jeremy Boles

Pratt Parser

Top-down operator precedence, and the easiest parser to write by hand.

A Pratt parser gives every token a binding power and then loops: take a prefix, then keep absorbing infix operators for as long as their binding power says you may. That’s most of it. No grammar to write down, no table to generate, which is why it’s the one parsing technique I can rebuild from memory.

Napkin’s core is one. I’d written a Pratt parser once before, so when I started Napkin over the Atlantic I carved that project’s core out into a shared library for the new one to stand on and rebuilt the rest from what I remembered. Five or six hours later the little language mostly worked.

The style suits what Napkin needs. Every line has to either produce a value or produce nothing, and it must never show an error, which means the parser has to be forgiving to a fault: unknown words are filler, and the last complete fragment on a line wins. That’s far easier to arrange when precedence lives in the tokens than when it lives in a grammar you have to make permissive on purpose.