Calculator

Building a working calculator with semantic actions

Calculator

This example shows a more advanced calculator grammar that supports variables, assignments, and function calls. The grammar defines operator precedence naturally through its structure.

Try It

Edit the input below and click Run to see the parse tree and computed result:

How It Works

Grammar Features

This calculator grammar supports:

  • Variables - Identifiers like x, y, total
  • Assignments - x = 10
  • Expressions - x + y * 2
  • Function calls - sin(x), max(a, b)
  • Operator precedence - * and / bind tighter than + and -

Evaluation

The evaluate function recursively walks the parse tree to compute numeric results. It maintains a symbol table for variables and supports built-in math functions.

Example Inputs

Try these inputs:

  • 1 + 2 * 3 - Basic arithmetic (result: 7)
  • x = 10 y = 20 x + y - Variables (result: 30)
  • sqrt(16) + abs(-5) - Function calls (result: 9)
  • sin(pi() / 2) - Trig functions (result: 1)
  • pow(2, 10) - Power function (result: 1024)
  • max(10, 20, 5) - Multi-argument function

Available Functions

sin, cos, tan, sqrt, abs, floor, ceil, round, log, exp, pow, min, max, pi, e