Skip to content
md ~/writing/eval-kullanmadan-hesap-makinesi-ayristirici
All posts

· 5 min read

A Calculator Without eval: Writing a Recursive Descent Parser

A Calculator Without eval: Writing a Recursive Descent Parser

The shortest way to write a calculator in Python is one line: eval(expression). eval("2+3*4") returns 14, with operator precedence and parentheses already handled. But eval doesn't just run maths; it runs any Python code it is given. This post is about how I wrote my own recursive descent parser for my desktop calculator instead of using eval, how operator precedence falls naturally out of the grammar, and why malicious or broken input cannot crash the app.

Why not eval?

When the text a user types goes straight into eval, the calculator's input box becomes a Python console:

>>> eval("__import__('os').getcwd()")
'C:\\Users\\...'

The same box could take a line that deletes files or downloads something. One might say it's a desktop app, the user is on their own computer anyway; but the expression could come from a file, the clipboard or another program. Ways of restricting eval, like an empty __builtins__, have well-known escapes. The only safe way is to define the accepted language up front and reject everything outside it.

Two steps: split first, then understand

The parser works in two steps.

1. Tokenizing: the text is split into meaningful pieces: numbers, operators, parentheses, function names. "2 + sqrt(16)" → [2.0, "+", "sqrt", "(", 16.0, ")"]. The moment a character that is not allowed shows up, it stops:

else:
    raise ValueError(f"Geçersiz karakter: '{char}'")  # invalid character

__import__('os') is rejected right here, at the first character, _.

2. Parsing: the tokens are read and evaluated according to a grammar.

The grammar: precedence comes for free

The language the calculator accepts is defined by these rules. Each line maps to one function:

expression := term    (('+' | '-') term)*
term       := unary   (('*' | '/' | juxtaposition) unary)*
unary      := ('-' | '+') unary  |  power
power      := postfix ('^' unary)?
postfix    := primary ('!' | '%')*
primary    := number | '(' expression ')' | function '(' expression ')' | constant

Each rule calls the one below it, and the lower rule binds tighter: multiplication is read and finished before addition, because term is called inside expression. There is no separate precedence table; precedence falls out of the order in which the functions call each other.

The code is an almost one-to-one translation of the rules:

def parse_expression(self):
    result = self.parse_term()
    while self.peek() in ("+", "-"):
        operator = self.advance()
        right = self.parse_term()
        # ...
        if operator == "+":
            result += right
        else:
            result -= right
    return result

def parse_term(self):
    result = self.parse_unary()
    while self.peek() in ("*", "/") or self.is_implicit_multiplication():
        # ...

While reading 2 + 3 * 4, parse_expression first calls parse_term and gets 2. When it sees +, it reads the right side with parse_term again, which finishes 3 * 4 and returns 12. The result is 14.

Small decisions in the rules

Writing a grammar forces you to make decisions that usually go unnoticed:

What is -2^2? In maths, -4: power first, then the minus. The unary rule calls unary again after the minus, which calls power, so the power is computed first.

What is 2^3^2? Exponents associate right to left: 2^(3^2) = 512. The power rule reads the exponent with unary again, so the right-hand power finishes first.

What is 200 + 10%? The answer people expect from a calculator is 220: increase 200 by 10 percent of it. On its own the percent sign divides by 100, so 50 * 10% = 5; in addition and subtraction it becomes a percentage of the left side.

2pi and 2(3+4): a number, parenthesis or function written next to another counts as multiplication, because that is how people type into a calculator.

>>> evaluate("-2^2"), evaluate("2^3^2"), evaluate("200+10%"), evaluate("2(3+4)")
(-4.0, 512.0, 220.0, 14.0)

Broken and malicious input

With my own parser, I also decide what happens to bad input. Python's own error messages, like unexpected EOF while parsing, mean nothing to a user, so every error is turned into a clear Turkish message:

  • 10/0 → Division by zero is not possible
  • sqrt(-4) → Cannot take the square root of a negative number
  • 1,00+2 → Invalid number: 1,00. A dot is used for decimals; a comma is accepted only as a thousands separator, as in 1,000.

Then there is very deep nesting. A recursive descent parser calls itself once more for every parenthesis. Thousands of nested parentheses exceed Python's recursion limit and raise RecursionError. If it is not caught the app crashes, and malicious or broken input can trigger that easily. The error is caught at the outermost level of parsing and turned into a clear message:

def evaluate(expression, degrees=False):
    tokens = tokenize(expression)
    if not tokens:
        raise ValueError("Boş ifade")  # empty expression
    parser = Parser(tokens, degrees)
    try:
        result = parser.parse_expression()
    except RecursionError:
        raise ValueError("İfade çok karmaşık")  # expression too complex
    if parser.peek() is not None:
        raise ValueError(f"Beklenmeyen ifade: '{parser.peek()}'")  # unexpected token
    return check_finite(result)

The last two lines matter too: if the expression ends but unread tokens remain, like 2 + 3), they are not silently ignored; it is an error. check_finite also keeps overflows such as 10^1000 from showing up on screen as inf.

Why recursive descent?

The well-known alternative is Dijkstra's shunting-yard algorithm: it holds operators on a stack according to a precedence table and turns the expression into postfix notation. That works too. I chose recursive descent because:

  • The code mirrors the grammar; reading a rule means reading its function.
  • Adding an operator means touching one function. Factorial and percent were added to the postfix rule in two lines.
  • The error message is raised exactly where the error is, for example ) expected.

What I took away

  • Text typed by a user should never run as code. Define the accepted language and reject the rest. Security starts from what do I allow, not what do I block.
  • Writing a grammar makes hidden decisions visible. The answers for -2^2, 2^3^2 and 200+10% are written explicitly in the code.
  • Recursion consumes a resource. Any recursive code whose depth the user controls has to expect that limit to be hit.
  • When parsing ends, the input must end too. Leftover tokens are not something to ignore silently; they are an error.