OCaml Mini Project
In this project you will build a calculator language, step by step: a tokenizer, a parser and an evaluator, with variables, functions and helpful error messages. It is a small version of what compilers do, and it uses much of the course: variants, records, pattern matching, recursion, Map, result and let*.
By the end, the calculator runs sessions like this:
> let r = 2.5
r = 2.5
> let area = 3.14159 * r ^ 2
area = 19.6349
> max(area, 20) / (1 - 1)
error: division by zeroEvery step is a complete program you can run and change. Because the playground cannot read keyboard input, the "user" is simulated by a list of input lines. In a terminal you would read them with In_channel.input_line stdin in a loop.
Step 1: The syntax tree
First, decide what an expression is. A variant type describes every kind of expression, and eval and to_string follow its shape:
type binop = Add | Sub | Mul | Div | Pow
type expr =
| Num of float
| Neg of expr
| Binop of binop * expr * expr
let rec eval = function
| Num f -> f
| Neg e -> -.eval e
| Binop (op, a, b) -> (
let x = eval a and y = eval b in
match op with Add -> x +. y | Sub -> x -. y | Mul -> x *. y | Div -> x /. y | Pow -> x ** y)
let symbol = function Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Pow -> "^"
let rec to_string = function
| Num f -> Printf.sprintf "%g" f
| Neg e -> "-" ^ to_string e
| Binop (op, a, b) -> "(" ^ to_string a ^ " " ^ symbol op ^ " " ^ to_string b ^ ")"
let () =
(* (1 + 2) * -3 ^ 2, written by hand as a tree *)
let e = Binop (Mul, Binop (Add, Num 1., Num 2.), Neg (Binop (Pow, Num 3., Num 2.))) in
Printf.printf "%s = %g\n" (to_string e) (eval e)((1 + 2) * -(3 ^ 2)) = -27
Writing trees by hand is tedious. The next two steps turn text into trees automatically.
Step 2: The tokenizer
A tokenizer (lexer) cuts the input string into tokens: numbers, names and symbols. Spaces are skipped. Unknown characters produce an Error with the position:
type token =
| NUM of float | IDENT of string
| PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS
let show_token = function
| NUM f -> Printf.sprintf "%g" f | IDENT s -> s
| PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
| LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="
let tokenize s =
let n = String.length s in
let rec scan p i = if i < n && p s.[i] then scan p (i + 1) else i in
let is_digit c = (c >= '0' && c <= '9') || c = '.' in
let is_ident c = match c with 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> true | _ -> false in
let rec go i acc =
if i >= n then Ok (List.rev acc)
else
let single tok = go (i + 1) (tok :: acc) in
match s.[i] with
| ' ' | '\t' -> go (i + 1) acc
| '+' -> single PLUS | '-' -> single MINUS | '*' -> single STAR | '/' -> single SLASH
| '^' -> single CARET | '(' -> single LPAREN | ')' -> single RPAREN
| ',' -> single COMMA | '=' -> single EQUALS
| '0' .. '9' | '.' -> (
let j = scan is_digit i in
let text = String.sub s i (j - i) in
match float_of_string_opt text with
| Some f -> go j (NUM f :: acc)
| None -> Error (Printf.sprintf "bad number %S at position %d" text i))
| 'a' .. 'z' | 'A' .. 'Z' | '_' ->
let j = scan is_ident i in
go j (IDENT (String.sub s i (j - i)) :: acc)
| c -> Error (Printf.sprintf "unexpected character '%c' at position %d" c i)
in
go 0 []
let () =
List.iter
(fun input ->
match tokenize input with
| Ok toks -> Printf.printf "%-18s -> %s\n" input (String.concat " | " (List.map show_token toks))
| Error msg -> Printf.printf "%-18s -> error: %s\n" input msg)
[ "1 + 2*3"; "let rate = 0.25"; "max(x, 10)^2"; "4 % 2"; "1.2.3" ]1 + 2*3 -> 1 | + | 2 | * | 3
let rate = 0.25 -> let | rate | = | 0.25
max(x, 10)^2 -> max | ( | x | , | 10 | ) | ^ | 2
4 % 2 -> error: unexpected character '%' at position 2
1.2.3 -> error: bad number "1.2.3" at position 0
Step 3: The parser
The parser turns a token list into a tree, respecting precedence: ^ binds tighter than * and /, which bind tighter than + and -. A classic recursive descent parser has one function per precedence level. Each function returns the parsed expression together with the remaining tokens:
expr := term (('+' | '-') term)*
term := unary (('*' | '/') unary)*
unary := '-' unary | power
power := atom ('^' unary)? right-associative: 2^3^2 = 2^(3^2)
atom := number | name | name '(' args ')' | '(' expr ')'type token =
| NUM of float | IDENT of string
| PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS
let show_token = function
| NUM f -> Printf.sprintf "%g" f | IDENT s -> s
| PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
| LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="
type binop = Add | Sub | Mul | Div | Pow
type expr =
| Num of float
| Var of string
| Neg of expr
| Binop of binop * expr * expr
| Call of string * expr list
exception Syntax_error of string
let rec parse_expr toks =
let rec loop lhs = function
| PLUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Add, lhs, rhs)) rest
| MINUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Sub, lhs, rhs)) rest
| rest -> (lhs, rest)
in
let lhs, rest = parse_term toks in
loop lhs rest
and parse_term toks =
let rec loop lhs = function
| STAR :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Mul, lhs, rhs)) rest
| SLASH :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Div, lhs, rhs)) rest
| rest -> (lhs, rest)
in
let lhs, rest = parse_unary toks in
loop lhs rest
and parse_unary = function
| MINUS :: rest -> let e, rest = parse_unary rest in (Neg e, rest)
| toks -> parse_power toks
and parse_power toks =
match parse_atom toks with
| base, CARET :: rest -> let exp, rest = parse_unary rest in (Binop (Pow, base, exp), rest)
| result -> result
and parse_atom = function
| NUM f :: rest -> (Num f, rest)
| IDENT name :: LPAREN :: rest -> let args, rest = parse_args rest in (Call (name, args), rest)
| IDENT name :: rest -> (Var name, rest)
| LPAREN :: rest -> (
match parse_expr rest with
| e, RPAREN :: rest -> (e, rest)
| _ -> raise (Syntax_error "expected ')'"))
| tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "'"))
| [] -> raise (Syntax_error "unexpected end of input")
and parse_args toks =
let first, rest = parse_expr toks in
match rest with
| COMMA :: rest -> let others, rest = parse_args rest in (first :: others, rest)
| RPAREN :: rest -> ([ first ], rest)
| _ -> raise (Syntax_error "expected ',' or ')' in arguments")
let parse toks =
match parse_expr toks with
| e, [] -> e
| _, tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "' after expression"))
let symbol = function Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Pow -> "^"
let rec to_string = function
| Num f -> Printf.sprintf "%g" f
| Var x -> x
| Neg e -> "-" ^ to_string e
| Binop (op, a, b) -> "(" ^ to_string a ^ " " ^ symbol op ^ " " ^ to_string b ^ ")"
| Call (f, args) -> f ^ "(" ^ String.concat ", " (List.map to_string args) ^ ")"
let () =
(* token lists written by hand here; step 4 connects the tokenizer *)
let examples =
[ [ NUM 1.; PLUS; NUM 2.; STAR; NUM 3. ];
[ NUM 2.; CARET; NUM 3.; CARET; NUM 2. ];
[ MINUS; NUM 2.; CARET; NUM 2. ];
[ NUM 10.; MINUS; NUM 4.; MINUS; NUM 3. ];
[ IDENT "max"; LPAREN; IDENT "x"; COMMA; NUM 1.; PLUS; NUM 1.; RPAREN ];
[ LPAREN; NUM 1.; PLUS; NUM 2. ];
[ NUM 1.; NUM 2. ] ]
in
List.iter
(fun toks ->
let src = String.concat " " (List.map show_token toks) in
match parse toks with
| e -> Printf.printf "%-22s => %s\n" src (to_string e)
| exception Syntax_error msg -> Printf.printf "%-22s => syntax error: %s\n" src msg)
examples1 + 2 * 3 => (1 + (2 * 3))
2 ^ 3 ^ 2 => (2 ^ (3 ^ 2))
- 2 ^ 2 => -(2 ^ 2)
10 - 4 - 3 => ((10 - 4) - 3)
max ( x , 1 + 1 ) => max(x, (1 + 1))
( 1 + 2 => syntax error: expected ')'
1 2 => syntax error: unexpected '2' after expression
The fully parenthesised output proves the precedence rules: * before +, ^ grouping to the right, and - grouping to the left (10 - 4 - 3 is (10 - 4) - 3 = 3, not 10 - (4 - 3) = 9).
Step 4: Evaluation with variables, functions and errors
Now the evaluator. Variables live in an immutable Map (the environment), built-in functions are looked up by name, and every failure becomes a value of a precise error variant. Evaluation returns a result, and let* chains the steps. The parser still uses an exception internally, but calculate converts it, so callers only ever see result:
type token =
| NUM of float | IDENT of string
| PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS
let show_token = function
| NUM f -> Printf.sprintf "%g" f | IDENT s -> s
| PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
| LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="
let tokenize s =
let n = String.length s in
let rec scan p i = if i < n && p s.[i] then scan p (i + 1) else i in
let is_digit c = (c >= '0' && c <= '9') || c = '.' in
let is_ident c = match c with 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> true | _ -> false in
let rec go i acc =
if i >= n then Ok (List.rev acc)
else
let single tok = go (i + 1) (tok :: acc) in
match s.[i] with
| ' ' | '\t' -> go (i + 1) acc
| '+' -> single PLUS | '-' -> single MINUS | '*' -> single STAR | '/' -> single SLASH
| '^' -> single CARET | '(' -> single LPAREN | ')' -> single RPAREN
| ',' -> single COMMA | '=' -> single EQUALS
| '0' .. '9' | '.' -> (
let j = scan is_digit i in
let text = String.sub s i (j - i) in
match float_of_string_opt text with
| Some f -> go j (NUM f :: acc)
| None -> Error (Printf.sprintf "bad number %S at position %d" text i))
| 'a' .. 'z' | 'A' .. 'Z' | '_' ->
let j = scan is_ident i in
go j (IDENT (String.sub s i (j - i)) :: acc)
| c -> Error (Printf.sprintf "unexpected character '%c' at position %d" c i)
in
go 0 []
type binop = Add | Sub | Mul | Div | Pow
type expr = Num of float | Var of string | Neg of expr | Binop of binop * expr * expr | Call of string * expr list
exception Syntax_error of string
let rec parse_expr toks =
let rec loop lhs = function
| PLUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Add, lhs, rhs)) rest
| MINUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Sub, lhs, rhs)) rest
| rest -> (lhs, rest)
in
let lhs, rest = parse_term toks in
loop lhs rest
and parse_term toks =
let rec loop lhs = function
| STAR :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Mul, lhs, rhs)) rest
| SLASH :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Div, lhs, rhs)) rest
| rest -> (lhs, rest)
in
let lhs, rest = parse_unary toks in
loop lhs rest
and parse_unary = function
| MINUS :: rest -> let e, rest = parse_unary rest in (Neg e, rest)
| toks -> parse_power toks
and parse_power toks =
match parse_atom toks with
| base, CARET :: rest -> let exp, rest = parse_unary rest in (Binop (Pow, base, exp), rest)
| result -> result
and parse_atom = function
| NUM f :: rest -> (Num f, rest)
| IDENT name :: LPAREN :: rest -> let args, rest = parse_args rest in (Call (name, args), rest)
| IDENT name :: rest -> (Var name, rest)
| LPAREN :: rest -> (
match parse_expr rest with e, RPAREN :: rest -> (e, rest) | _ -> raise (Syntax_error "expected ')'"))
| tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "'"))
| [] -> raise (Syntax_error "unexpected end of input")
and parse_args toks =
let first, rest = parse_expr toks in
match rest with
| COMMA :: rest -> let others, rest = parse_args rest in (first :: others, rest)
| RPAREN :: rest -> ([ first ], rest)
| _ -> raise (Syntax_error "expected ',' or ')' in arguments")
let parse toks =
match parse_expr toks with
| e, [] -> e
| _, tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "' after expression"))
(* ---- new in this step ---- *)
module Env = Map.Make (String)
type error =
| Syntax of string
| Unbound_variable of string
| Unknown_function of string
| Bad_arguments of string
| Division_by_zero
let error_to_string = function
| Syntax msg -> "syntax error: " ^ msg
| Unbound_variable x -> "unknown variable '" ^ x ^ "'"
| Unknown_function f -> "unknown function '" ^ f ^ "'"
| Bad_arguments msg -> msg
| Division_by_zero -> "division by zero"
let ( let* ) = Result.bind
let call name args =
match (name, args) with
| "sqrt", [ x ] -> if x < 0. then Error (Bad_arguments "sqrt of a negative number") else Ok (sqrt x)
| "abs", [ x ] -> Ok (Float.abs x)
| ("max" | "min"), x :: rest -> Ok (List.fold_left (if name = "max" then Float.max else Float.min) x rest)
| ("sqrt" | "abs"), _ -> Error (Bad_arguments (name ^ " takes exactly 1 argument"))
| _ -> Error (Unknown_function name)
let rec eval env = function
| Num f -> Ok f
| Var x -> Option.to_result ~none:(Unbound_variable x) (Env.find_opt x env)
| Neg e -> let* v = eval env e in Ok (-.v)
| Binop (op, a, b) -> (
let* x = eval env a in
let* y = eval env b in
match op with
| Add -> Ok (x +. y)
| Sub -> Ok (x -. y)
| Mul -> Ok (x *. y)
| Div -> if y = 0. then Error Division_by_zero else Ok (x /. y)
| Pow -> Ok (x ** y))
| Call (f, args) ->
let* values = eval_all env args in
call f values
and eval_all env = function
| [] -> Ok []
| e :: rest ->
let* v = eval env e in
let* vs = eval_all env rest in
Ok (v :: vs)
let calculate env input =
let* toks = Result.map_error (fun m -> Syntax m) (tokenize input) in
let* tree = try Ok (parse toks) with Syntax_error m -> Error (Syntax m) in
eval env tree
let () =
let env = Env.(empty |> add "pi" Float.pi |> add "x" 4.) in
List.iter
(fun input ->
match calculate env input with
| Ok v -> Printf.printf "%-20s = %g\n" input v
| Error e -> Printf.printf "%-20s ! %s\n" input (error_to_string e))
[ "2 * pi * x"; "sqrt(x) + 2^-1"; "max(1, x, 3) - min(9, 2)"; "10 / (x - 4)"; "y + 1"; "sqrt(-x)";
"abs(1, 2)"; "log(10)"; "3 +"; "2 $ 3" ]2 * pi * x = 25.1327
sqrt(x) + 2^-1 = 2.5
max(1, x, 3) - min(9, 2) = 2
10 / (x - 4) ! division by zero
y + 1 ! unknown variable 'y'
sqrt(-x) ! sqrt of a negative number
abs(1, 2) ! abs takes exactly 1 argument
log(10) ! unknown function 'log'
3 + ! syntax error: unexpected end of input
2 $ 3 ! syntax error: unexpected character '