ce/ast.ml

59 lines
1.2 KiB
OCaml
Raw Normal View History

2022-01-10 23:11:13 +09:00
type typ =
| Int of int
2022-01-18 15:33:56 +09:00
| Float of float
2022-01-10 23:11:13 +09:00
| Unit
2022-01-10 01:31:47 +09:00
2022-01-10 23:11:13 +09:00
let typ_to_string = function
2022-01-10 01:31:47 +09:00
| Int n -> Printf.sprintf "%d" n
2022-01-18 15:33:56 +09:00
| Float n -> Printf.sprintf "%f" n
2022-01-10 01:31:47 +09:00
| Unit -> "()"
2022-01-10 23:11:13 +09:00
type binop =
| Add | Sub | Mul | Div (* arithmetics *)
| Mod (* modular operation *)
| Exp (* exponentation *)
2022-01-10 01:31:47 +09:00
2022-01-10 23:11:13 +09:00
let binop_to_string = function
2022-01-10 01:31:47 +09:00
| Add -> "+"
| Sub -> "-"
| Mul -> "*"
| Div -> "/"
| Mod -> "%"
| Exp -> "^"
2022-01-10 01:31:47 +09:00
2022-01-10 23:11:13 +09:00
type t =
| Value of typ
| Binop of t * binop * t
| Set_binop_pre of binop * t
2022-01-11 01:05:29 +09:00
| Get_binop_pre of binop
2022-01-10 01:31:47 +09:00
let value v = Value v
let binop left op right =
Binop (left, op, right)
let set_binop_pre op pre =
Set_binop_pre (op, pre)
(* print ast LISP style. *)
let print ast =
let pr = Printf.printf in
let pv v = pr "%s" @@ typ_to_string v in
2022-01-10 23:11:13 +09:00
let rec aux = function
2022-01-10 01:31:47 +09:00
| Value n -> pv n
| Binop (left, op, right) -> begin
pr "(%s " @@ binop_to_string op;
aux left;
pr " ";
aux right;
pr ")";
end
| Set_binop_pre (op, pre) ->
pr "(set_pre %s " (binop_to_string op);
aux pre;
pr ")"
2022-01-11 01:05:29 +09:00
| Get_binop_pre op ->
pr "(get_pre %s)" (binop_to_string op)
2022-01-10 01:31:47 +09:00
in
aux ast; pr "\n"