2022-01-10 01:31:47 +09:00
|
|
|
open Ast
|
2022-01-18 16:52:33 +09:00
|
|
|
open Ast.Value
|
2022-01-10 01:31:47 +09:00
|
|
|
|
2022-01-18 16:52:33 +09:00
|
|
|
exception No_operation
|
2022-01-19 14:17:04 +09:00
|
|
|
exception No_such_variable of string
|
2022-01-13 01:13:41 +09:00
|
|
|
|
2022-01-18 16:52:33 +09:00
|
|
|
let rec binop op l r =
|
|
|
|
let tl = typeof l and tr = typeof r in
|
|
|
|
let ty = Type.merge tl tr in
|
|
|
|
let rec promote_until t x =
|
|
|
|
if typeof x = t
|
|
|
|
then x
|
|
|
|
else promote_until t (promote x)
|
|
|
|
in
|
|
|
|
let l = promote_until ty l
|
|
|
|
and r = promote_until ty r in
|
|
|
|
match Binop.get op ty with
|
|
|
|
| None -> begin
|
|
|
|
try binop op (promote l) (promote r)
|
|
|
|
with _ -> raise No_operation
|
2022-01-18 15:33:56 +09:00
|
|
|
end
|
2022-01-18 16:52:33 +09:00
|
|
|
| Some f -> f l r
|
2022-01-10 23:11:13 +09:00
|
|
|
|
2022-01-20 01:35:18 +09:00
|
|
|
let eval vars ast =
|
2022-01-19 14:17:04 +09:00
|
|
|
let rec aux = function
|
|
|
|
| Value v -> v
|
2022-01-20 01:35:18 +09:00
|
|
|
| Var v -> begin match Hashtbl.find_opt vars v with
|
|
|
|
| None -> raise @@ No_such_variable v
|
|
|
|
| Some v -> v
|
|
|
|
end
|
2022-01-23 01:20:34 +09:00
|
|
|
| Unary (op, t) ->
|
|
|
|
let t = aux t in
|
|
|
|
let op = Unary.get op (Value.typeof t) in
|
|
|
|
op t
|
2022-01-19 14:17:04 +09:00
|
|
|
| Binop (l, op, r) ->
|
|
|
|
let l = aux l and r = aux r in
|
|
|
|
binop op l r
|
2022-01-21 00:17:01 +09:00
|
|
|
| Let (var, e) ->
|
|
|
|
let v = aux e in
|
|
|
|
Hashtbl.replace vars var v;
|
|
|
|
v
|
2022-01-19 14:17:04 +09:00
|
|
|
| Set_binop_pre (op, l) ->
|
|
|
|
let l =
|
|
|
|
match aux l with
|
|
|
|
| Int n -> n
|
|
|
|
| v -> raise @@ Invalid_type (typeof v)
|
|
|
|
in
|
|
|
|
Hashtbl.replace Parser.precedence op l;
|
|
|
|
Nop
|
|
|
|
| Get_binop_pre op ->
|
|
|
|
Int (Hashtbl.find Parser.precedence op)
|
2022-01-20 23:36:53 +09:00
|
|
|
| Set_binop_aso (op, a) ->
|
|
|
|
Hashtbl.replace Parser.oper_assoc op @@ Parser.assoc_of_string a;
|
|
|
|
Nop
|
|
|
|
| Get_binop_aso op ->
|
|
|
|
match Hashtbl.find_opt Parser.oper_assoc op with
|
|
|
|
| None -> String "left"
|
|
|
|
| Some a -> String (Parser.assoc_to_string a)
|
2022-01-19 14:17:04 +09:00
|
|
|
in
|
|
|
|
aux ast
|