ce/ast.ml

78 lines
1.9 KiB
OCaml
Raw Normal View History

2022-02-01 21:38:00 +09:00
(* simple, untyped AST. *)
type t =
| Nint of int
| Nfloat of float
| Nstring of string
2022-02-08 00:26:03 +09:00
| Nsymbol of string
| Nfunction of string list * t
| Nexternal of string
2022-02-01 21:38:00 +09:00
| Var of string
| Let of string * t
| Unary of operator * t
| Binop of t * operator * t
| Apply of t * t list (* function application *)
2022-02-07 23:12:11 +09:00
(* these will be seperated into (toplevel) directives. *)
2022-02-01 21:38:00 +09:00
| Set_binop_pre of operator * t
| Get_binop_pre of operator
| Set_binop_aso of operator * string
| Get_binop_aso of operator
and operator =
| Add | Sub | Mul | Div (* arithmetics *)
| Mod (* modular operation *)
| Exp (* exponentation *)
| Negate
2022-02-07 23:12:11 +09:00
let op_to_string = function
| Add -> "+"
| Sub -> "-"
| Mul -> "*"
| Div -> "/"
| Mod -> "%"
| Exp -> "^"
| Negate -> "-"
2022-01-10 01:31:47 +09:00
2022-01-23 01:20:34 +09:00
let unary op t =
Unary (op, t)
2022-01-10 01:31:47 +09:00
let binop left op right =
Binop (left, op, right)
(* print ast LISP style. *)
let print ast =
let pr = Printf.printf in
2022-01-10 23:11:13 +09:00
let rec aux = function
| Nint n -> pr "%d" n
| Nfloat n -> pr "%f" n
| Nstring s -> pr "\"%s\"" s
2022-02-08 00:26:03 +09:00
| Nsymbol s -> pr "#%s" s
| Nfunction (args, e) ->
pr "lambda (%s" @@ List.hd args;
List.iter (pr " %s") @@ List.tl args;
pr ") ("; aux e; pr")"
| Nexternal e -> pr "(extern %s)" e
2022-01-19 14:17:04 +09:00
| Var v -> pr "%s" v
2022-01-21 00:17:01 +09:00
| Let (v, e) ->
2022-01-29 20:01:48 +09:00
pr "(let %s " v; aux e; pr ")"
| Unary (op, t) ->
2022-02-07 23:12:11 +09:00
let op = op_to_string op in
2022-02-01 21:38:00 +09:00
pr "(%s " op; aux t; pr ")"
2022-01-29 20:01:48 +09:00
| Binop (left, op, right) ->
2022-02-07 23:12:11 +09:00
let op = op_to_string op in
2022-02-01 21:38:00 +09:00
pr "(%s " op; aux left; pr " "; aux right; pr ")"
2022-01-29 20:01:48 +09:00
| Apply (f, args) ->
pr "("; List.iter aux @@ f::args; pr ")"
2022-01-10 01:31:47 +09:00
| Set_binop_pre (op, pre) ->
2022-02-07 23:12:11 +09:00
pr "(set_pre %s " (op_to_string op);
2022-01-10 01:31:47 +09:00
aux pre;
pr ")"
2022-01-11 01:05:29 +09:00
| Get_binop_pre op ->
2022-02-07 23:12:11 +09:00
pr "(get_pre %s)" (op_to_string op)
2022-01-20 23:36:53 +09:00
| Set_binop_aso (op, aso) ->
2022-02-07 23:12:11 +09:00
pr "(set_assoc %s %s)" (op_to_string op) aso
2022-01-20 23:36:53 +09:00
| Get_binop_aso op ->
2022-02-07 23:12:11 +09:00
pr "(get_pre %s)" (op_to_string op)
2022-01-10 01:31:47 +09:00
in
aux ast; pr "\n"