Skip to main content

Pratt Parser

What is a Pratt Parser?

A Pratt parser, also known as a Top-Down Operator Precedence parser, is an efficient parsing technique for expressions involving operators with different precedences. Unlike traditional recursive descent parsers, Pratt parsers use a central table to control operator precedence and associativity, making them both compact and flexible.

How Does It Work?

  • Operates recursively, similar to recursive descent, but with fewer methods.
  • Uses precedence tables to determine evaluation order.
  • Supports prefix, infix, and postfix operators, as well as different associativities.

Advantages

  • Compact and flexible implementation.
  • Precedence and associativity are data-driven and easy to adjust.
  • Well-suited for complex expressions with many operators.

Example (Pseudo-Code)

def parse_expression(precedence=0):
token = next_token()
left = parse_prefix(token)
while precedence < get_precedence(peek_next_token()):
token = next_token()
left = parse_infix(token, left)
return left

Comparison with Other Parsers

Parser Type

Features

Pratt Parser

Recursive, data-driven precedence, compact

Shunting Yard

Explicit stack, similar precedence handling

Recursive Descent

Many methods, less flexible

References