ce/eval.ml

29 lines
655 B
OCaml
Raw Normal View History

2022-01-10 01:31:47 +09:00
open Ast
exception Invalid_type
let arith intf a b =
2022-01-10 23:11:13 +09:00
match a, b with
| Int a, Int b -> Int (intf a b)
| _ -> raise Invalid_type
2022-01-10 01:31:47 +09:00
2022-01-10 23:11:13 +09:00
let binop_to_func = function
2022-01-11 01:05:29 +09:00
| Add -> arith Int.add
| Sub -> arith Int.sub
| Mul -> arith Int.mul
| Div -> arith Int.div
| Mod -> arith Int.rem
| _ -> assert false
2022-01-10 23:11:13 +09:00
let rec eval = function
| Value v -> v
2022-01-10 01:31:47 +09:00
| Binop (l, op, r) ->
let f = binop_to_func op in
f (eval l) (eval r)
| Set_binop_pre (op, l) ->
let l = match eval l with Int n -> n | _ -> raise Invalid_type in
2022-01-11 01:05:29 +09:00
Hashtbl.replace Parser.precedence op l;
2022-01-10 23:11:13 +09:00
Unit
2022-01-11 01:05:29 +09:00
| Get_binop_pre op ->
Int (Hashtbl.find Parser.precedence op)