Pratt Parsers: Expression Parsing Made Easy (2011)

Pratt Parsers: Expression Parsing Made Easy
Pratt or “top-down operator precedence” parsers are a clever solution to parsing expressions in a programming language. Recursive descent is easy for parsing declarations and statements, but it becomes challenging when dealing with expressions that contain infix, postfix, and mixfix operators. Pratt parsing solves this problem by providing a simple and readable approach to handle operator precedence. Unfortunately, Pratt’s technique is not well-known, and there are few modern articles about it. This article aims to explain the core concepts behind Pratt parsing in a clear and understandable manner by building a parser for a toy language called Bantam. The parser will handle variable names, prefix operators, infix operators, postfix operators, and even mixfix expressions. The implementation of this parser is in Java, a language known for its verbosity. The article breaks down the parser into smaller steps to make it easier to understand. By the end, the parser can handle complex nested expressions correctly with the right precedence and associativity. The author has found Pratt parsers to be a great fit for their projects and now prefers using this technique for parsing.

https://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/

To top