Pratt Parsing (Top-Down Operator Precedence Parsing)

Since we're building Apex, Pratt Parsing is one of the most useful parsing techniques you'll encounter. Many modern interpreters, compilers, and language tools use a Pratt-style parser for expressions because it is much simpler than writing huge recursive-descent grammars for operators.


The Problem Pratt Parsing Solves

Consider this expression:

1 + 2 * 3

Humans know it means:

1 + (2 * 3)

because * has higher precedence than +.

Now consider:

1 + 2 * 3 - 4 / 2

Different operators have:

A parser must understand all of this.


Traditional Recursive Descent

Without Pratt Parsing, you often write:

expression
 └── term
      └── factor
           └── primary

Example grammar: