ce/eval.ml

25 lines
588 B
OCaml
Raw Normal View History

2022-01-10 01:31:47 +09:00
open Ast
2022-01-11 01:05:29 +09:00
let arith f a b =
2022-01-10 23:11:13 +09:00
match a, b with
| Int a, Int b -> Int (f a b)
| _ -> failwith "typecheck failed"
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
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) ->
2022-01-10 23:11:13 +09:00
let l = match eval l with Int n -> n | _ -> failwith "not int" 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)