Files
rexlang/docs/12-calculator-walkthrough.md
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

2.8 KiB

12. A real program: the calculator

The folder examples/calc/ holds a calculator split over five files. It uses almost everything from these notes. Run it:

cargo run -q -- run examples/calc/main.rex examples/calc/session.txt

or type calculations interactively by leaving off the file name.

1 + 2 * 3          = 7.0
2 ^ 3 ^ 2          = 512.0
x = 4
x * 2 + pi         = 11.1415926535898
sqrt(16) + max(1, 5)

The pieces

File Job Features it shows
token.rex Turns text into tokens enums, structs, char, string slicing, errors
ast.rex The shape of a calculation an enum that holds other nodes
parser.rex Builds the tree a struct with methods, ?, recursion
eval.rex Computes the answer match, maps, function values, closures
main.rex Reads lines and prints import, os, shared

1. Tokens

"2 * (3 + 4)" becomes a list of small pieces: a number, an operator, an open parenthesis and so on. Each has a kind (an enum), its text and its position, so errors can say "at column 5".

The tokenizer looks at one character at a time (var c = src[i]) and decides what kind of token starts there: c.is_digit() starts a number, c.is_letter() a name, and so on. src[start..i] cuts the finished piece out of the text.

2. The tree

pub enum Node {
    Num(value: float)
    Var(name: string)
    Neg(inner: []Node)
    Bin(op: string, sides: []Node)
    Call(name: string, args: []Node)
    Assign(name: string, value: []Node)
}

An enum can't contain itself directly, so the parts that hold other nodes use a list ([]Node) with one or more items.

3. The parser

One method per level of precedence: sum calls product, which calls unary, which calls power, which calls atom. Each returns (Node, error) and the callers pass problems up with ?.

4. The evaluator

The scope that remembers variables and functions is two maps:

pub struct Scope {
    variables: map[string, float]
    builtins: map[string, Builtin]
    ...
}

A built-in function is a struct holding its name, how many arguments it takes, and a function value:

s.builtins["sqrt"] = Builtin{"sqrt", 1, a => math.sqrt(a[0])}

eval is one big match on the node. Looking up a variable is variables.get(name), which gives nil when it isn't there, turned into a friendly error.

5. The main file

The scope is created once as shared, so every line sees the variables set by the lines before it, with no need to pass the scope back and forth:

var scope = shared eval.new_scope()
...
run_line(scope, line)

Try changing it

  • Add a function sin(x) next to sqrt.
  • Add % as an operator in the tokenizer, parser and apply.
  • Make sum accept any number of arguments.

Next: C and C++ libraries