codehs-sandbox

All programs / overengineered-calculatoe

overengineered-calculatoe

A lexer, parser and tree-walking interpreter for arithmetic

Run the calculator

On CodeHS, readLine pops up a prompt. Here, what you type goes to that same call, and the program runs fresh each time.

What it does

It reads one line of arithmetic, then lexes it into tokens, parses the tokens into a syntax tree, and interprets the tree to get the answer. It handles integers and decimals, + − * / ^, parentheses and unary signs.

The interesting idea

Recursive descent, with one function per precedence level. Lower-precedence functions call higher ones, so the tree comes out the right shape without any precedence table:

  • expression: + and −, looping left to right (left-associative)
  • term: * and /, also a left-to-right loop
  • unary: a leading + or −, which calls itself so --3 works
  • exponent: ^, whose right side goes back up to unary. That makes 2^3^2 mean 2^(3^2) = 512, and lets 2^-1 parse.
  • factor: a number, or a whole parenthesised expression

Because unary sits above exponent, -2^2 is -(2^2) = -4, the same convention mathematicians use. The lexer is a switch (true) over character tests. The parser uses the classic peek/eat pair and checks for EOF so trailing junk is a syntax error. The interpreter is a recursive evaluate(node).

Error messages are the program’s own, rude ones included. Try 1.5.2 or 7 % 2.

Original source

The file exactly as saved on CodeHS, read-only. Open the raw file.

Checking SHA-256…

Evidence: CodeHS history

Screenshots of CodeHS’s “My Code History” page, which logs every save with a timestamp and the reason for it (autosave, run, paste).