Unit content
Pratt parsing and expression precedence
Expression grammars need to decide how operators group. A Pratt parser handles this by assigning operators binding strengths and letting the parser decide how far an expression extends from those strengths.
Prefix and infix roles
A token can define how it starts an expression, such as unary -, and separately how it continues one, such as binary -.
Binding power
When parsing an infix operator, the parser compares its binding power with the surrounding context. Higher-binding operators are consumed inside the current expression before lower-binding operators.
This naturally parses
2 + 3 * 4
as
2 + (3 * 4)
without creating one grammar rule for every precedence level.
Associativity can be expressed by choosing slightly different left and right binding powers.
Pratt parsing is therefore a compact technique for expression languages with many prefix, postfix and infix operators.