Arithmetic Expressions

Parsing arithmetic expressions with operator precedence

Arithmetic Expressions

This classic example demonstrates how grammar structure naturally enforces operator precedence and associativity without explicit precedence declarations.

Try It

Edit the expression below and click Run to see the parse tree:

How Precedence Works

The grammar structure enforces precedence through nesting:

Rule Operators Precedence
Expr + - Lowest
Term * / Higher
Factor ( ) Highest

Parse Tree Structure

For the input 1 + 2 * 3, notice how the parse tree groups 2 * 3 as a Term before adding 1:

Expr
├── Expr
│   └── Term
│       └── Factor
│           └── NUMBER: "1"
├── "+"
└── Term
    ├── Term
    │   └── Factor
    │       └── NUMBER: "2"
    ├── "*"
    └── Factor
        └── NUMBER: "3"

Left Associativity

The grammar uses left-recursion (Expr -> Expr "+" Term), which makes operators left-associative. For 1 - 2 - 3, this means (1 - 2) - 3 = -4, not 1 - (2 - 3) = 2.

Example Expressions

Try these expressions:

  • 1 + 2 + 3 - Left associative addition
  • 10 - 3 - 2 - Left associative subtraction
  • 2 * 3 + 4 - Multiplication before addition
  • (2 + 3) * 4 - Parentheses override precedence
  • 2 * (3 + 4) - Parentheses change evaluation order